Search This Blog

Monday, January 22, 2018

Upgrade Site SharePoint 2010 to SharePoint 2013

Step :1 Save the below script  UpgradeSite.PS1 and map the .bat file and execute run with admin
-----------------------------------------------start-----------------------------------------

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$webApps = Get-SPWebApplication
foreach($webApp in $webApps)
{
$sites = $webApp.Sites
foreach($site in $sites)
{
Upgrade-SPSite $site.RootWeb.Url -VersionUpgrade -Unthrottled
$site.Dispose()
}
}


---------------------------------------end script----------------------------------------------------

Step bat file : Open notepad and Save UpgradeSite.bat below line
--------------------------------------------------------------------------------

cd /d %~dp0
powershell -noexit -file "UpgradeSite.PS1" "%CD%"
pause

Download all WSP file from Central Admin -SharePoint 2013

Step 1: Save below script  ExtractWSP.PS1 file
---------------------------------------------------start script------------------------

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$dirName = "F:\JaisonArumugam\WSP"
Write-Host Exporting solutions to $dirName
foreach ($solution in Get-SPSolution
    $id = $Solution.SolutionID
    $title = $Solution.Name
    $filename = $Solution.SolutionFile.Name
    Write-Host "Exporting '$title' to …\$filename" -nonewline 
    try
        $solution.SolutionFile.SaveAs("$dirName\$filename")
        Write-Host " – done" -foreground green 
    } 
    catch 
    { 
        Write-Host " – error : $_" -foreground red 
    }
}

--------------------------------------------------end script----------------------------------

Save .bat file and execute run with admin..


cd /d %~dp0
powershell -noexit -file "ExtractWSP.PS1" "%CD%"
pause



SharePoint 2013 - Deployment script


