Archive

Archive for the ‘C#’ Category

How To: Remove Content Type from List / Library Programmatically

July 30, 2013 4 comments

Guys,

Quick code for removing default content type from list / library.

Generally, we need it while we create new list / library with our custom Content Type on feature activation for our custom solution.

 /// <summary>
 /// Removes the default CT from list.
 /// </summary>
 /// <param name="currentWeb">Represent current web of web application</param>
 /// <param name="listNames">Represent list names from where default content type need to remove</param>
 private void RemoveDefaultCTFromList(SPWeb currentWeb, List<string> listNames)
 {
 for (int i = 0; i < listNames.Count; i++)
 {
 try
 {
 SPList list = currentWeb.Lists.TryGetList(listNames[i]);
 if (list != null)
 {
 SPContentType itemCT = list.ContentTypes["Item"];
 if (itemCT != null)
 {
 list.ContentTypes.Delete(itemCT.Id);
 list.Update();
 }

 list.EnableFolderCreation = false;
 list.Update();
 }
 else
 {
 Log.LogWriter(null, string.Format("List '{0}' does not exist in current web", listNames[i]));
 }
 }
 catch (Exception ex)
 {
  // Error handling code
 }
 }
 }

Hope, it will help to somebody to quick reuse.

Happy SharePointing !!!


								

How To: Click Once application with SharePoint 2010

October 11, 2012 Leave a comment

Guys !!

Today, one of my friend was looking for the solution, where he can open Desktop application (Client side) from SharePoint site using browser.

It seems interesting for me as i did not work before. I got solution on internet which is really useful.

Using Click Once Application(also known as Smart Client application), we can achieve same.

Ingo has given very nice article, how we can create click once application with SharePoint 2010.

Click here to see his article.

Happy Coding !!!

SharePoint 2010: Copy Document Set to another library Programmatically

June 19, 2012 6 comments

SharePoint 2010 is having new feature called Document Set.

This a great feature to manage different set of documents within one document library. Document Set is very similar to folder within a document library but it comes with a lot of great useful features

Document Set is content type which must be attached in library before use. To use document set content type “Document Set” feature must be activated in site.

Also, Workflows can be attached using SharePoint designer for document sets.


using (SPSite site = new SPSite("http://jshah:1111"))
using (SPWeb web = site.OpenWeb())
{
   SPList sourceList = web.Lists["Source"];
   SPListItem sourceItem = sourceList.Folders[0];
   DocumentSet documentSet = DocumentSet.GetDocumentSet(sourceItem.Folder);

   SPList targetList = web.Lists["Target"];
   SPContentTypeId contentTypeId = targetList.ContentTypes["Document Set"].Id;
   byte[] documentSetData = documentSet.Export();
   string documentSetName = documentSet.Item.Name;
   SPFolder targetFolder = targetList.RootFolder;
   Hashtable properties = sourceItem.Properties;
   DocumentSet.Import(documentSetData, documentSetName, targetFolder, contentTypeId,     properties, web.CurrentUser);
}

If you get the “DocID: Site prefix not set” error during the “DocumentSet.Import” you can use the following PowerShell command to fix that:

$site = Get-SPSite http://jshah:1111 

$properties = $site.RootWeb.Properties

$properties[“docid_msft_hier_siteprefix”] = “”

$properties.Update()

Ref: http://www.thesharepointblog.net/Lists/Posts/Post.aspx?List=815f255a-d0ef-4258-be2a-28487dc9975c&ID=117

.Net Managed Client Object Model: Fetch All Webs, Libraries, Items

June 14, 2012 9 comments

In SharePoint 2010, we have 3 client object model.

  1. .Net Managed Client Object Model
  2. Silverlight
  3. ECMA Script / JavaScript

Today, I am presenting .NET Managed Client Object Model to retrieve all webs, libraries, items from SharePoint.

Prerequisites References for your desktop application:

  1. Microsoft.SharePoint.Client.dll
  2. Microsoft.SharePoint.Client.Runtime.dll

My Custom Classes to feel like we are working on SharePoint Server Object model:

public class SPWeb
 {
     public string WebGUID { get; set; }
     public string Title { get; set; }
     public string ServerRelativeUrl { get; set; }
     public string ParentType { get; set; }
     public SPBase Parent { get; set; }
 }
 public class SPList
 {
     public string ListGUID { get; set; }
     public string Title { get; set; }
     public string ParentWebUrl { get; set; }
     public string RootFolderServerRelativeUrl { get; set; }
 }

