Tuesday, July 31, 2012

Upload File to SharePoint Library using PowerShell

We had a PowerShell script code to generate Large Lists reports in D:\Reports, and now want to periodically upload them to a document library "Reports" in my Admin site. So, scheduled a PowerShell script to do so. Here is my PowerShell code to upload the report to a document library.

Upload file to SharePoint 2010 Library using PowerShell
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#Function to Upload File
function UploadFile($WebURL, $DocLibName, $FilePath)
{
#Get the Web & Lists to upload the file
$Web = Get-SPWeb $WebURL
$List = $Web.GetFolder($DocLibName) 

#Get the Files collection 
$Files = $List.Files 

#Get File Name from Path
$FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1) 

#delete the File from library, if already exist!
if($Files.Item($DocLibName +"/" + $FileName))
{
$Files.delete($DocLibName +"/" + $FileName)
}
#Get the File
$File= Get-ChildItem $FilePath

#Add File to the collection
$Files.Add($DocLibName +"/" + $FileName,$File.OpenRead(),$false)

#Dispose the objects
$web.Dispose()
 }
 
#call the upload function
UploadFile "http://sharepoint.company.com" "Monthly Reports" "D:\Reports\LargeLists.txt"

Upload File to SharePoint using PowerShell with Metadata:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Function to Upload File
function UploadFile($WebURL, $DocLibName, $FilePath)
{
#Get the SharePoint Web & Lists to upload the file
$Web = Get-SPWeb $WebURL
$List = $Web.GetFolder($DocLibName)
 
#Get the Files collection from SharePoint Document Library
$Files = $List.Files
 
#Get File Name from Path
$FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
 
#Get the File from Disk
$File= Get-ChildItem $FilePath

#Set the Metadata
 $Metadata = @{}
 $Metadata.add("Department", "Sales")
 $Metadata.add("Location", "APAC");
 
#Add File to Files collection of Document Library
$Files.Add($DocLibName +"/" + $FileName,$File.OpenRead(), $Metadata,  $true) #true for overwrite file, if already exists!

<# Alternatively, You can set the metadata as: 
   $UploadedFile=$Files.Add($DocLibName +"/" + $FileName,$File.OpenRead(), $true)
   $UploadedFile.Item["Department"]="Sales"
   $UploadedFile.Item.Update() 
 #>
   
 }
  
#call the upload function
UploadFile "http://sharepoint.company.com" "Monthly Reports" "E:\Reports\UsageReport.csv"

If you are looking for a way to upload Files to SharePoint List or Library using C#, Have a look at my another post: How to Programmatically upload File to SharePoint document library?

If you wan to upload Multiple Files in Bulk, Refer: Bulk upload files to SharePoint using PowerShell


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, July 30, 2012

Delete or Restore SharePoint Recycle Bin Items based on Deleted Date using PowerShell

Requirement is to Restore all the Items deleted before last week from Recycle bin, which were already deleted from End-User Recycle bin (1st Stage Recycle bin).

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

$WebApp=get-spwebapplication "http://sharePoint.crescent.com"

    foreach ($SPSite in $WebApp.Sites)
    {
     #Contains both First Stage & Second Stage Recycle bin Items
     $SPRecycleBinItemCollection  = $SPSite.RecycleBin;
     
     #write-host "Processing Site: " $SPSite.RootWeb.Title "`n" 
     #write-host "Total No. of Items in Recycle bin: " $SPRecycleBinItemCollection.Count
        for ($i=$SPRecycleBinItemCollection.Count-1; $i -GE 0;  $i--)
            {
             # check whether the Recycle bin Item is a SecondStageRecycleBin Item
              if($SPRecycleBinItemCollection[$i].ItemState -eq [Microsoft.SharePoint.SPRecycleBinItemState]::SecondStageRecycleBin)
               {
               $deletedTime = $SPRecycleBinItemCollection[$i].DeletedDate;
               
               $selectedTime=(Get-Date).AddDays(-7)

                if ($selectedTime -LT $deletedTime)
                    {
                        $guid = $SPRecycleBinItemCollection[$i].ID;
                        write-host "Item Restored:" $SPRecycleBinItemCollection[$i].Title
                        $SPRecycleBinItemCollection.Restore($guid);
                        #$SPRecycleBinItemCollection.Delete($guid);
                    }
                }
            }
       }


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, July 29, 2012

Display Lists from Other Site Collection/Web Application Using JQuery

Another frequent requirement is to display Lists/Libraries from Root site to Sub-site or Sub-site to Root site, and in some cases from Cross Site collection. While this can be fulfilled by Web Services, Custom Web Parts, etc, here is the simple JQuery method to display SharePoint list from another site collection or from different site.

I deployed the JQuery file to my WFEs and referred it in the script:
<script type="text/javascript" src="/_layouts/jquery/jquery.min.js"></script>

