Showing posts with label Client object model. Show all posts
Showing posts with label Client object model. Show all posts

Thursday, December 24, 2020

Unauthorized exception while downloading file from SharePoint

In this article, How to download the SharePoint  library files in Document Library


 var file = clientContext.Web.GetFileByServerRelativeUrl(fileRef);

                clientContext.Load(file);

                clientContext.ExecuteQuery();                    

                ClientResult<Stream> streamResult = file.OpenBinaryStream();

                clientContext.ExecuteQuery();

#sharepoint #SharePoint Developer/  #O365 #Administrator/ #NET #jQuery #AngularJS #poweapps #powerautomate #spfx #pnp #workflo

Thursday, October 20, 2016

Client Object Model vs Server Object Model?

Server Object Model?
SharePoint server where the Server Object Model binaries

Example

inside Web Parts / Workflows.

Client Object Model?

client machines where the entire SharePoint binaries are not available.

Example
Windows Forms application in a client machine.

Update list item or change item value using Client Object Model


"Client" in the namespace.  For example, in the server object model you have:
Microsoft.SharePoint.SPSite
Microsoft.SharePoint.SPWeb
Microsoft.SharePoint.SPList

In the client object model you have:
Microsoft.SharePoint.Client.Site
Microsoft.SharePoint.Client.Web
Microsoft.SharePoint.Client.List


NameSpace:


Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll


Example Code:

ClientContext context = new ClientContext("http://peakfinders.com");

Web web = context.Web;

List list = web.Lists.GetByTitle("yourlistname");

CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems);

context.ExecuteQuery();

ListItem item = listItems[listItems.Count - 1];
item["Status"] = "Complete";
item.Update();

context.ExecuteQuery();

Add new item or Insert new item using CLient Object Model


"Client" in the namespace.  For example, in the server object model you have:
Microsoft.SharePoint.SPSite
Microsoft.SharePoint.SPWeb
Microsoft.SharePoint.SPList

In the client object model you have:
Microsoft.SharePoint.Client.Site
Microsoft.SharePoint.Client.Web
Microsoft.SharePoint.Client.List


NameSpace:


Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll


Example Code:

ClientContext context = new ClientContext("http://peakfinders.com");

Web web = context.Web;

List list = web.Lists.GetByTitle("yourlistname");

ListItemCreationInformation newItem = new ListItemCreationInformation();
ListItem listItem = list.AddItem(newItem);
listItem["Title"] = "Peakfinder";
listItem.Update();

context.ExecuteQuery();

Get By Search using Client Object Model


"Client" in the namespace.  For example, in the server object model you have:
Microsoft.SharePoint.SPSite
Microsoft.SharePoint.SPWeb
Microsoft.SharePoint.SPList

In the client object model you have:
Microsoft.SharePoint.Client.Site
Microsoft.SharePoint.Client.Web
Microsoft.SharePoint.Client.List


NameSpace:


Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll


Example Code:

ClientContext context = new ClientContext("http://peakfinders.com");
List list = context.Web.Lists.GetByTitle("yourlistname");
CamlQuery query = new CamlQuery();
query.ViewXml = @"<View>
    <Query>
        <Where>
        <Eq>
            <FieldRef Name='Status'/>
            <Value Type='Text'>Pending</Value>
        </Eq>
        </Where>
    </Query>
    </View>";

ListItemCollection listItems = list.GetItems(query);
context.Load(listItems, items => items.Include(
                                                item => item["Name"],
                                                item => item["Designation"],
                                                item => item["Status"]
                                                ));
context.ExecuteQuery();


Get By Row Limit using Client Object Model


“Client” in the namespace.  For example, in the server object model you have:

  • Microsoft.SharePoint.SPSite
  • Microsoft.SharePoint.SPWeb
  • Microsoft.SharePoint.SPList

In the client object model you have:

  • Microsoft.SharePoint.Client.Site
  • Microsoft.SharePoint.Client.Web
  • Microsoft.SharePoint.Client.List


NameSpace:


Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll


Example Code:

ClientContext context = new ClientContext("http://peakfinders.com");
List list = context.Web.Lists.GetByTitle("yourlistname");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><RowLimit>3</RowLimit></View>";

ListItemCollection listItems = list.GetItems(query);

context.Load(listItems);
context.ExecuteQuery();
context.ExecuteQuery();

Update List Items Client Object Model


“Client” in the namespace.  For example, in the server object model you have:
·         Microsoft.SharePoint.SPSite
·         Microsoft.SharePoint.SPWeb
·         Microsoft.SharePoint.SPList
In the client object model you have:
·         Microsoft.SharePoint.Client.Site
·         Microsoft.SharePoint.Client.Web
     ·         Microsoft.SharePoint.Client.List

