Showing posts with label Sharepoint Client Object Model. Show all posts
Showing posts with label Sharepoint Client Object Model. Show all posts

Friday, November 27, 2015

SharePoint Migration Lookup error

There was site in SharePoint 2010 and I was planning to move it to SharePoint 2013 version by performing a Content db migration .

The site had a list which consists of lookup columns ,these were lookup to other list.But the point here was that these columns were hidden while it was created through element.xml in the solution .The list was working fine in SharePoint 2010 ,But when I migrated the 2010 site to SharePoint 2013 the link of the lookup is lost and the data is been displayed as a text field Eg: "#2;lookupValue" etc .
This was creating few problems in my solution due to mismatch in the values of the list itms .I had to fix the lookup column .Below is the resolution to this migration error



I placed the below code in Content Editor WebPart and made the field readable,This changed the column back as lookup .Later you can change the column to readonly =true


<content id="Main" contentplaceholderid="PlaceHolderMain" runat="server"></content><script language="ecmascript" type="text/ecmascript">
        var fieldCollection;
        var field;
        var list;
        function UpdateField() {
            var clientContext = SP.ClientContext.get_current();
            if (clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("ListA");
                this.fieldCollection = list.get_fields();
                this.field = fieldCollection.getByTitle("Column1");
                this.field.set_readOnlyField(false);
                this.field.update();

            clientContext.load(this.fieldCollection);
            clientContext.load(this.field);
                clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
            }
        }
        function OnLoadSuccess(sender, args) {
            alert("Field deleted successfully.");
        }
        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
</script><input type="button" id="btnUpdateField" onclick="UpdateField()" value="Change ReadOnly"/> 

Thursday, September 11, 2014

Sharepoint Client Object find if the folder exists in Sharepoint list or library

Below code finds if the Folder is present or not in a SharePoint List or library from client side



public void CheckFolderExists(string siteURL)
        {


            ClientContext clientContext = new ClientContext(siteURL);
            List oList = clientContext.Web.Lists.GetByTitle("ListA");

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View Scope='RecursiveAll'>"
                                                + "<Query>"
                                                         + "   <Where>"
 + "      <Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq>"
                                                         + "   </Where>"
                                                + "</Query>"
                                + "</View>";
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(collListItem);
            clientContext.ExecuteQuery();

            string a = "";
            foreach (ListItem oListItem in collListItem)
            {
               
               a = a + oListItem["Title"];
               
            }
            label1.Text = a;

        }


The code will give you all the folders in the list ,you can play with CAML query or object to get the folder which you need

Sharepoint Client Object model create Folders in Document Library or list programmatically

Below methods will create a Folder or Subfolders in SharePoint library from client side.
Providing the relative path you can create the subfolder e.i  folder inside a folder as well

DDL used are Microsoft.Sharepoint.client and Microsoft.Sharepoint.Client.runtime.


public void CreateListFolder(string siteUrl, string listName, string relativePath, string folderName)
        {
            using (ClientContext clientContext = new ClientContext(siteUrl))
            {
                Web web = clientContext.Web;
                List list = web.Lists.GetByTitle(listName);
                list.EnableFolderCreation = true;
              
                ListItemCreationInformation newItem = new ListItemCreationInformation();
                newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
                newItem.FolderUrl = siteUrl +"/"+ listName;
                if (!relativePath.Equals(string.Empty))
                {
                    newItem.FolderUrl += "/" + relativePath;
                }
                newItem.LeafName = folderName;
                ListItem item = list.AddItem(newItem);
                 //updating the metadata for the folder
                item["Col1"] = "Folder Property-1";
                item.Update();
                clientContext.Load(list);
                clientContext.ExecuteQuery();
            }


You can call the method a below
CreateListFolder(@"http://WebApplication:777", "ListA", "", "FolderA");



Other way of creating it is


  public void CreateLibraryFolder2()
        {
            using (var clientContext = new ClientContext(@"http://WebApplication:777/"))
            {
                var web = clientContext.Web;
                var lst = web.Lists.GetByTitle("Shared Documents");
                var fld1 = lst.RootFolder.Folders.Add("FirstLevel2");
                var fld2 = fld1.Folders.Add("SecondLevel2");      
                fld1.Update();
                fld2.Update();

                var t1 = lst.RootFolder.Folders.Add("FirstLevel7");
                var t2 = t1.Folders.Add("SecondLevel7");
                fld1.Update();
                fld2.Update();
                               

                clientContext.ExecuteQuery();
               
            }
        }

        
Thanks to the references found by googling :)

SharePoint Client object model to upload files into the Document library

Below code uses the managed client object model to upload files to SharePoint library from the client system.
I uploaded the files to SharePoint and my requirement was to upload  into particular folder of the document library through a console application. DDL used are Microsoft.Sharepoint.client and Microsoft.Sharepoint.Client.runtime.
Below method uploads the files like PDF or Excel or word document into particular folder of the SharePoint library

public void UploadDocument(string fileName, string filePath)
        {

            ClientContext ctx = new ClientContext("http://WebApplication:777/");

            Web currentWeb = ctx.Web;
            ctx.Load(currentWeb);
            ctx.ExecuteQuery();

            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {

Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/Shared Documents/" + fileName, fs, true);

            }

Microsoft.SharePoint.Client.File getFile = currentWeb.GetFileByServerRelativeUrl("/Shared Documents/" + fileName);
            ctx.Load(getFile);
            ctx.ExecuteQuery();

            //check out to make sure not to create multiple versions
            getFile.CheckOut();

            ListItem item = getFile.ListItemAllFields;
            item["testcol1"] = "T1";
            item["testDateCol2"] = DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ssZ");
            //item["ContentTypeId"] = "0x0101";
            item.Update();
           
            // use OverwriteCheckIn type to make sure not to create multiple versions
            getFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
            ctx.ExecuteQuery();

        }

You can upload into folder by changing the code as below
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/Shared Documents/Folder1" + fileName, fs, true);


You can then call the method in your application as below

UploadDocument("TestDocument.docx", @"E:\Path1\TestDocument.docx");