<!-- placeholder for processing Image and List View -->
<div id="ListViewPlaceHolder"><img src="/_layouts/images/GEARS_AN.GIF" alt="" /></div>
 
<script type="text/javascript">
<!-- Specify the View URL of the list you want to show: -->

var ShowWP = "https://portal.crescent.com/clients/mcdonald/Lists/ClientNotes/AllItems.aspx";
$("#ListViewPlaceHolder").load(ShowWP +" #WebPartWPQ2 .ms-listviewtable",function() {
    $("#ListViewPlaceHolder *").removeAttr("id onclick onfocus onmouseover");
});

</script>

SharePoint User Toolkit  at http://usermanagedsolutions.com/SharePoint-User-Toolkit/Pages/Cross-Site-List-Snapshot.aspx provides UI to Generate the script. Just enter your List URL and get the Javascript, place it in CEWP or wherever applicable.
 sharepoint display list from another site collection

By the way, SharePoint User Toolkit offers few more such features like Image Rotators, Tabs, etc.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, July 26, 2012

Maintenance Page for SharePoint - Quick way to Implement

Here is the quick way to implement Maintenance page in SharePoint, during scheduled down times/upgrade/service pack patching: Create a new app_offline.htm file in IIS Root folder of your SharePoint site. Place some descriptive text/images to the file, Make sure the file size is at least 512 bytes (otherwise, you will get 404 page not found error!). That's all!
maintenance page sharepoint 2010

I've placed the maintenance page content like this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Site Under Maintenance</title>
</head>

<body>
<div align="center"><br />
  <br />
  <br />
  <br />
  <img src="http://testIntranet.crescent.com/images/maintenance.gif" width="600" height="300" /></div>
</body>
</html>

and the output: Maintenance page for SharePoint 2010/2013
sharepoint display maintenance page
maintenance page SharePoint 2010

As long as this file exists in the root, ASP.NET shuts down the site, stops processing any requests. So, After the maintenance activity, Just delete the app_offline.htm file to end up the maintenance mode.

For some reasons, If this doesn't work for you: Create a dummy website in TEST environment, assign the PROD site's Host headers, Place the above content in Index.htm, change the IP addresses in publishing server! (ISA/ F5).


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, July 23, 2012

How to Create - Update - Delete SharePoint Views Programmatically

Often in development we may have to deal with SharePoint Views programmatically. Here I'm sharing the code snippets from my recent project to handle views programmatically.

Creating a New View Programmatically:
    using (SPSite site = new SPSite("http://crescent.sharepoint.com"))
        {
                using (SPWeb web = site.OpenWeb())
                {
                   //Get the List
                     SPList ProjectDocuments = web.Lists["Client Documents"];

             //Set the View fields
             StringCollection ViewFields = new StringCollection();
             ViewFields.Add("Type");
             ViewFields.Add("Name");
            
             //Set the View Filter and Sort order
             string viewQuery = @" <Where><Eq><FieldRef Name='Status' /><Value Type='Choice'>In Progress</Value></Eq></Where><OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy> ";

             //Create the view
             ProjectDocuments.Views.Add("Proposal Documents", ViewFields, ViewQuery, 100, true, false);
            
             //Update the List
             ProjectDocuments.Update();
  
               }
      }

Add/Remove fields to an existing View Programmatically:
  
                //Get the List
                SPList ProjectDocuments = web.Lists["Project Documents"];

                //Get the view 
                SPView ProjectDocumentsDV = ProjectDocuments.DefaultView;
                // Or it can be: SPView oView = oList.Views["View-Name"];

                //Delete all fields from the view
                ProjectDocumentsDV.ViewFields.DeleteAll();
                //Add "Type" and "Name" fields
                ProjectDocumentsDV.ViewFields.Add("Type");
                ProjectDocumentsDV.ViewFields.Add("Name");

                //Update the view
                ProjectDocumentsDV.Update();
                //Update the List
                ProjectDocuments.Update();


Get the Fields from View Programmatically:
              
              SPView ProjectDocumentsView = ProjectDocuments.DefaultView;

              //Get the fields from a View
              SPViewFieldCollection ViewFieldColl = ProjectDocumentsView.ViewFields;

                    foreach (string ViewField in ViewFieldCol)
                      {
                          Console.WriteLine("Field Name : " + ViewField);
                      }

Delete Existing View Programmatically:
  //Get the List
     SPList ProjectDocuments = web.Lists["Project Documents"];

     //Get the view 
     SPView ProjectDocumentsView = ProjectDocuments.DefaultView;

    //Delete the views
    ProjectDocuments.Views.Delete(ProjectDocumentsView.ID);
    ProjectDocuments.Update();


PowerShell Script to Create - Update - Copy - Delete SharePoint List Views:
How to Create / Update / Copy / Delete SharePoint Views with PowerShell


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, July 21, 2012