NameSpace:


Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll


Example Code:

ClientContext context = new ClientContext("http://peakfinders.com");
List list = context.Web.Lists.GetByTitle("yourlistname");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
ListItemCollection items = list.GetItems(query);

context.Load(items);

context.ExecuteQuery();

foreach(ListItem item in items)
    if ((item.Id % 2) == 0)
    {
        item["Title"] += "**";
        item.Update();
    }

context.ExecuteQuery();

Get List Items Client Object Model

“Client” in the namespace.  For example, in the server object model you have:
·         Microsoft.SharePoint.SPSite
·         Microsoft.SharePoint.SPWeb
·         Microsoft.SharePoint.SPList
In the client object model you have:
·         Microsoft.SharePoint.Client.Site
·         Microsoft.SharePoint.Client.Web
     ·         Microsoft.SharePoint.Client.List

NameSpace:


Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll


Example Code:

ClientContext context = new ClientContext("http://peakfinders.com");
List list = context.Web.Lists.GetByTitle("yourlistname");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
ListItemCollection items = list.GetItems(query);

context.Load(list);
context.Load(items);

context.ExecuteQuery();

Friday, February 12, 2016

When we get retrive People or Group field returning semicolon hash then Name

1;#Deepak Kumar


Get User name:

new SPFieldLookupValue(properties.ListItem["Staff Member"].ToString()).LookupValue;


Get User ID:

new SPFieldLookupValue(properties.ListItem["Staff Member"].ToString()).LookupId;

Using Split fuction:

properties.ListItem["Staff Member"].ToString();

You are going to be returned their userID and username, so it will always be returned separated by ;#.



properties.ListItem["Staff Member"].ToString().split(";#")[1];

Tuesday, January 5, 2016

How to access the sharepoint 2013 list from another web application using CSOM

we have to add this reference

Microsoft.SharePoint.Client
Microsoft.SharePoint.Client.Runtime

ClientContext context = new ClientContext("http://peakfinders");

Web web = context.Web;

List list = web.Lists.GetByTitle(“Users”);

CamlQuery caml=new CamlQuery();

ListItemCollection items = list.GetItems(caml);