public class SPFolder
 {
     public string ID { get; set; }
     public string UniqueID { get; set; }
     public string Name { get; set; }
     public string Title { get; set; }
     public string ParentWebUrl { get; set; }
     public string ListName { get; set; }
     public string ServerRelativeUrl { get; set; }
     public string ParentFolderServerRelativeUrl { get; set; }
 }

 public class SPListItem
 {
     public string ID { get; set; }
     public string Name { get; set; }
     public string Title { get; set; }
     public string ServerRelativeUrl { get; set; }
     public string Modified { get; set; }
     public string ModifiedBy { get; set; }
     public string CreatedBy { get; set; }
     public string Size { get; set; }
     public string Created { get; set; }
     public string UniqueId { get; set; }
     public string ListName { get; set; }
 }

Methods which is used to fetch Webs / libraries / Items:


public List<SPWeb> GetAllWebs(string webURL)
{
    var webColl = new List<SPWeb>();
    try
    {
    var currentWeb = _ctx.Site.OpenWeb(webURL);
    var allWebs = currentWeb.Webs;
    var webCollection = _ctx.LoadQuery(
                                      allWebs.Include(web => web.Title,
                                      web => web.Id,
                                      web => web.ServerRelativeUrl));
    _ctx.ExecuteQuery();
     webColl.AddRange(webCollection.Select(web => new SPWeb
                                    {
                                      Title = web.Title,
                                      WebGUID = web.Id.ToString(),
                                      ServerRelativeUrl = web.ServerRelativeUrl
                                     }));
    }
    catch (Exception ex)
    {
      // error log
    }
 return webColl;
}

public List<SPList> GetAllLibraries(string webURL)
{
   var listColl = new List<SPList>();
   try
   {
     var currentWeb = _ctx.Site.OpenWeb(webURL);
     var query = from list in currentWeb.Lists
                 where list.BaseType == BaseType.DocumentLibrary
                 select list;
     var AllLists = currentWeb.Lists;
     var listCollection = _ctx.LoadQuery(query.Include(myList => myList.Title,
                                       myList => myList.Id,
                                       myList => myList.RootFolder.ServerRelativeUrl,
                                       myList => myList.ParentWebUrl,
                                       myList => myList.Hidden,
                                       myList => myList.IsApplicationList));
      _ctx.ExecuteQuery();

      listColl.AddRange(from list in listCollection
                        where !list.Hidden
                        select new SPList
                        {
                            Title = list.Title,
                            ListGUID = list.Id.ToString(),
                            RootFolderServerRelativeUrl = list.RootFolder.ServerRelativeUrl,
                            ParentWebUrl = list.ParentWebUrl
                         });
   }
   catch (Exception ex)
   {
       // error log
   }
  return listColl;
}

public List<SPFolder> GetAllFolder(string webURL, string listName, string folderName)
{
    var itemColl = new List<SPFolder>();
    try
    {
      var currentWeb = _ctx.Site.OpenWeb(webURL);
      var currentList = currentWeb.Lists.GetByTitle(listName);

      var query = new CamlQuery();

      if (folderName.Length > 0)
         query.FolderServerRelativeUrl = folderName;

      query.ViewXml = @"<View><Query><Where>
                        <Or>
                          <Eq>
                             <FieldRef Name='ContentType' />
                             <Value Type='Text'>Document Set</Value>
                          </Eq>
                          <Eq>
                             <FieldRef Name='ContentType' />
                             <Value Type='Text'>Folder</Value>
                          </Eq>
                        </Or>
                        </Where></Query></View>";

      var listitems = currentList.GetItems(query);
      _ctx.Load(listitems);
      _ctx.ExecuteQuery();

      itemColl.AddRange(listitems.ToList().Select(item => new SPFolder()
                       {
                           ID = Convert.ToString(item["ID"]),
                           UniqueID = Convert.ToString(item["GUID"]),
                           ListName = listName,
                           ParentWebUrl = webURL,
                           Title = Convert.ToString(item["FileLeafRef"]),
                           Name = "folder",
                           ServerRelativeUrl = Convert.ToString(item["FileRef"])
                       }).AsEnumerable());
  }
  catch (Exception ex)
  {
     // error log
  }
  return itemColl;
}
public List<SPListItem> GetAllItems(string webURL, string listName, string folderName)
{
    var itemColl = new List<SPListItem>();
    try
    {
        var currentWeb = _ctx.Site.OpenWeb(webURL);
        var currentList = currentWeb.Lists.GetByTitle(listName);
        var query = new CamlQuery();

        if (folderName.Length > 0)
           query.FolderServerRelativeUrl = folderName;

        var myquery = from myitems in currentList.GetItems(query)
                      select myitems;

        var listitems = _ctx.LoadQuery(myquery.Include(myitem => myitem["ID"],
                                      myitem => myitem["FileLeafRef"],
                                      myitem => myitem["Modified"],
                                      myitem => myitem["File_x0020_Size"],
                                      myitem => myitem["Modified_x0020_By"],
                                      myitem => myitem["Created_x0020_By"],
                                      myitem => myitem["FileRef"],
                                      myitem => myitem["UniqueId"],
                                      ));

         _ctx.ExecuteQuery();

         foreach (var nitem in listitems.Select(item => new SPListItem
         {
               ID = Convert.ToString(item["ID"]),
               ParentWebUrl = webURL,
               Title = Convert.ToString(item["FileLeafRef"]),
               Modified = item["Modified"] != null ? Convert.ToString(item["Modified"]) : string.Empty,
               Size = item["File_x0020_Size"] != null ? Convert.ToString(item["File_x0020_Size"]) : string.Empty,
               CreatedBy = item["Created_x0020_By"] != null ? Convert.ToString(item["Created_x0020_By"]) : string.Empty,
               ModifiedBy = item["Modified_x0020_By"] != null ? Convert.ToString(item["Modified_x0020_By"]) : string.Empty,
               UniqueId = item["UniqueId"].ToString(),
               ServerRelativeUrl = Convert.ToString(item["FileRef"]),
               ListName = listName
         }))

         itemColl.Add(nitem);
    }
    catch (Exception ex)
    {
         // error log
    }
    return itemColl;
}