SharePoint 2010 Custom Error Page Redirect in Event Receivers

In my last post Allow only Certain File Types to be Uploaded in SharePoint Document Library using Event Receiver I developed an Event receiver to prevent files other than PDF from being uploaded to a document library. So when user tries to upload a file other than PDF they'll get an Error message in the window saying "You are allowed to upload only PDF files". No issues!

But in most of the cases, user tried uploading word files, receives the error message and complains they don't know how to make the word or other file types to PDF. So, to help out users, what we wanted to do is instead of just saying "You are allowed to upload only PDF files", what if we instruct users on "How to convert the word document to PDF" with some descriptive text? Sounds good! Lets get started! Do these 3 modifications to the existing project to get SharePoint event receiver custom error page.

SharePoint redirect from event receiver:
1. Update the Event Receiver: ItemAdding Section's Code would be:
public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);

           if (!properties.AfterUrl.EndsWith("pdf"))
           {
               properties.Status=SPEventReceiverStatus.CancelWithRedirectUrl;
               properties.RedirectUrl = "/_Layouts/Crescent.ProjectSites.AllowPDFOnly/PDFOnlyError.aspx";
           }
       }

2. Add a Application Page to the Project, optionally a Icon to represent Error.
sharepoint event receiver custom error page
Now the Project will be looking like:
sharepoint 2010 event receiver custom error page

3. Update the Error page: Under the PlaceHolderMain Place some content to give descriptive Error message:

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div style="float:left"> 
    <asp:Image ID="Image1" runat="server" ImageUrl="/_Layouts/Crescent.ProjectSites.AllowPDFOnly/Error.png" />
</div>
<div style="width:700px; height:300px; padding-left:10px;"> 
<h2>You are allowed to Upload only PDF files. <br /></h2> <h3>Here is How to Convert Word files to PDF</h3>
<P>1. Open the file you wish to save.</P>
<P>2. Click the Microsoft Word button in the top left-hand corner.</P>
<P>3. Go to Save As > PDF or XPS. If this option is not available to you, go here to download Microsoft's free PDF and XPS converter. Note that this will only work for Windows; if you have a Mac, use the method below.</P>
<P>4. Type in the desired file name and adjust settings as necessary. Choose Minimum Size if you wish to reduce the size and quality.</P>
<P>5. Hit Publish. This will convert your document and open it in Adobe Reader (if you have it installed)</P>
</div>
</asp:Content>

See the Result in action: SharePoint 2010 event receiver custom error page.
sharepoint 2010 event receiver custom error
SharePoint 2010 event receiver custom error


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, July 19, 2012

Restrict File Types in SharePoint Document Library Upload using Event Receiver

Requirement: In a Project collaboration SharePoint site, had a requirement to Allow users to upload only PDF files to a Document library and prevent all other files from being uploaded.

Solution: Our requirement is basically to prevent files being uploaded other than PDF, isn't it? So lets jump to visual studio and create a Event Receiver in SharePoint to restrict file types in SharePoint document library.

How to Create a Event Receiver in SharePoint 2010?
Compared with MOSS 2007, Creating Event receivers in SharePoint 2010 is very easy With Visual Studio 2010. Here are the steps:

1. Create a New Visual Studio Project, Choose SharePoint >> 2010 >> Event Receiver >> Give it a Name. Say "Crescent.ProjectSites.AllowPDFOnly"
sharepoint document library restrict file types on upload
2. Make it as a Farm solution, choose the event receiver properties as in the below screen.
sharepoint restrict file types for document library
3. On clicking "Finish" button, Visual Studio will create the project structure as:
sharepoint 2010 document library restrict file types
4. Now, in the Elements.xml file, change the ListTemplateID="101" (Which means all document Libraries) to ListURL="RelativePathOfDocLibrary" say: ProjectDocuments.
sharepoint document library restrict file type
Change the <Receivers attribute restrict file types in document library sharepoint
5. Update the Event receiver ItemAdding section's code as below:
   if (!properties.AfterUrl.EndsWith("pdf"))
               {
                   properties.ErrorMessage = "You are allowed to upload only PDF Files!";
                   properties.Status = SPEventReceiverStatus.CancelWithError;
                   properties.Cancel = true;
               }


So, The complete code would be:
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace Crescent.ProjectSites.AllowPDFOnly.EventReceiver1
{
    public class EventReceiver1 : SPItemEventReceiver
    {
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);

           if (!properties.AfterUrl.EndsWith("pdf"))
           {
               properties.ErrorMessage = "You are allowed to upload only PDF Files!";
               properties.Status = SPEventReceiverStatus.CancelWithError;
               properties.Cancel = true;
           }
       }
    }
}
See the the result in action!SharePoint document library restricts file type other than PDF.
sharepoint document library restrict file type


Drawback: This will prevent creating sub-folders which doesn't end with PDF! so if you need folder, name it like "folder.pdf" and then rename!

