Showing posts with label console application. Show all posts
Showing posts with label console application. Show all posts

Tuesday, March 5, 2013

SharePoint 2010 : Query using SPMetal entity

In SharePoint 2010, we can use LINQ queries to search data within SharePoint site. In previous SharePoint versions, I tend to use CAML queries instead, which is an efficient way to look for items. However, LINQ queries are faster and simpler to implement.
For more information on LINQ queries: follow this URL
For using LINQ within SharePoint, Microsoft has provided a tool named SPMetal.exe which resides in the 14 hive folder. This tool generates an entity class which we can add to our Visual Studio solution to get intellisense and use the entity classes for fetching data from SharePoint site.

Using SPMetal.exe

Go to command prompt and navigate to
  • C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\bin
  • Type SPMetal.exe /web:http://sharepointsite /code:C:\MyLINQEntity.cs

Now if you open the file, we just created, you can see all the lists, libraries have their classes with content types mentioned. It might happen that some custom content types are replaces with Item which is by default behaviour; you can modify the content types for the actual ones (you will get it in the intellisense).

Now that you add your .cs file to your Visual Studio project, you can use it for fetching items in SharePoint site.

using (PropertiesEntityDataContext context = new PropertiesEntityDataContext(SPSiteAddress))
{
//creating object from the Entity
EntityList<legalcasedocumentset> documentSet = context.GetList<legalcasedocumentset>(libName);
var first3Items = from item in documentSet.ScopeToFolder(folderURL, true)
where item.Name == docSetName
select item;

Tuesday, February 12, 2013

Inserting Terms to the Term Store : SharePoint 2010

Managed Metadata, one of my most widely used feature in SharePoint 2010 comes with many exciting things. I tend to use them very often depending on the business case. Recently I came across a scenario where I had to Insert almost 1000 items to the Term Store with their sub sets. In my case it was the list of manufacturers and their products. So I wrote a console application to do the same. In my case, I had a excel sheet of values which I read using my previously created ReadExcel.cs. Here is the code :


 using (SPSite site = new SPSite(""))
            {
                TaxonomySession _TaxonomySession = new TaxonomySession(site);

                //Get instance of the Term Store
                TermStore _TermStore = _TaxonomySession.TermStores[""];

                //Instance of Term Store
                Group _Group = _TermStore.Groups[""];

                //Instance of Term Group
                TermSet _TermSet = _Group.TermSets[""];

                FileStream filename = File.Open(@"", FileMode.Open);

                for (int i = 1; i &lt;= 1000; i++)
                {

                   // ReadExcel.ReadxlswithID() is my function to read the row values in Excel

                    if (ReadExcel.ReadxlswithID(filename, "A" + i.ToString(), "Sheet2") != null)
                    {
                        string manufacturer = ReadExcel.ReadxlswithID(filename, "A" + i.ToString(), "Sheet2");

                        string product = ReadExcel.ReadxlswithID(filename, "B" + i.ToString(), "Sheet2");

                        TermCollection terms = _TermSet.GetTerms(manufacturer, true);

                        try
                        {

                            if (terms.Count &gt; 0)
                            {
                                Term tExists = _TermSet.GetTerm(terms[0].Id);
                 
                                //Get the branch of terms within terms
                                TermCollection subTermExists = tExists.GetTerms(50);

                                bool termAlreadyExists = false;

                                for (int j = 0; j &lt; subTermExists.Count; j++)
                                {
                                    if (product == subTermExists[j].Name)
                                    {
                                        termAlreadyExists = true;
                                        break;
                                    }
                                }

                                if (e == false)
                                {
                                    Term subTerm = tExists.CreateTerm(product, 1033);

                                    _TermStore.CommitAll();
                                }

                            }
                            else
                            {

                                Term _term = _TermSet.CreateTerm(manufacturer, 1033);

                                Term _sTerm = _term.CreateTerm(product, 1033);

                                _TermStore.CommitAll();

                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString() + product);
                        }
                    }

                }
            }

For any queries, please write to me.

Friday, February 8, 2013

SharePoint 2010 : Copying Document sets programatically from one library to another with metadata


Many of you must have come across situations where you have to move the already created Document sets (with a whole bunch of documents in it) from one location to another due to organization re-structure or may be introduction of some new ways of working.
I did come across similar situation where I had to move 5000 Document Sets with documents in them counting 60,000 in total from one library to another. In my case the document sets are within a folder in the source library. Since I am not a folder-loving developer, I tend not to use them frequently.

So here is my code to copy the document sets from source library and put it into the destination library without folders.
Please note:

  • Metadata columns (for Document Set and Document) should read same in the destination library and the source library if you want them to be copied along the process
  • Make sure you have set up Document Set content types in the destination library
I am using a console application so add reference to  
  • Microsoft.SharePoint
  • Microsoft.Office.DocumentManagement.DocumentSets
and make sure your target machine and build is set to proper values.

using (SPSite site = new SPSite("http://sharepointsite"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFolder folder = web.GetFolder("folderURL"); // sharepointsite/library/folder

                    SPList sourceList = web.Lists["sourcelistname"];

                    SPQuery query = new SPQuery();                    
                    query.Folder = folder;


                    SPListItemCollection itemColl = sourceList.GetItems(query);
                    foreach (SPListItem sourceItem in itemColl)
                    {                        

                        if (sourceItem.ContentType.Name == "Document Set")
                        {
                            DocumentSet documentSet = DocumentSet.GetDocumentSet(sourceItem.Folder);

                            SPList targetList = web.Lists["targetListName"];

                            SPContentTypeId contentTypeId = targetList.ContentTypes["destination document library"].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);
                        }
                    }
                }
            }