Step :1 Copy and save the below script in DeployWSP.PS1
Step :2 Map the path in bat file and execute
Step: 3 Change the WSP file path
-------------------------------------script--------------------------------------------------------------------

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
Function WaitForInsallation([string] $SolutionName)
{
        Write-Host -NoNewline "Waiting for deployment job to complete" $SolutionName "."
        $WSPSol = Get-SPSolution $SolutionName
        while($wspSol.JobExists)
        {
            sleep 2
            Write-Host -NoNewline "."
            $wspSol = Get-SPSolution $SolutionName
        }
        Write-Host "job Completed" -ForegroundColor green
}
Function Deploy-SPSolution ($WSPFolderPath)
{
    #Get all wsp files from the given folder
    $WSPFiles = Get-childitem $WspFolderPath | where {$_.Name -like "*.wsp"}

    #Iterate through each wsp and Add in to the solution store
    ForEach($File in $wspFiles)
    {
        $wsp = Get-SPSolution | Where {$_.Name -eq $File.Name}

        if($wsp -eq $null)
        {
            write-host "Adding WSP solution:"$File.Name
            Add-SPSolution -LiteralPath ($WspFolderPath + "\" + $file.Name)
        }
        else
        {
            write-host "solution already exists!"

        }
    }
}

try
{
Deploy-SPSolution "F:\JaisonArumugam\WSPPath"
write-host -nonewline "Continue? (Y/N) "
$response = read-host
if ( $response -ne "Y" ) { exit }
}
catch
{
    write-host $_.exception
}


 ---------------------------------------------bat file--------------------------------------------------
save .bat below line and execute run with admin

cd /d %~dp0
powershell -noexit -file "DeployWSP.PS1" "%CD%"
pause

Thursday, January 18, 2018

SharePoint 2013: CSOM vs. REST

The CSOM (and the JSOM by extension) is a Microsoft generated collection of libraries that acts as a proxy to the server-side object model. The CSOM is not a complete replacement for the server side object model. The way I look at it is that I can do just about everything I need to do using the CSOM within a specific site collection. In SharePoint 2013 it was greatly improved as it got additions for working with search, BCS, taxonomies, workflows and user profiles to name just a few. The CSOM is available in managed form for .NET and Silverlight clients as well as unmanaged form in JavaScript (aka: the JSOM).
The REST interface on the other hand is mostly brand new in the SharePoint 2013 release. There was a single service in SharePoint 2010 that we could use that enabled read/write to data within a list. The current REST implementation covers a huge area of SharePoint 2013. For those of you keeping score, this is also an OData interface to SharePoint 2013.
REST is something a Roy Fielding wrote back in 2000 that described a way to share data over HTTP. Unfortunately companies created very different implementation of RESTful services so a bunch got together to define an agreed upon protocol called the Open Data Protocol, also known as OData). The OData spec defines the data formats returned as well as the specific vocabularies used to interact with OData services. Each vendor then implemented it on their own technology stack. Microsoft did this and called their OData product WCF Data Services (notice the URL is actually odata.aspx on MSDN). SharePoint 2013's REST interface is built using WCF Data Services 5.0 which implements the OData v3.0 specification. Unfortunately the SharePoint 2013 implementation does not include everything the spec states, but it's pretty close.
By the way, if you're looking for some great training on this subject, check out Rob Windsor's epic 6.5 hour course at Pluralsight that does a great job of demonstrating both: SharePoint 2013 Development: Client Object Model and REST API.
My Thoughts:
For the email discussion that I witnessed, most people were favoring the CSOM over the REST API in SharePoint 2013 for a few reasons. Most boiled down to the fact that when developing with REST, your custom code tends to be more chatty with the server than CSOM. For instance, if I wanted to create a list with a few custom fields, I could do that in one round trip to the server if using CSOM, but with REST it would be 1 call for the creation of the list and (n) calls for each field I want to create.
Another thing to mention is that when working with the CSOM, the libraries SharePoint provides handle all the plumbing of the HTTP request/response for us. However when using REST, you build it up yourself, including the digest values (required for SharePoint's handing of the replay attack), the type of data you want, the HTTP method, etc. So there is a bit more work to working with REST.
Now, keep in mind that before I pitch my preference in the rest of this post, I strongly believe there is no right or wrong answer. I guess there is one wrong answer: people who say one is better than the other one. Fact is just like everything else in SharePoint, we've got multiple ways to do the same thing and we can choose what we like best for our situation.
However with that being said, for me I strongly prefer REST over the CSOM for numerous reasons. The only exception to this is when there is something in the CSOM that I can't do in REST. Two big cases come to mind here (but there are others): the REST API doesn't have support for working with managed metadata taxonomies and I also can't interact with workflows via REST. The CSOM has coverage for both of these things, including a very robust Workflow Services CSOM API (sadly it's poorly documented... in fact, sadly, its full of inaccuracies).
So... why do I prefer REST over CSOM? Let me enumerate a few things:
  • Data Access: with CSOM, I have to write CAML queries (nasty) whereas with the REST API I use OData vocabularies and the documentation is quite good
  • With the REST API, I can use any of the open source & community libraries available, and there are a ton including the following. With CSOM, it’s my code + CSOM… zero to very few utility libraries out there.
  • With the REST API, there is a lot more documentation out there, and stuff not supplied by MSFT, so when I need help, it’s easy to find an answer. For CSOM, it’s 100% SharePoint and even what’s on MSDN has some gaps for 2013 (nature of a new release)… one small example: Workflow Services CSOM API (contains inaccuracies and a lot of gaps as last published prior to B2 public release ~12mo ago).
  • With the REST API, I can easily test queries in the browser & using Fiddler making me more productive. With CSOM, I must write something and run it in SharePoint / console app.