File Controller Feature from kwizcom allows you to achieve the same! You can restrict files on upload based on File Type, Size.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, July 18, 2012

SharePoint 2013 Preview officially launched!

SharePoint 2013 preview officially launched with great features. Here are some useful URL's to get started:



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, July 12, 2012

Customize Top Navigation Programmatically in SharePoint 2010

Requirement: Had to customize the Top navigation with bunch of provided internal/external links as part of a branding project.

Solution: Designed a feature to programmatically add links to top navigation bar. when activated, feature will add bunch of links to the top navigation bar.

Customize navigation programmatically in SharePoint 2010:
        
public override void FeatureActivated(SPFeatureReceiverProperties properties)
        { 
            SPSite site = properties.Feature.Parent as SPSite;
            SPWeb rootWeb = site.RootWeb;
            // Get the top link bar.
            SPNavigationNodeCollection topNavNodes = rootWeb.Navigation.TopNavigationBar;

            // Create a simple external Link node.
            SPNavigationNode node = new SPNavigationNode("I-Best", "http://ibest.crescent.com",true);
            topNavNodes.AddAsLast(node);

            //Add Heading & child Links node
            SPNavigationNode oNewNode = new SPNavigationNode("Org Browser", "");
            rootWeb.Navigation.TopNavigationBar.AddAsLast(oNewNode);
            oNewNode.Properties.Add("NodeType", "Heading");
            oNewNode.Update();

            SPNavigationNode oChild1 = new SPNavigationNode("Official", "");
            oNewNode.Children.AddAsFirst(oChild1);
            oChild1.Properties.Add("NodeType", "Heading");
            oChild1.Update();

            SPNavigationNode oChild2 = new SPNavigationNode("Leave Application","http://ibest.crescent.com/apps/Leave.aspx",true);
            oNewNode.Children.Add(oChild2, oChild1);
         }

In an another SharePoint 2007 Project, Had to remove all the Top navigation items and add Links for custom provisioned pages. Here is the code for customizing SharePoint top navigation bar programmatically:

                    //Use Unique Top navigation 
                    web.Navigation.UseShared = false;
                    web.Update();

           
                    //Get the top navigation to customize
                    SPNavigationNodeCollection topNavigationBarNodes = web.Navigation.TopNavigationBar;

                    //Remove All Nodes in Top navigation
                    for (int i = topNavigationBarNodes.Count; i > 0; i--)
                    {
                        topNavigationBarNodes.Delete(topNavigationBarNodes[i-1]);
                    }

                    //Add Top Navigation Page Links
                    SPNavigationNode HomePageMenuItem = new SPNavigationNode(web.Title, "Main.aspx", false);
                    topNavigationBarNodes.AddAsFirst(HomePageMenuItem);

                    //Add Project Documents Link
                    SPNavigationNode ProjectDocumentsMenuItem = new SPNavigationNode("Project Documents","ProjectDocuments.aspx", false);
                    topNavigationBarNodes.AddAsLast(ProjectDocumentsMenuItem);

                    //Add Project Accounting
                    SPNavigationNode ProjectAccountingMenuItem = new SPNavigationNode("Project Accounting", "ProjectAccounting.aspx", false);
                    topNavigationBarNodes.AddAsLast(ProjectAccountingMenuItem);

                    //Add Project Checklist
                    SPNavigationNode ProjectChecklistMenuItem = new SPNavigationNode("Project Checklist", "ProjectChecklist.aspx", false);
                    topNavigationBarNodes.AddAsLast(ProjectChecklistMenuItem);

                    web.Update(); 


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, July 8, 2012

SharePoint List Column Limits

There are limits in number of columns we can create in a SharePoint list. You may Get "Column Limit Exceeded" when You add a new column to a SharePoint List. This is because of the column limitations.

For SharePoint 2003/2007:
With Windows SharePoint Services, you can create the following numbers of each column type for each list or library:
  •     64 Single line of text and Choice (drop-down menu or radio buttons)
  •     31 Multiple lines of text and Choice (check boxes (allow multiple sections))
  •     32 Number and currency
  •     32 Hyperlink
  •     16 Date and time
  •     16 Lookup
  •     16 Yes/No
  •     8 Calculated
Refer this KB for the limitations on the maximum number of columns we can have:
http://support.microsoft.com/kb/823555

The above applies to SharePoint 2007 as well, but This is not a hard limit.

For SharePoint 2010 lists Column limits:  
Refer this Technet article: http://technet.microsoft.com/en-us/library/cc262787.aspx#Column



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, July 7, 2012

How to Create SharePoint List or Library Programmatically

At times, We may have to create List or Document Libraries programmatically. These code snippets will help to get it done.

