Sunday, July 28, 2013

Copy \ Add Document to Document Set

In this article we can explore the copy document from a document library to document set through code.

Following are the activities involved in copying document:
  • Find the document library
  • Find the document by name
  • Create a byte array from document
  • Find document set and add document to document set
Inside Visual Studio

Create a new console application and name it as DocLibCreation. Make sure you change the target framework to .Net 3.5.

Add the following code into the Program.cs file:

public static void CopyDocument( SPWeb objProjectSite, SPWeb rootSite)
objProjectSite.AllowUnsafeUpdates = true;
SPList objList = rootSite.Lists.TryGetList("Source Document Library");
SPFile objFile = null;
Foreach (SPListItem itm in objList.Items)
if (itm.Name == "My Document")
objFile = itm.File;
byte[] sourceFileContent = objFile.OpenBinary();
SPList prjDocsList = objProjectSite.Lists.TryGetList("Destination Document Library");
SPFolder folDocSet = objProjectSite.GetFolder("Destination Document Library" + "/" + "Document Set Name");
folDocSet.Files.Add("Document Name" , sourceFileContent, true );
ObjProjectSite.AllowUnsafeUpdates = false;

Monday, July 22, 2013

Get all seach scopes for current site collection

In this article we will be seeing about search scopes in SharePoint 2010.|

In this article:
  • Add namespaces
  • Get search context
  • Get all scopes
  • Skip default scopes
  • Add scopes in dropdown
Get all the search scopes:

Add following namespaces.

using Microsoft.Office.Server;
using  Microsoft.Office.Server.Search.Administration;

Use following method to populate all scopes of current site collection in dropdown.

private void GetScopes()
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
// Get the search context object.
SearchContext context = SearchContext.GetContext(site);
Scopes scopes = new scopes(context);
foreach(Scope scope in scopes.GetSharedScopes())
// Skip following default scopes
// Global Query Exclusion - Everything that should be omitted from all search by default
// Rank Demoted Sites - Sites whose rank will be demoted in click - distance calculation.

if(scope.Name != "Global Query Exclusion" && scope.Name !="Rank demoted Sites")
// Show scopes in dropdown

Sunday, July 7, 2013

CAML Query to get all documents from a Document Library

CAML query to retrieve all documents from all folders in a document library.

SPList lstDocs = SPContext.Current.Web.Lists.TryGetList("myDocLib");
SPQuery query = new SPQuery();
query.Query = @"<Where><BeginsWith><FieldRef Name = 'ContentTypeId' /><Value Type= 'ContentTypeId'>0x0101</Value></BeginsWith></Where>";
query.ViewAttributes = "Scope = 'RecursiveAll'";
SPListItemCollection itmsDocs = lstDocs.GetItems(query);