context.Load<List>(list
context.Load<ListItemCollection>(items
context.ExecuteQuery();

foreach (Microsoft.SharePoint.Client.ListItem item in items)

{

Console.WriteLine(item.FieldValues["Title"]);

}

Console.ReadLine();

Sunday, December 27, 2015

ConditionalScope using SharePoint Client Object Model

ClientContext context = new ClientContext("http://SiteUrl"); 

SP.List list = context.Web.GetCatalog(ListTemplateType.WebPartCatalog); 
BasePermissions perm = new BasePermissions(); 
perm.Set(PermissionKind.ManageLists); 

ConditionalScope scope = 
    new ConditionalScope(context, 
                         () => list.ServerObjectIsNull && context.Web.DoesUserHavePermissions(perm).Value); 
using (scope.StartScope()) 

    context.Load(list, l => l.Title); 

context.ExecuteQuery(); 

label1.Text = scope.TestResult.Value; 

if (scope.TestResult.Value) 

    label1.Text = list.Title; 
}  

Do and Don't do When we using SharePoint Client Object Model


Please follow below steps in SharePoint Client object Model Development:


  • ClientContext.ExecuteQuery before accessing any value properties
  • Don't use value objects returned from methods or properties in the same query.
  • When we methods or properties that return client objects in another method call in the same query
  • Group data retrieval on the same object together to improve performance
  • Specify which properties of objects you want to return
  • conditional scope to test for preconditions before loading data
  • Use an exception handling scope to catch exceptions

How to programmatically get permissions for list using client object model SharePoint 2013

//Get the lists

ClientContext clientContext = new ClientContext(_siteurl);
clientContext.AuthenticationMode =ClientAuthenticationMode.Default;
clientContext.Credentials = new System.Net.NetworkCredential
(“peakfinders”, “password@1”, “peakfinders”);
Web oweb = clientContext.Web;

            List myList = 
oweb .Lists.GetByTitle("Employee");

            roles = 
oweb.LoadQuery(
            myList.RoleAssignments.Include(
            roleAssign => 
roleAssign.Member,
            
roleAssign=> roleAssign.RoleDefinitionBindings.Include(
            roleDefine => 
roleDefine.Name, // for each role def, include roleDef’s Name
            
roleDefine=> roleDefine.Description,
            
roleDefine=> roleDefine.RoleTypeKind,
            
roleDefine=> roleDefine.BasePermissions)));
            
clientContext.ExecuteQuery();

            Dictionary dicpermission= new Dictionary();

            foreach (RoleAssignment ra in roles)
            {
                var rdc = ra.RoleDefinitionBindings;
                string permission = string.Empty;
                foreach (var strrp in rdc)
                {
                    permission += 
strrp.Name.ToString() +","+ strrp.Description.ToString() +","+ strrp.RoleTypeKind.ToString()+","+ strrp.BasePermissions.ToString();                  
                }
                
dicpermission.Add(ra.Member.Title, permission);

Tuesday, December 15, 2015

How to get all Sub Webs or SubSite using Client Object Model in SharePoint 2013

static string mainpath = "http://peakfinders/";
        static void Main(string[] args)
        {

            subsite(mainpath);
         
        }

        public static  void  subsite(string path)
        {
        
            try
            {
                ClientContext clientContext = new ClientContext( path );
                Web osweb = clientContext.Web;
                clientContext.Load(osweb, website => website.Webs, website => website.Title);
                clientContext.ExecuteQuery();
                foreach (Web oweb in osweb.Webs)
                {
                    string newpath = mainpath + oweb.ServerRelativeUrl;
                    getSubWebs(newpath);
                    Console.WriteLine(newpath + "\n" + oweb.Title );
   Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
              
            }
        
         
        }

Wednesday, October 14, 2015

How to retrieve User profile Service Properties using Client Object Model In windows Application or Console application

Solution Explorer, right-click on the "References" folder and then click on "Add Reference"

We have to add ddl:
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
Microsoft.SharePoint.Client.UserProfiles.dll

Namespace:

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;
Coding:

string siteUserName="nam";
string _siteurl="http://sharepoint.com";
string _sitepassword ="pass@word1";
string accountName ="raghupc\raghu";
ClientContext clientContext = new ClientContext(_siteurl);
clientContext.AuthenticationMode =ClientAuthenticationMode.Default;
clientContext.Credentials = new System.Net.NetworkCredential(_siteUserName, _sitepassword, _domainName);
Web oweb = clientContext.Web;
clientContext.ExecuteQuery();
PeopleManager peopleMang = new PeopleManager(clientContext);
PersonProperties personProp = peopleMang.GetPropertiesFor(accountName);
clientContext.Load(personProp, p => p.AccountName, p => p.Email, p => p.DisplayName);
clientContext.ExecuteQuery();
Label1.Text= personProp.AccountName;
Label2.Text= personProp.Email;
Label3.Text =personProp.DisplayName;

Tuesday, October 6, 2015

How to get field values ECMA Script/Javascript using CSOM?

In this below script,get field values ECMA Script/Javascript using CSOM

get field values ECMA Script/Javascript using CSOM

SharePoint client object model used to retrieve, update, and manage data in SharePoint 2013.


Types:
1.Server Object Model
2.Client Object Model
3.Javascript Library
4.Rest Service/OData Library

Loads the SP.Runtime.js and SP.js files by using the getScript function in jQuery.


Title – SP.ListItem.get_item('Title');

ID – SP.ListItem.get_id();

Url -SP.ListItem.get_item('urlfieldname').get_url()

Description – SP.ListItem.get_item('descriptionfieldname').get_description();

Current Version – SP.ListItem.get_item("_UIVersionString");

Lookup field – SP.ListItem.get_item('LookupFieldName’).get_lookupValue(); // or get_lookupID();

Created By – SP.ListItem.get_item("Author").get_lookupValue();

Modified by – SP.ListItem.get_item("Editor").get_lookupValue();

Choice Field – SP.ListItem.get_item('ChoiceFieldcolumnName');

Created Date – SP.ListItem.get_item("Created");

Modified Date – SP.ListItem.get_item("Modified"); -> case sensitive does not work with 'modified’

File  – SP.ListItem.get_file();

File Versions -  File.get_versions();.

Content Type – SP.ListItem.get_contentType();

Parent List – SP.ListItem.get_parentList();

Note:  ('LookupFieldName’).get_lookupValue() sometimes returns an array of data, especially when your lookup allows multiple values.
For this,you will need to iterate the array and get each value individually.

 SP.ListItem.get_item('LookupFieldName’)[0].get_lookupValue();

For Arrays:


       for(var i = 0; i < oListItem.get_item("LookupFieldName").length; i++)
 {
      alert(oListItem.get_item("LookupFieldName")[i].get_lookupId()); // or get_lookupValue()
 }

Tuesday, March 17, 2015

how to create CRUD operation in SharePoint App in Client Object Model?

Add List item
how to create a custom properties in  user profile service application



Open to Central Adminstration->Application Management->Manage Service Applications-> Click on the User Profile Service Application.