Using .Net Object Model (C#)

          using (SPSite site = new SPSite("http://sharepoint"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //Create a document library
                    web.Lists.Add("Project Docs", "Library for Storing Project Documents", SPListTemplateType.DocumentLibrary);

                    //Create a Link List
                    web.Lists.Add("Portal Links", "Links to Portal Resources", SPListTemplateType.Links);
                    //SPListTemplateType.Links can be: SPListTemplate AssetTemplate = web.ListTemplates["Links"];


                    //Create a List based on Custom List template
                    SPListTemplateCollection CustomListTemplates = site.GetCustomListTemplates(web);
                    SPListTemplate TrainingTemplate = CustomListTemplates["Training List Template"];
                    web.Lists.Add("Project Links", "Links to project artifacts", TrainingTemplate);

                    //Set the Show in Quick Lanuch Property
                    SPList ProjectLinks = web.Lists["Project Links"];
                    ProjectLinks.OnQuickLaunch = true;

                    // Add new column to the List
                    ProjectLinks.Fields.Add("Link Description", SPFieldType.Text,true);
                    ProjectLinks.Update();

                        // If the "Notes"  Rich Text Field field, if is not in the List already!
            SPFieldCollection fields = ProjectLinks.Fields;
                if (!fields.ContainsField("Notes"))
                {
                    //Add Notes field Rich Text Field
                    SPFieldMultiLineText oFldNotes = (SPFieldMultiLineText)CaseNotes.Fields[CaseNotes.Fields.Add("Notes", SPFieldType.Note, true)];
                    oFldNotes.RichText = true;
                    oFldNotes.RichTextMode = SPRichTextMode.FullHtml;
                    oFldNotes.Update();
                    //Update the List
                    ProjectLinks.Update();
                }

               }
           }

For all available List template types, Refer: SPListTemplateType


Create SharePoint List using PowerShell:


Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 
$site = Get-SPSite -Identity "http://sharepoint"
$web= $site.OpenWeb()

#Create a Link List
$LinkTemplate = $web.ListTemplates["Links"];
$web.Lists.Add("Support Links", "Links to Portal support", $LinkTemplate);
#$LinkTemplate can be: $LinkTemplate = [Microsoft.SharePoint.SPListTemplateType]::Links

#set Quick lanuch option
$SupportLinkList = $web.Lists["Support Links"]
$SupportLinkList.OnQuickLaunch = $true
#Add new Field
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
$SupportLinkList.Fields.Add("Link Description",$spFieldType,$true)
$SupportLinkList.update()

#Create a List based on Custom List template
$CustomListTemplates = $site.GetCustomListTemplates($web)
$web.Lists.Add("Project Links", "Links to project artifacts", $CustomListTemplates["Training List Template"])

$web.Dispose()
$site.dispose()


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, July 6, 2012

Activate/Deactivate Features Programmatically in SharePoint

At times, We may have to activate/deactivate features programmatically. Here is the code snippet:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace ActivateFeature
{
    class Program
    {
        static void Main(string[] args)
        {
            string SiteURL;

            if (args.Length == 0)
            {
                Console.WriteLine("Enter the site collection URL:");
                SiteURL = Console.ReadLine();
            }
            else
            {
                SiteURL = args[0];
            }
            SPSite oSPSite = new SPSite(SiteURL);

            //Get the Feature to Activate
            SPFarm farm = oSPSite.WebApplication.Farm;
            SPFeatureDefinitionCollection features = farm.FeatureDefinitions;
            SPFeatureDefinition feature = features[new Guid("05BA4E54-C1E9-4244-8276-06451EBBB260")];


            if (feature != null)    //Make sure Feature is installed!
            {
                // Activate the feature
                oSPSite.Features.Add(feature.Id, true);
                //call oSPSite.Features.Remove
            }
        }
    }
}

PowerShell way:
To activate a feature in PowerShell:
Enable-SPFeature -identity <Feature-Folder-Name/GUID> -URL <URL-of-Web-app/Site coll/Site>

To deactivate a feature: 
Disable-SPFeature -identity <Feature-Folder-Name/GUID> -URL <URL-of-Web-app/Site coll/Site>


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, July 4, 2012

Set Sorting, Filter, Group By in SharePoint Views Programmatically

SharePoint List views uses CAML internally to Filter, Sort list items. In a Recent project, we had to programmatically set the Filter and Sort order of default views.

How to Get the CAML?
Simple! use U2U CAML Query builder, one of my favorite SharePoint tool.
Set Sorting, Filter, Group By in SharePoint Views Programmatically

C# code to set the View Filter, Sort options:
 //Get the List, say "Project Tasks" 
  SPList ProjectTasks = web.Lists["Project Tasks"];

 //Get the view 
 SPView ProjectTasksView = ProjectTasks.DefaultView;
 // Or you can get a specific view by: List.Views["View-Name"]

 //Set the CAML Query
 string viewQuery = @" <Where><Eq><FieldRef Name='Status' /><Value Type='Choice'>In Progress</Value></Eq></Where><OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy> ";
 //Update the view 
  ProjectTasksView.Query = viewQuery;
  ProjectTasksView.Update();

  //Update the List
  ProjectTasks.Update();

U2U doesn't offer Group by in its UI, However just append <GroupBy Collapse="TRUE"><FieldRef Name="Country" /></GroupBy>  to the Query to get the Group by applied.

PowerShell way to Set View Options:
$web=Get-SPWeb -identity "http://sharepoint.com"
$list=$web.lists["Tasks"]
$view =  $list.DefaultView  # To fetch a particular view, use:  $list.Views | ?{$_.title -eq "View-Name"}
$view.Query = '<OrderBy><FieldRef Name="Modified" Ascending="False" /></OrderBy>'
$view.Update()
$list.Update()


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, July 2, 2012

How to Create Custom Application Page in SharePoint 2010 to get List Owners

In my environment, This is one of a Frequently asked question: How do I find who has created a List or Library? oops, I don't find any direct way from SharePoint interface to know who has created a List or Library.

Lets develop a Application page, host it under Layouts folder and let the users access that page to get the list owners information.

How to get Who has Created a List/Library?

Here is how to Create a Custom Application Page for SharePoint 2010 using Visual Studio - Step by Step:

1. Create a Visual studio "Empty SharePoint Project", Give it a name, Lets say "ListOwner".

2. Add a New Item to the Project, choose "Application Page", Name it, Say "ListOwner.aspx"
how to create custom application page in sharepoint 2010

3. This will create the project structure as in the below screen.
how to create custom page in sharepoint 2010

4. Now, Lets add a grid to the page, to display all the Lists and its owners from the current site.
Go to the ListOwner.aspx page, locate the code block:

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
</asp:Content>

and add the SPGrid in between above code. So it will be:
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"><h2>List owners Info:</h2></asp:Label>
     
     <SharePoint:SPGridView runat="server" ID="GridView" AutoGenerateColumns="false"
            GridLines=Horizontal HeaderStyle-BackColor="#18518E" RowStyle-BackColor="#D3E4E5" RowStyle-ForeColor="Black" AlternatingRowStyle-BackColor="#fcfcfc" HeaderStyle-Font-Bold="true"  />
     
</asp:Content>

As the next step, we've to write the code to fetch the lists & libraries to the Grid, by editing ListOwner.aspx.cs

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;

namespace ListOwner.Layouts.ListOwner
{
    public partial class ListOwner : LayoutsPageBase
    {
   
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
      
            //Add columns to Data Table
            dt.Columns.Add("List Name", typeof(string));
            dt.Columns.Add("List URL", typeof(string));
            dt.Columns.Add("Description", typeof(string));
            dt.Columns.Add("Owner", typeof(string));
            dt.Columns.Add("OwnerURL", typeof(string));

            //Add List info as rows
            foreach(SPList list in SPContext.Current.Web.Lists)
            {
                //can Filter the Lists by SPListTemplateType http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splisttemplatetype.aspx
                
                DataRow row = dt.NewRow();
                row["List Name"] = list.Title;
                row["List URL"] = SPContext.Current.Web.Url + list.RootFolder.ServerRelativeUrl;
                row["Description"] = list.Description;
                row["Owner"] = list.Author.LoginName;
                row["OwnerURL"] = SPContext.Current.Web.Url + "/_layouts/userdisp.aspx?ID=" + list.Author.ID + "&Source=" + Page.Request.Url;
       
                dt.Rows.Add(row);
            }

            //Add Columns to Grid
            HyperLinkField col1 = new HyperLinkField();
            col1.HeaderText = "List Name";
            col1.DataTextField = "List Name";
            col1.DataNavigateUrlFields = new string[] { dt.Columns["List URL"].ToString() };
            GridView.Columns.Add(col1);

            SPBoundField col2= new SPBoundField();
            col2.HeaderText = "Description";
            col2.DataField = "Description";
            GridView.Columns.Add(col2);

            HyperLinkField col3 = new HyperLinkField();
            col3.HeaderText = "List Owner";
            col3.DataTextField = "Owner";
            col3.DataNavigateUrlFields = new String[] { dt.Columns["OwnerURL"].ToString() };
            GridView.Columns.Add(col3);
                 
            //Set the Datasource and bind to Grid
            GridView.DataSource = dt;
            GridView.DataBind();

        }
    }
}

