I want to ask regarding sharepoint clientClient context:
var clientContext = SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('splist');
It returns the current web url (https://sharepoint.com/sites/site1). However i want to get the url of other tenant URL which is (https://sharepoint.com/sites/site2).
Tried googling this but to no avail.
You can open a new ClientContex to a different site than the one you are one with the below way:
let clientContext = new SP.ClientContext("https://sharepoint.com/sites/site2");
let oList = clientContext
.get_web()
.get_lists()
.getByTitle("Test List");
The above code is the initialization part of the ClientContext Object.
What you have to be aware of is that since you open a context with the perspective of the user and, afterwards, perfoms some kind of action, you have to make sure that the use has a High-enough Access Level in order to perform the action.
For the next, step you can use the ClientContext Object in order to get List Items from a list and define some callbacks in order to handle Query retrieval succes or any exceptions that might occur.
query.set_viewXml("<View>.... some CAML query ....</View>");
items = oList.getItems(query);
clientContext.load(items);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
Related
We have a requirement where users are to be allowed to search a list called "Reports" from the front-end, and advanced search, such as author:"John Smith" or filetype:docx, is to be supported.
We decided that this can be achieved using Sharepoint Server Search API (using the Keyword Query Language). Also, since it is possible that all users don't have access to all items in the list, we decided to go with the approach to use a web method with elevated privileges to query the list.
This is my attempt so far...
public string GetSearchResults(string listname, string searchQuery)
{
SPUser superUser = SPContext.Current.Web.AllUsers[#"SHAREPOINT\SYSTEM"];
using (SPSite site = new SPSite(SPContext.Current.Web.Url, superUser.UserToken))
{
KeywordQuery keywordQuery = new KeywordQuery(site);
keywordQuery.QueryText = searchQuery;
//where should listname be specified?
SearchExecutor searchExecutor = new SearchExecutor();
ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
var resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults);
ResultTable resultTable = resultTables.FirstOrDefault();
DataTable dataTable = resultTable.Table;
}
//how to parse result to filter only items in given list?
}
...but what I don't understand is how to restrict search to only a given list or how to parse the search result to retrieve items of the list matching the search query.
I'm new to Sharepoint search, so any pointers would help.
This is possible either to give list path or list guid in query text
keywordQuery.QueryText = "Path:/Sales/Lists/Prospects/ (contentclass:STS_ListItem OR IsDocument:True) -ContentClass=urn:content-class:SPSPeople ";
I am trying to make a query on a SPList but I got an error saying that List doesn't exist.
How can I read the current context in the proper way ?
Is somehow a deployment issue ?
var clientContext = new SP.ClientContext.get_current();;
var oList = clientContext.get_web().get_lists().getByTitle("MyList");
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="SearchUserName" /><Value Type="Text">' + loginName + '</Value></Eq></Where></Query></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
//do something
}), Function.createDelegate(this, function (sender, args) {
//log error
}));
I get the error: List 'MyList' does not exist at site with URL '.... site path'
What am I doing wrong? Is there another way of reading the current context?
You could have run into a simple problem which tripped me up:
When you use getByTitle() you need to use the List's display name,
Is your list display name "MyList" or might it be "My List"?
The List 'Title' = List Display Name (Often has spaces)
The List 'Name' = List Internal Name (usually no spaces or special characters)
To find the display name look at what the list is called in the "Site Contents" page.
To find the internal name, look at the URL when you hover over (or click) the List name in "Site Contents".
Try get_web().get_lists().getByTitle("My List");
Remember SharePoint considers each subsite a seperate site. If your code runs on the root of your SharePoint site, but the lists resides in a subsite, your code will not work. You would then need to specify the site when setting your client context.
Are you sure that get_current is actually returning the correct context?
It might be safer to specify the context.
Also, you could use the lists ID instead of the name then get by ID instead.
After I ran into the same problem, I realized my mistake was the following :
I was running Sharepoint's workbench with the root URL of my domain
So I was running workbench with URL
https://mydomainname.sharepoint.com/_layouts/15/workbench.aspx
While I should have used
https://mydomainname.sharepoint.com/sites/myfirstsite/_layouts/15/workbench.aspx
I am quite stumped with this. In enhancing an existing feature to a SharePoint solution, I found that they were querying the Wss_Content directly. Knowing I should not be using that stored procedure, I used the SharePoint object model to retrieve the users group information from the userName. What's burning me is that it is slower then the stored procedure. Is there a smarter/faster way to get this information? We are using SharePoint 2007. Below is roughly what the function does:
private string GetTitle(string userName)
{
string results = string.Empty;
try
{
SPSite spSite = new SPSite("http://devvm");
SPWeb spWeb = spSite.AllWebs[""];
SPUser user = spWeb.AllUsers["aspnetsqlmembershipprovider:" + userName];
SPGroupCollection groups = user.Groups;
results = groups[0].Name;
}
catch (Exception ex)
{
Console.WriteLine("Unable to find user" + userName);
results = "No Group Found";
}
return results;
}
and the Stored Procedure code is:
SELECT #role=Groups.Title
FROM WSS_Content.DBO.UserInfo Info
LEFT JOIN WSS_Content.DBO.GroupMembership Membership
ON Info.tp_ID=Membership.MemberID
LEFT JOIN Wss_Content.DBO.Groups Groups
ON Membership.GroupID=Groups.ID
WHERE tp_Login='aspnetsqlmembershipprovider:' + #username
FYI the reason I have this in a try-catch is that this is a sub-query to another list that might not have a user associated to the item.
Any help in this would be greatly appreciated.
How are you calling that code? If you are using this inside a console application then yes it will be slower, it needs to fire up the supporting objects that are normally live when using this inside a native sharepoint context.
Also you are referencing an SPSite and SPWeb object without disposing of the object, this has inherent performance issues as well.
I need to check for duplicates. Currently I have items stored in sub folders in a list.
How can I retrieve all items in the list from a web service, so I can check for duplicates?
Here is code from object model: I want to do exactly this, but from a web service
private static void PrintItemTitles()
{
string strUrl = "http://localhost:8099/";
using (SPSite site = new SPSite(strUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyList"];
SPListItemCollection items = list.Items;
foreach (SPListItem item in items)
if (item != null)
Console.WriteLine(item.Title);
}
}
}
Use SPList.Items doesn't return all items? Well, then try SPList.GetItems(SPQuery).
Have a following SPQuery:
SPQuery query = new SPQuery();
query.ViewFields = "<FieldRef Name='ID'/><FieldRef Name='Title'/>";
query.Query = String.Format("<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>", someItemTitle)
query.MeetingInstanceId = -1; //In case if you query recurring meeting workspace - get items from all meetings
query.RowLimit = 10; //Will you have more than 10 duplicates? Increase this value
query.ViewAttributes = "Scope='RecursiveAll'"; //Also return items from folders subfolders
Note: There could be some mistakes in code, because i`m writing from top of my head
By executing this query and if it returns more than one item, then you have a duplicate!
Edit: Ahh, sorry, you are talking about Web Services.
Then this code won't help. There are 2 options then:
Option 1: You CAN create a view that
does include items even from folders
(flat view). See here for
instructions.
Option 2: According to Lists Web Service's GetListItems method, you can pass QueryOptions parameter. Pass in
<QueryOptions>
<MeetingInstanceID>-1</MeetingInstanceID> <!-- Again, if you query recurring meeting, you want ALL items -->
<ViewAttributes Scope='RecursiveAll' /> <!-- or Recursive if that does not work -->
</QueryOptions>
Good luck!
You can use the Lists.asmx web service, but that is quite hard to do as it returns quite a lot of information. I would deploy a custom web service on my SharePoint environment that contains that code and returns the list items.
I am using form base authentication in my Sharepoint site. On my login page there are custom fields to be filled by unauthenticated user. These fields i want to add in to my list. I am using following code to insert record in list.
protected void AddVendor(object sender, EventArgs e)
{
string strList = "http://comp01:5353/Lists/Vendors/";
using (SPSite site = new SPSite(strList))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPUser user = web.AllUsers["demouser"];
SPList list = web.Lists["Vendors"];
SPListItem Item = list.Items.Add();
Item["First Name"] = txtVendorName.Text;
Item["Last Name"] = txtVLastName.Text;
Item["business"] = txtDescription.Text;
Item["Description"] = txtDescription.Text;
Item["Mobile No"] = txtMobileNumber.Text;
Item["Approved"] = "No";
Item["Created By"] = "demoadmin";
Item["Modified By"] = "demoadmin";
Item.Update();
}
}
}
but is is giving me an error saying that Thread was being aborted. I don't know what exactly missing. but is it because I am performing add action and user is not authenticated...?
I donĀ“t know if it will help you but the code that says (f.e.) Item["Modified By"] will not work since that is the internal name which is Modified_x0020_By. This goes for all the fields with "spaces" in them.
This might be one of your issues...
Where have you written this code, is it inside some event ? Login Control Provides two events that will help you to solve this
OnLoginError="OnLoginError" OnLoggedIn="OnLoggedIn"
I did similar functionality where I wanted to capture the user name loggin to the site and log it to the DB Table. And with respect to the ThreadAbort Exception, it happens when you use Response.Redirect while a code is being executed. In you case I doubt that its being thrown because you are trying to do the above code but the FBA system tries to redirect the user to the default.aspx . Try out above said Event of the Login Control it should help you.