JSOM - Load mutliple SharePoint objects in one request - sharepoint

Is there a way to load multiple objects in one request like this:
var context = new SP.ClientContext.get_current();
this.web = context.get_web();
this.site = context.get_site();
var list = this.web.get_lists().getByTitle(window.sessionStorage.getItem('selectedContentType'));
var query = '<View Scope=\'RecursiveAll\'><Query>' + $('.camlQuery').val() + '</Query></View>';
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(query);
this.items = list.getItems(camlQuery);
context.load(this.site);
context.load(this.items, 'Include(ID,DocIcon,LinkFilename,FileRef,FileLeafRef,Title,ContentType,SupplierPGProduct)');
context.executeQueryAsync(Function.createDelegate(this, get_Data_onSuccess), Function.createDelegate(this, get_Data_onFailure));
}
In this example, I mean this.site and this.items in one async request?
Or do I have to load first this.site and when the request is successful, then load the this.items?

I've found the answer in sharepoint.stackexchange.
Here is the link to the answer.
https://sharepoint.stackexchange.com/a/227984/47825

Related

NetSuite RestLet call from SuiteLet Client

I am trying to call a RestLet webservice/URL from another SuiteScript. As i understand I need to use the http/https module to do so. But I am not able to find some example or steps to do so.
Planning to use this code in SS2.0-
var response = http.post({
url: 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=601&deploy=1',
body: myDataObj, // json object
headers: headerObj // json obj
});
The below code works for me.
var nameValue = "arin";
var myDataObj = {
"name" : nameValue
};
var myRequest = {};
myRequest.headers = {};
myRequest.headers["Authorization"] = 'NLAuth nlauth_account=TSTDRV158xxxx,nlauth_email=XXXX,nlauth_signature=XXXX,nlauth_role=3';
myRequest.headers["Content-Type"] = 'application/json';
myRequest.headers["Accept"] = '*/*';
myRequest.url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=601&deploy=1'; // RESTlet
// URL
myRequest.method = "POST";
myRequest.body = JSON.stringify(myDataObj);
// myRequest.body = myDataObj;
var myResponse = https.post(myRequest);
And reading the response data for JSON return ...
log.debug("Resonse", myResponse.body);
log.debug("Resonse", myResponse.code);
var data = myResponse.body;
var retObj = JSON.parse(data);
log.debug("Resonse Ret city - ", retObj.city);
Here's a basic example of how to do it:
var myRequest = {};
myRequest.headers = {};
myRequest.headers["Authorization"] = 'NLAuth nlauth_account=TSTDRVXXXXX, nlauth_email=xxx#xxx.com, nlauth_signature=XXXXXXX, nlauth_role=3';
myRequest.headers["contentType"] = 'application/json';
myRequest.url = 'https://XXXXXXXXX'; //RESTlet URL
myRequest.body = myDataObj;
var myResponse = https.post(myRequest);
Be careful exposing this on clientside scripts. You don't want to expose your credentials.

Trying to get all records of a generic list using Sharepoint and Microsoft Graph api