Build and deploy the project! That's all, we are done creating custom SharePoint 2010 application page using visual studio 2010.
how to create custom sharepoint 2010 application page using visual studio 2010

Tail: 
How to find Who has Created a Particular SharePoint Site collection or Sub-Site?
You can get the Site Creator, Created Time, etc by accessing the SPWeb.Author, SPWeb.Created properties.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, July 1, 2012

Run a Console Application and Mail Output Report with PowerShell

We had a console application GetStorageReport which runs and generates detailed storage reports based on some SharePoint APIs. Got the requirement to run the tool periodically and mail the output report of the application. Scheduled a PowerShell script to execute the application and mail the report to Administration team.

Here is my PowerShell code:
 
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#Trigger the executable file
Start-Process "D:\Scripts\StorageReport\GetStorageReport.exe"

# Wait until the report is generated
while(-not (Test-Path "D:\Scripts\StorageReport\StorageReport.csv"))
  {
    Start-Sleep 30  #sleep for 30 seconds
  }
  
$ReportDate=get-date -Format "MMM-dd-yyyy"

#Rename the Report 
Rename-Item -Path "D:\Scripts\StorageReport\StorageReport.csv" -NewName "D:\Scripts\StorageReport\StorageReport_$ReportDate.csv"
 
  #Send the Mail
 $MailMessageParameters = @{
                SmtpServer = "smtp.company.org"
    Subject = "SharePoint Storage Report - $ReportDate"
    Body = "Please find attached Database storage report as on $ReportDate"
    From = "SharePointReports@company.com"
    To = "AdminTeam@company.com"
    Attachments ="D:\Scripts\StorageReport\StorageReport_$ReportDate.csv"
    }
 Send-MailMessage @MailMessageParameters
 
 #Remove the Report
 if (Test-Path "D:\Scripts\StorageReport\StorageReport_$ReportDate.csv")
 {
    Remove-Item "D:\Scripts\StorageReport\StorageReport_$ReportDate.csv"
 }



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Set ListViewWebPart Toolbar Type Programmatically