You can add / remove any property from Custom Class according to your requirement.

Happy Coding !!!

How To: Export Site Collection To XML

October 22, 2011 2 comments

Recently, I was working on project. And I need to know how many sites, lists available in our site collection.

I was looking out put in XML format.

So, I write utility which takes input of site collection and it export structure of site collection and lists.

public static void ExportToXML(string url)
        {
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            XmlNode sitesNode = doc.CreateElement("Site");
            XmlAttribute x_Url = doc.CreateAttribute("url");
            x_Url.Value = url;
            sitesNode.Attributes.Append(x_Url);

            XmlAttribute copygroupattr = doc.CreateAttribute("CopyGroups");
            copygroupattr.Value = "true";
            sitesNode.Attributes.Append(copygroupattr);

            SPSite site = new SPSite(url);
            // Console.WriteLine("<Site>");
            foreach (SPWeb web in site.AllWebs)
            {
                XmlNode webnode = doc.CreateElement("Web");
                XmlAttribute titleattribute = doc.CreateAttribute("title");
                titleattribute.Value = (web.Name.Length > 0) ? web.Name : web.Title;
                webnode.Attributes.Append(titleattribute);

                XmlAttribute weburlattribute = doc.CreateAttribute("url");
                weburlattribute.Value = web.Url;
                webnode.Attributes.Append(weburlattribute);

                Console.WriteLine("<web title=\"" + web.Name + "\" url=\"" + web.Url + "\">");
                foreach (SPList list in web.Lists)
                {

                    XmlNode listnode = doc.CreateElement("list");
                    XmlAttribute listattribute = doc.CreateAttribute("title");
                    listattribute.Value = list.Title;
                    listnode.Attributes.Append(listattribute);

                    XmlAttribute listurlattribute = doc.CreateAttribute("url");
                    listurlattribute.Value = list.DefaultViewUrl;
                    listnode.Attributes.Append(listurlattribute);
                    if (list.EventReceivers.Count > 0)
                    {
                        XmlAttribute listEventattribute = doc.CreateAttribute("EventHandler");
                        listEventattribute.Value = "true";
                        listnode.Attributes.Append(listEventattribute);
                    }
                    XmlAttribute listGuidattribute = doc.CreateAttribute("Guid");
                    listGuidattribute.Value = list.ID.ToString();
                    listnode.Attributes.Append(listGuidattribute);

                    Console.WriteLine("<list title=\"" + list.Title + "\" url=\"" + list.DefaultViewUrl + "\"  Guid=\"" + list.ID.ToString() + "\">");
                    //SPFieldCollection fields = list.Fields;
                    //foreach (SPListItem item in list.Items)
                    //{
                    //    Console.WriteLine("<item>");
                    //    foreach (SPField field in fields)
                    //    {
                    //        //note put a check for null field values here
                    //        Console.WriteLine("<property title=\"" + field.Title + "\" value=\"" + item[field.Id].ToString() + "\"/>");
                    //    }
                    //    Console.WriteLine("</item>");
                    //}
                    Console.WriteLine("</list>");
                    webnode.AppendChild(listnode);
                }
                Console.WriteLine("</web>");
                sitesNode.AppendChild(webnode);
            }
            Console.WriteLine("</site>");

            doc.AppendChild(sitesNode);
            doc.Save("C:\\Export.xml");
            Console.ReadLine();
        }

Ref: http://withinsharepoint.com/archives/87

Happy Coding!!!