When trying to get records of a list in SharePoint i keep getting Response like:
{"#odata.context":"https://graph.microsoft.com/beta/$metadata#users('123')/sharepoint/sites('456')/lists('789')/items","value":[]}
I was able to run through all sites and lists but still fail on items. The list has the GenericList template. However on another list with the template DesignCatalog i were able to get all items. Is "/items" the wrong way to get records of a generic list?
Here is a snippet of my current Code:
const string serviceEndpoint = "https://graph.microsoft.com/beta/";
HttpClient client = new HttpClient();
var token = await _authenticationHelper.GetTokenAsync();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
// get the site
HttpResponseMessage responseGetSites = await client.GetAsync(new Uri(serviceEndpoint + "sharePoint:/Intranet"));
if (responseGetSites.IsSuccessStatusCode)
{
string responseContent = await responseGetSites.Content.ReadAsStringAsync();
var jResult = JObject.Parse(responseContent);
siteItem = JsonConvert.DeserializeObject<SiteItemModel>(jResult.ToString());
// get all lists with the given site id
HttpResponseMessage responseGetLists = await client.GetAsync(new Uri(serviceEndpoint + "sharepoint/sites/" + siteItem.SiteId + "/lists"));
if (responseGetLists.IsSuccessStatusCode)
{
string responseContent2 = await responseGetLists.Content.ReadAsStringAsync();
var jResult2 = JObject.Parse(responseContent2);
foreach (JObject listresponse in jResult2["value"])
{
ListItemModel desiralizedItemModel = JsonConvert.DeserializeObject<ListItemModel>(listresponse.ToString());
listItemCollection.Add(desiralizedItemModel);
}
// find a specific list
string listId = listItemCollection.Where(w => w.listName == "MyTestlist").First().listId;
// get all records with of the given list
HttpResponseMessage responseGetItems = await client.GetAsync(new Uri(serviceEndpoint + "sharepoint/sites/" + siteItem.SiteId + "/lists/" + listId + "/items"));
if (responseGetItems.IsSuccessStatusCode)
{
string responseContent3 = await responseGetItems.Content.ReadAsStringAsync();
var jResult3 = JObject.Parse(responseContent3);
I had the same problem. I had to add "Sites.ReadWrite.All" permission under MS Graph, not under sharepoint (I was writing to the list as well, but "Sites.Read.All" should work).

SharePoint CAML query gets (401) Unauthorized exception

I have a query which looks like this:
var site = properties.Site;
var context = new ClientContext(site.Url);
List list = context.Web.Lists.GetByTitle(properties.ListTitle);
var query = new CamlQuery();
query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/>" +
"<Value Type='Text'>" + fieldName + "</Value></Eq></Where></Query></View>";
ListItemCollection itemCollection = list.GetItems(query);
context.Load(itemCollection);
context.ExecuteQuery();
In this scenario properties is an SPItemEventProperties.
Whenever it gets to ExecuteQuery(), it throws an exception: The remote server returned an error: (401) Unauthorized.
What could be the cause of this?
Looking at your code I guess this is RER associated with list item action. It happens that if you run it from host web (rather than app web) or you use CSOM it fails to authencitate back to SharePoint. Most likely when you will try to debug your code you will see that your RER has not received a valid context token (SPRemoteEventProperties.ContextToken is an empty string). Additionally the way you create your context using constructor
var context = new ClientContext(site.Url);
Does not deal with authenticateion. You have token methods to do that.
var context = TokenHelper.CreateRemoteEventReceiverClientContext(properties)
This will return a valid context as long as this event is on app web.
If this does not resolve your problem you will need to switch to use app permissions in your AppManifest and build a proper Realm from your SPHostUrl
var siteUrl = properties.Site.Url;
var siteUri = new Uri(siteUrl);
var realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken;
using (var context = TokenHelper.GetClientContextWithAccessToken(siteUrl, token))
{
}
Let me know if that helps.

How to retrieve all settings with OrmLiteAppSettings in one call?

I'm using the TextFileSettings and OrmLiteAppSettings together via MultiAppSettings, but would prefer to pre-read all the database settings in one call versus on demand, is there a way to do that, so that everything is in memory?
Below is the relevant code:
OracleDialect.Provider.NamingStrategy = new OrmLiteNamingStrategyBase();
OracleDialect.Provider.StringSerializer = new JsonStringSerializer();
var fileSettings = new TextFileSettings(ConfigUtils.GetAppSetting("PathToSecuredFile"));
var dbFactory = new OrmLiteConnectionFactory(fileSettings.GetString("LeadDbConfigKey"), OracleOrmLiteDialectProvider.Instance);
var dbSettings = new OrmLiteAppSettings(dbFactory);
var multiSettings = new MultiAppSettings(fileSettings, dbSettings);
container.Register<IAppSettings>(c => multiSettings);
Thank you,
Stephen
To preload all db App Settings you can just read the entire ConfigSetting db table into a .NET Dictionary and wrap it in DictionarySettings, e.g:
using (db = dbFactory.Open())
{
var allDbSettings = db.Dictionary<string,string>(
db.From<ConfigSetting>().Select(x => new { x.Id, x.Value}));
var multiSettings = new MultiAppSettings(
fileSettings,
new DictionarySettings(allDbSettings));
}

Root site collection in Javascript

How to get the Root Site collection url when the context is in a child site, in JavaScript or JQuery.
You could use the following using client object model
var clientContext = new SP.ClientContext();
var owebsite = clientContext.get_site.get_rootWeb();
Without client object model you can use the following
var siteCollectionPath= _spPageContextInfo.siteServerRelativeUrl;
var clientContext = new SP.ClientContext.get_current();
this.web = clientContext.get_site().get_rootWeb();
It's working for me.
Do you mean root web or root site collection?
This one will get you the root site collection:
_spPageContextInfo.siteAbsoluteUrl.replace(_spPageContextInfo.siteServerRelativeUrl, _spPageContextInfo.siteServerRelativeUrl == \"/\" ? \"/\": \"\") + \""
From my post: http://www.rdacorp.com/2015/03/alternate-solution-alternate-css-url-sharepoint-2013-online/
Below sample script shows how you can retrieve root web. The onQuerySucceedSample function alerts root site title.
getRootWeb = function () {
//Get and load a reference to the root web of the current site collection.
var ctx = new SP.ClientContext.get_current();
var site = ctx.get_site();
this.rootWeb = site.get_rootWeb();
ctx.load(this.rootWeb);
//Ask SharePoint to pull data for us
ctx.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceed),Function.createDelegate(this, this.onQueryFailed));
};
//Function executed on success
onQuerySucceed = function () {
alert(this.rootWeb.get_title());
};
//Function executed on failure
onQueryFailed = function (sender, args) {
alert('Unable to retrieve data from the SharePoint. Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
};
you can get the url without the client object model by using available information and string parse it down from there. Not as robust as the Client-Object model but significantly less complicated for simple tasks.
window.location.href
...gives you the full window url (e.g. "http://sitecollection.com/sites/mysite/Lists/myList/NewForm.aspx?ContentTypeId=0x01006AC2C39AA621424EBAD9C2AC8A54F8B9007B626ABEEB66E34196C46E13E0CA41A2&ContentTypeName=xxxx")
L_Menu_BaseUrl
Or
_spPageContextInfo.siteServerRelativeUrl
...(as Jinxed points out) will give you the relative url (e.g. "/sites/mysite")

Resources