While adding a ListViewWebPart to web part page programmatically, had to set the List View's tool bar to "Summary View". After trying for hours found this code:

  //Method to Set the Tool bar type
        public static void SetToolbarType(SPView spView, String toolBarType)
        {
            spView.GetType().InvokeMember("EnsureFullBlownXmlDocument", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod, null, spView, null, System.Globalization.CultureInfo.CurrentCulture);

            System.Reflection.PropertyInfo nodeProp = spView.GetType().GetProperty("Node", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            XmlNode node = nodeProp.GetValue(spView, null) as XmlNode;
            XmlNode toolbarNode = node.SelectSingleNode("Toolbar");

            if (toolbarNode != null)
            {
                toolbarNode.Attributes["Type"].Value = toolBarType;

                // If the toolbartype is Freeform (i.e. Summary Toolbar) then we need to manually 
                // add some CAML to get it to work.
                if (String.Compare(toolBarType, "Freeform", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
                {
                    string newItemString = "";
                    XmlAttribute positionNode = toolbarNode.OwnerDocument.CreateAttribute("Position");
                    positionNode.Value = "After";
                    toolbarNode.Attributes.Append(positionNode);

                    switch (spView.ParentList.BaseTemplate)
                    {
                        case SPListTemplateType.Announcements:
                            newItemString = "announcement";
                            break;
                        case SPListTemplateType.Events:
                            newItemString = "event";
                            break;
                        case SPListTemplateType.Tasks:
                            newItemString = "task";
                            break;
                        case SPListTemplateType.DiscussionBoard:
                            newItemString = "discussion";
                            break;
                        case SPListTemplateType.Links:
                            newItemString = "link";
                            break;
                        case SPListTemplateType.GenericList:
                            newItemString = "item";
                            break;
                        case SPListTemplateType.DocumentLibrary:
                            newItemString = "document";
                            break;
                        default:
                            newItemString = "item";
                            break;
                    }

                    if (spView.ParentList.BaseType == SPBaseType.DocumentLibrary)
                    {
                        newItemString = "document";
                    }

                    // Add the CAML
                    toolbarNode.InnerXml = @"<IfHasRights><RightsChoices><RightsGroup PermAddListItems=""required"" /></RightsChoices><Then><HTML><![CDATA[ <table width=100% cellpadding=0 cellspacing=0 border=0 > <tr> <td colspan=""2"" class=""ms-partline""><IMG   src=""/_layouts/images/blank.gif"" width=1 height=1 alt=""""></td> </tr> <tr> <td class=""ms-addnew"" style=""padding-bottom: 3px""> <img src=""/_layouts/images/rect.gif"" alt="""">&nbsp;<a class=""ms-addnew"" ID=""idAddNewItem"" href=""]]></HTML><URL Cmd=""New"" /><HTML><![CDATA["" ONCLICK=""BLOCKED SCRIPTNewItem(']]></HTML><URL Cmd=""New"" /><HTML><![CDATA[', true);BLOCKED SCRIPTreturn false;"" target=""_self"">]]></HTML><HTML>Add new " + newItemString + @"</HTML><HTML><![CDATA[</a> </td> </tr> <tr><td><IMG src=""/_layouts/images/blank.gif"" width=1 height=5 alt=""""></td></tr> </table>]]></HTML></Then></IfHasRights>";
                }

                spView.Update();

            }
        } 
    }


Above script credit goes to Jalil Sear

Call the above method wherever required:

                //Create the object SPLimitedWebPart Manager
                SPLimitedWebPartManager WebPartMgr = web.GetLimitedWebPartManager("Home.aspx", PersonalizationScope.Shared);
 
              //Add Client Notes List view web part
                SPList ProjectNotesList = web.Lists["Project Notes"];
                ListViewWebPart ProjectNotesListViewWP = new ListViewWebPart();
                 //Set the properties of the webpart
                ProjectNotesListViewWP.ChromeType = PartChromeType.None;
                ProjectNotesListViewWP.Title = "Client Notes";
                ProjectNotesListViewWP.ListName = ProjectNotesList.ID.ToString("B").ToUpper();
                ProjectNotesListViewWP.ViewGuid = ProjectNotesList.DefaultView.ID.ToString("B").ToUpper();
                //Define the zone in which webparts need to be added
                WebPartMgr.AddWebPart(ProjectNotesListViewWP, "Left", 1);
                
                //Set the Tool bar
                System.Reflection.PropertyInfo ProjectNotesViewProp = ProjectNotesListViewWP.GetType().GetProperty("View", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                spView = ProjectNotesViewProp.GetValue(ProjectNotesListViewWP, null) as SPView;
                Helper.SetToolbarType(spView, "Freeform");

                WebPartMgr.SaveChanges(ProjectNotesListViewWP);


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


How to Change Site Collection URL in SharePoint

At times, we get requests to change the Site collection URLs. While its relatively straightforward and easy by going to Site Actions >> Site Settings >> Title, description, and icon under Look and Feel to change the sub-site's URL, changing the site collection URL is not so!
how to change the site url in sharepoint
You can Change the URL of SharePoint 2010 Sub-Site using PowerShell also:

Get-SPWeb http://sharepoint.com/sites/sitecollection/subsite | Set-SPWeb -RelativeUrl newsubsiteURL

How to Change Site Collection URL in SharePoint?

To change the site collection's URL, There is no out-of-the-box user interface or direct ways. So, after making sure the destination URL's managed path is already in place and verifying the target site collection URL doesn't exist, I do this three step manual process.
  1. Backup the Source Site collection
  2. Delete the Source Site collection (Yes, its must! we've to delete the site collection before restoring it. Otherwise you will end up in No content databases are available for this operation GUID conflict issue.)
  3. Restore the Backup with the target URL
In MOSS 2007, I used to do it with STSADM as to change site collection URL:
stsadm -o backup -url http://sharepoint.crescent.com/sites/source -overwrite -filename source.bak

stsadm -o deletesite -url http://sharepoint.crescent.com/sites/source

stsadm -o restore -url http://sharepoint.crescent.com/sites/destination -filename source.bak

Now, in SharePoint 2010 with the help of PowerShell, Why don't try placing them into a script file to save some time?

Change SharePoint site collection URL using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#Get the Source Site Collection URL
$sourceURL = Read-Host “Enter the Source Site Collection URL:”
 
#Get the Target Site Collection URL
$targetURL = Read-Host “Enter the Destination Site Collection URL”
 
#Location for the backup file
$backupPath = Read-Host “Enter the Backup File name & location (E.g. c:\temp\Source.bak):”

Try
{
  #Set the Error Action
  $ErrorActionPreference = "Stop"

 Write-Host "Backing up the Source Site Collection..."-ForegroundColor DarkGreen
 Backup-SPSite $sourceURL -Path $backupPath -force
 Write-Host "Backup Completed!`n"

 #Delete source Site Collection
 Write-Host "Deleting the Source Site Collection..."
 Remove-SPSite -Identity $sourceURL -Confirm:$false
 Write-Host "Source Site Deleted!`n"

 #Restore Site Collection to new URL
 Write-Host "Restoring to Target Site Collection..."
 Restore-SPSite $targetURL -Path $backupPath -Confirm:$false
 Write-Host "Site Restored to Target!`n"

 #Remove backup files
 Remove-Item $backupPath
}
catch
{
 Write-Host "Operation Failed. Find the Error Message below:" -ForegroundColor Red
 Write-Host $_.Exception.Message -ForegroundColor Red
}
finally
{
 #Reset the Error Action to Default
 $ErrorActionPreference = "Continue"
}

write-host "Process Completed!"

I Love PowerShell! The above method is also applicable when you want to change the Managed Path of your site collection (both SharePoint 2007 & SharePoint 2010).

To change host-named site collection's URL, you can simply use this PowerShell script:
$site = Get-SPSite -Identity "http://sales.crescent.com/teams/cloud"
$site.rename("http://sales.brightpoint.com/teams/CloudHosting")


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


You might also like:

Related Posts Plugin for WordPress, Blogger...