There’s one point (I touched on it previously in this post) that keeps being made by the CSOM zealots over REST that I find someone ironic: REST is chattier than CSOM.
This is an academic argument in my point of view. Yes, because we lack batching support in SharePoint REST, you bet it is but that is something the SharePoint team could implement as the technology they rely on (WCF Data Services 5.0) already supports it (http://msdn.microsoft.com/en-us/library/dd744839.aspx). But the current state is we don’t have it. Still it’s an interesting argument to make. Consider this counter point: if you’re writing a web app, have you looked at Fiddler when you make your single page request? Notice all YOUR CSS, JavaScript & images being requested in a separate HTTP request? We all [likely] know that you can “batch” these by combining CSS & JavaScript and merging images using sprites, but do we do it? From what I see, the vast majority doesn’t. So (and I'm admittedly painting with a big brush) you’ve already shot down the “I won’t use it because it’s chatty” because your app is already chatty.

ref : http://www.andrewconnell.com/blog/sharepoint-2013-csom-vs.-rest-...-my-preference-and-why

How do I know if SharePoint Online or SharePoint Server is best for my business?
For modern businesses, Office 365 with SharePoint Online is the obvious choice. Not only does SharePoint Online deliver greater functionality and flexibility, it also comes at a lower cost.
From a functionality perspective, SharePoint Online is the ideal choice for organisations. Your business will be able to operate more effectively as Microsoft commits SharePoint Online to a 99.9% uptime SLA.
If your business has remote and mobile workers, SharePoint Online is an ideal solution. Not only does it support remote access, it allows a higher level of integration with external parties, such as consultants, who aren’t directly employed by your business. SharePoint Online includes a file sharing feature which works better in O365 than in SharePoint Server. SharePoint Online makes it easy for teams to work together effectively, regardless of physical location.
SharePoint Online is part of the Office 365 plan, so the service is billed monthly on a per user basis. With no need to purchase and maintain expensive hardware on which to install the system, you only pay for what you need, and you can quickly scale the service up or down as your needs evolve and business changes.
As a cloud-hosted platform, Microsoft takes care of SharePoint Online disaster recovery, upgrades and patches. This means you don’t need to train and manage a dedicated IT team to maintain the infrastructure, reducing your operating costs. You’ll have immediate access to new features and updates as they’re released.
When is SharePoint Online the better option?
·         If you want to get things up and running quickly: in most cases it will only take minutes to set up an Office 365 account. SharePoint will be at your fingertips in no time at all
·         If you are keen to reduce the costs of your dedicated infrastructure
·         If you want to collaborate with external employees, partners or customers
·         If you would like to use new technologies like Office Delve  and Sway 
·         If you want to provide your employees with state-of-the-art tools for mobile deployment as well
When is SharePoint On-Premises the better option?
·         If you already have a dedicated infrastructure for SharePoint
·         If you have integrated external employees and customers in your infrastructure already
·         If you require so-called farm solutions – so programs that penetrate deep into the system
·         If you are required to do so for data protection reasons
·         If your Internet connection does not have sufficient bandwidth

Thursday, January 4, 2018

Move Folder to SharePoint Document Library- 2013/2016

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace MoveFolderToSharePoint
{
    static class Program
    {
        private static int file_count = 0;
        private static int mbfile_count = 0;
        static int folder_count = 0;
        private static double file_mb_size = 0;
        private static int dir_too_count = 0;
        private static int file_too_count = 0;
        static System.Data.DataTable table = new System.Data.DataTable();
        static byte[] byteArr = null;
        static bool isValid = false;
        static string illegalChars = "[\\~#%&*{}/:<>?|\"-]";
        static string replacement = " ";
        static string dirName = string.Empty;
        static string FolderPath = string.Empty;
        static string ListName = string.Empty;
        static int limitFilesize = 0;
        ///
        /// Get the file count of a given directory recursively.
        ///
        static void Main(string[] args)
        {

            using (SPSite site = new SPSite("http://win-2016"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    // Here we create a DataTable with four columns.
                    table.Columns.Add("File Name", typeof(string));
                    table.Columns.Add("File Size", typeof(string));
                    table.Columns.Add("File MBSize", typeof(string));
                    table.Columns.Add("SizeStatus", typeof(string));
                    table.Columns.Add("Status", typeof(string));
                    table.Columns.Add("DateTime", typeof(DateTime));
                    table.Columns.Add("File Path", typeof(string));
                    Console.Write("Please enter folder path : ");
                    FolderPath = Console.ReadLine();
                    Console.Write("Please enter document library name : ");
                    ListName = Console.ReadLine();
                    Console.Write("Please enter file size(< MB) : ");
                    limitFilesize = Convert.ToInt32(Console.ReadLine());
                    string dirPath = @"" + FolderPath + "";
                    dirName = Path.GetFileNameWithoutExtension(dirPath);
                    FolderPath = Regex.Replace(FolderPath.Split(':')[1], @"\\", "/");
                    Console.WriteLine("Working on it...please wait..");
                    System.Data.DataTable tableExport = GetSubFolder(dirPath, web);
                    ExportListFromTable(tableExport, dirName + "_AllFileSizeLog");
                    Console.WriteLine("--------------------------------------------------");
                    Console.WriteLine("Total Files Count ==> {0}", file_count);
                    Console.WriteLine("Total folder Count ==> {0}", folder_count);
                    Console.WriteLine("-------------------------------------------");
                    Console.WriteLine("Total <100 MB Files Count ==> {0}", mbfile_count);
                    Console.WriteLine("--------------------------------------------------");
                    Console.WriteLine("dir too big Total Count ==> {0}", dir_too_count);
                    Console.WriteLine("Files too big Count ==> {0}", file_too_count);
                    Console.ReadKey();
                }
            }

        }
        /// <summary>
        /// get folder tree
        /// </summary>
        /// <param name="folder"></param>
        /// <returns></returns>
        public static System.Data.DataTable GetSubFolder(string folder, SPWeb web)
        {
            try
            {             

                if (folder.Length < 255)
                {
                    string dirPath = Regex.Replace(folder.Split(':')[1], @"\\", "/");
                    dirPath = dirPath.Remove(0, FolderPath.Length);
                    Console.WriteLine(dirPath);
                    if (!string.IsNullOrEmpty(dirPath))
                    {
                        var folderWeb = web.CreateFolder(ListName, dirPath);
                    }
                    string[] subFolders = Directory.GetDirectories(folder);
                    foreach (string subFolder in subFolders)
                    {
                        folder_count++;
                        GetSubFolder(subFolder, web);
                    }
                    string[] files = Directory.GetFiles(folder); FileInfo fileInfo = null;
                    foreach (string file in files)
                    {
                        string nameFile = Path.GetFileName(file);
                        string filefullPath = file;
                        isValid = Regex.IsMatch(nameFile, illegalChars, RegexOptions.CultureInvariant);
                        if (isValid)
                        {
                            Regex regEx = new Regex(illegalChars);
                            nameFile = Regex.Replace(regEx.Replace(nameFile, replacement), @"\s+", " ");
                            if (file.Length < 255)
                            {
                                System.IO.File.Move(file, @"" + folder + "\\" + nameFile);
                                filefullPath = @"" + folder + "\\" + nameFile;
                                File.Delete(file);
                            }
                        }
                        long size = 0;
                        if (filefullPath.Length < 255)
                        {
                            fileInfo = new FileInfo(filefullPath);
                            size = fileInfo.Length;
                            file_mb_size = ConvertBytesToMegabytes(size);
                            if (file_mb_size < limitFilesize)
                            {
                                byteArr = File.ReadAllBytes(filefullPath);  // # % * : < > ? / 
                                web.Files.Add(ListName + dirPath + "/" + nameFile, byteArr, true);
                                Console.WriteLine("File Uploaded("+ file_mb_size.ToString("0.000") + "<"+limitFilesize+"MB) :" + file_count + " :" + nameFile);
                                mbfile_count++;
                                table.Rows.Add(nameFile, size, file_mb_size.ToString("0.000"), "<100", "Success", DateTime.Now, file);
                            }
                            else
                            {
                                Console.WriteLine("File Omitting..(>100MB) :" + file_count + " :" + nameFile);
                                table.Rows.Add(nameFile, size, file_mb_size.ToString("0.000"), ">100", "Success", DateTime.Now, file);
                            }
                        }
                        else
                        {
                            Console.WriteLine("File too big...:" + file_count + " :" + nameFile);
                        }
                        //truncate files to 255 characters
                        string truncatedFilename = file;
                        if (truncatedFilename.Length > 255)
                        {
                            file_too_count++;
                            truncatedFilename = truncatedFilename.Substring(0, 255);
                            //replace any single quote in filename with two double quotes
                            truncatedFilename = truncatedFilename.Replace("'", "''");
                            table.Rows.Add(nameFile, size, file_mb_size.ToString("0.000"), "Null", "File Long", DateTime.Now, file);
                        }

                        file_count++;
                    }

                }
                else
                {
                    dir_too_count++;
                    table.Rows.Add(folder, "0", file_mb_size.ToString("0.000"), "Null", "Folder Long", DateTime.Now, "None");
                }
                return table;
            }
            catch (Exception ex)
            {
                Console.Write("Error : " + ex.Message);
                Console.Write("Trace : " + ex.StackTrace);
                return table;
            }
        }
        /// <summary>
        /// bytes to MB
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        static double ConvertBytesToMegabytes(long bytes)
        {
            return (bytes / 1024f) / 1024f;
        }
        /// <summary>
        /// Ensure SPFolder
        /// </summary>
        /// <param name="web"></param>
        /// <param name="listTitle"></param>
        /// <param name="folderUrl"></param>
        /// <returns></returns>
        public static SPFolder CreateFolder(this SPWeb web, string listTitle, string folderUrl)
        {
            if (string.IsNullOrEmpty(folderUrl))
                throw new ArgumentNullException("folderUrl");
            var list = web.Lists.TryGetList(listTitle);
            return CreateFolderInternal(list, list.RootFolder, folderUrl);
        }
        /// <summary>
        ///CreateFolderInternal
        /// </summary>
        /// <param name="list"></param>
        /// <param name="parentFolder"></param>
        /// <param name="folderUrl"></param>
        /// <returns></returns>
        private static SPFolder CreateFolderInternal(SPList list, SPFolder parentFolder, string folderUrl)
        {
            var folderNames = folderUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var folderName = folderNames[0];

            var curFolder =
                parentFolder.SubFolders.Cast<SPFolder>()
                            .FirstOrDefault(
                                f =>
                                System.String.Compare(f.Name, folderName, System.StringComparison.OrdinalIgnoreCase) ==
                                0);
            if (curFolder == null)
            {
                var folderItem = list.Items.Add(parentFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder,
                                                folderName);
                folderItem.SystemUpdate();
                curFolder = folderItem.Folder;
            }


            if (folderNames.Length > 1)
            {
                var subFolderUrl = string.Join("/", folderNames, 1, folderNames.Length - 1);
                return CreateFolderInternal(list, curFolder, subFolderUrl);
            }
            return curFolder;
        }
        /// <summary>
        /// Export to xls to directory Path
        /// </summary>
        public static void ExportListFromTable(System.Data.DataTable table, string filename)
        {
            DirectoryInfo dir = new DirectoryInfo(@"C:\Reports");
            dir.Create();
            string excelFileName = string.Format(@"C:\Reports\" + filename + "_{0}.xls", DateTime.Now.Ticks.ToString());

            FileInfo file = new FileInfo(excelFileName);
            StreamWriter streamWriter = file.CreateText();

            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
            Table tblListView = new Table();
            tblListView.ID = "_tblListView";

            tblListView.BorderStyle = BorderStyle.Solid;
            tblListView.BorderWidth = Unit.Pixel(1);
            tblListView.GridLines = GridLines.Horizontal;
            tblListView.BorderColor = System.Drawing.Color.LightGreen;
            System.Data.DataView dvListViewData = table.DefaultView;
            if (dvListViewData != null && dvListViewData.Count > 0)
            {
                tblListView.Rows.Add(new TableRow());
                tblListView.Rows[0].BackColor = System.Drawing.Color.LightGreen;
                tblListView.Rows[0].Font.Bold = true;

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    tblListView.Rows[0].Cells.Add(new TableCell());
                    tblListView.Rows[0].Cells[i].Text = table.Columns[i].ToString();
                }

                for (int i = 0; i < dvListViewData.Count; i++)
                {
                    tblListView.Rows.Add(new TableRow());

                    for (int j = 0; j < table.Columns.Count; j++)
                    {
                        tblListView.Rows[i + 1].BorderStyle = BorderStyle.Dotted;
                        tblListView.Rows[i + 1].Cells.Add(new TableCell());
                        tblListView.Rows[i + 1].Cells[j].Text = dvListViewData[i][j].ToString();
                    }
                }
            }
            tblListView.RenderControl(htmlTextWriter);
            streamWriter.Write(stringWriter.ToString());

            htmlTextWriter.Close();
            streamWriter.Close();
            stringWriter.Close();
        }
    }
}