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
Related
I am running my code under administrative rights that iterates over different site->spweb to check the existance of a list. Strangely and for some site the code returns me that list does not exists(exception : List does not exists) Yet i can totally browse the list from browser on the same web
what am i missing here ?
EDIT:Adding Code
foreach (SPSite s in webApp.Sites)
{
foreach (SPWeb w in s.AllWebs)
{
try{
SPList sourceList = w.Lists["Ticks and Cross"];
}catch(exception ex){ ..... }
}
s.Dispose();
}
All sites has same templates, so there is no chance that list is not ther. For some site i get the sourceList, for other its exception, its really wired
I guess you pass incorrect parameter to Lists[]. You should specify valid guid, title or index of the list. Can you post your code?
From code I've automatically created a lot of similar sites (SPWeb) in my site collection from a site template (in Sharepoint Foundation). Every site has a home page on which I've added the "what's new" web part (found under "Social collaboration").
Even though the web part has several "target lists" (I'd have called it "source lists") added to it on the template site, this connection is lost on the sites created from the template. So I need to programmatically find all these web parts and add the target lists to them. Looping the web parts is not an issue - I've done that before - but I can't seem to find a word on the net on how to go about modifying this particular web part. All I have is a brief intellisense.
I've found out that it recides in the
Microsoft.SharePoint.Applications.GroupBoard.WebPartPages
namespace, but on the lists provided on MSDN this is one of very few namespaces that doesn't have a link to a reference documentation.
Does anyone have any experience of modifying this web part from code? If not, how would you go about to find out? I can't seem to figure out a method for this..
Here is how I did it. It worked really well. I had a feature that created several list instances and provisioned the What's New web part. In the Feature Receiver, I looped through all of the list instances, indexed the Modified field, and then added the list to the web part:
private void ConfigureLists(SPWeb web, SPFeatureReceiverProperties properties)
{
List<Guid> ids = new List<Guid>();
SPElementDefinitionCollection elements =
properties.Feature.Definition.GetElementDefinitions(new CultureInfo((int)web.Language, false));
foreach (SPElementDefinition element in elements)
{
if ("ListInstance" == element.ElementType)
{
XmlNode node = element.XmlDefinition;
SPList list = web.Lists[node.Attributes["Title"].Value];
SPField field = list.Fields[SPBuiltInFieldId.Modified];
if (!field.Indexed)
{
field.Indexed = true;
field.Update();
}
ids.Add(list.ID);
}
}
string targetConfig = string.Empty;
foreach (Guid id in ids)
{
targetConfig += string.Format("'{0}',''\n", id);
}
SPFile file = web.GetFile("Pages/default.aspx");
file.CheckOut();
using (SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
WhatsNewWebPart webpart = null;
foreach (System.Web.UI.WebControls.WebParts.WebPart eachWebPart in manager.WebParts)
{
webpart = eachWebPart as WhatsNewWebPart;
if (null != webpart)
{
break;
}
}
if (null != webpart)
{
webpart.TargetConfig = targetConfig;
manager.SaveChanges(webpart);
}
}
file.CheckIn("ConfigureWebParts");
file.Publish("ConfigureWebParts");
file.Approve("ConfigureWebParts");
}
If you are unsure about the property, export the web part from the browser, then open the .webpart/.dwp file with a text editor. Somewhere in the xml will be a reference to the source list.
*.webparts are usually easier to modify, just set the property.
*.dwps are harder because you sometimes have to get the property (eg ViewXML), then load it into an XmlDocument, then replace the property, and write the xml document string value back to ViewXML.
We're running SharePoint 2007 SP1 and profiles are imported from Active Directory (a full import runs daily). We had a problem where many of the users were disabled unintentionally in Active Directory and this caused their profiles to be removed from SharePoint. We re-enabled their Active Directory accounts and ran a full import which restored their SharePoint profiles. However, all of their My Links are missing. Is there a method or best practice for restoring them?
I posted this because I couldn't find an answer to my problem anywhere. This post by Joel Oleson that describes a similar problem to mine gave me a hint as to where to go looking for the missing data. And This post by Corey Roth showed me how to programatically add the links to a users My Links.
First things first - you need to restore a backup of the database that contains the My Links data. You don't want to restore over your working database, you want to restore it to another location. The links stored in the SSP Database. (You can find out the name of the database by going into Central Admin --> Shared Services Admin then open the menu for the SSP and click on Edit Properties - the SSP Database is listed on the properties page.)
Once the database has been restored you want to retrieve the Link information:
the domain account name of the user who owns the link,
the url of the link
the name of the link
This query will get you that information:
SELECT UPF.NTName, UL.Url, UL.Title
FROM UserLinks UL INNER JOIN UserProfile_full UPF ON UL.recordID = UPF.recordID
INNER JOIN UserPrivacyPolicy UPP ON UL.PolicyId = UPP.id
ORDER BY NTName
(I should note that I did not take into account what group or what privacy level the links were set to, you could probably find that information by looking at the information in the UserPrivacyPolicy table)
I copied the results into Excel & saved it as a .csv file (comma separated list) - just because my production server did not have access to the location where I restored my database. I ordered the columns with Title last because the Title could contain commas and that would mess up how I'm reading in the data. (I checked and the other two fields do not contain commas - you should check yours before making this assumption.)
I then wrote a little console app to import the data. It takes two arguments:
the path where the file containing all of the links is located (ie c:\temp\links.csv)
the url of the SSP from with the My Links have gone missing (ie https://portal.mydomain.com)
These are the references used:
Microsoft.Office.Server (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.Office.Server.dll)
Microsoft.SharePoint (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll)
System
System.Data
System.Web
System.Xml
And this is the code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Web;
namespace UserLinks
{
class Program
{
static void Main(string[] args)
{
string _accountName = "", _linkTitle = "", _url = "", _tmp = "", _path = "", _SPSsite = "";
// Check arguments
if (args.Length != 2)
{
ShowUsage();
return;
}
_path = args[0];
_SPSsite = args[1];
using (SPSite _site = new SPSite(_SPSsite))
{
ServerContext _context = ServerContext.GetContext(_site);
UserProfileManager _userProfileManger = new UserProfileManager(_context);
/* Expecting a comma seperated list with 3 columns:
* AccountName in the format Domain\Account name - I am assuming there are no commas in this field
* URL - I am assuming there are no commas in this field
* Link Title - link title is last because there may be commas in the title
*/
TextReader _reader = new StreamReader(_path, System.Text.Encoding.Default);
while (_reader.Peek() != -1)
{
_tmp = _reader.ReadLine();
_accountName = _tmp.Substring(0, _tmp.IndexOf(','));
_tmp = _tmp.Replace(_accountName + ",", "");
_url = _tmp.Substring(0, _tmp.IndexOf(','));
_linkTitle = _tmp.Replace(_url + ",", "");
try
{
UserProfile _currentUser = _userProfileManger.GetUserProfile(_accountName);
QuickLinkManager _quickLinkManager = _currentUser.QuickLinks;
_quickLinkManager.Create(_linkTitle, _url, QuickLinkGroupType.General, null, Privacy.Private); //I am assuming that all links have no group assigned to them and they are all private links
}
catch (Exception ex)
{
Console.WriteLine(_accountName);
Console.WriteLine(ex);
}
}
_reader.Close();
}
}
private static void ShowUsage()
{
Console.WriteLine("Usage");
Console.WriteLine("UserLinks [FilePath] [SharePoint URL]");
}
}
}
So problem solved & as a side benefit, this program can be used to force links to show up in a user's My Links list.
This post has some pretty good information about MyLinks and its relationship with the SSP database (that's actually where these links are stored counterintuitively.) Hopefully you can have your DBA validate that these links still exist; and that they're associated with the correct profiles.
http://www.k2distillery.com/2009/01/moving-sharepoint-my-links-between-ssps.html
When you do a profile import, you normally risk losing the existing customization/updated information.
I've created a list template based on an Issue list and it is saved in the List Template Gallery. Now how do I create a new list based on this template?
string internalName = "MyListTemplateName";
SPListTemplate t = null;
foreach (SPListTemplate template in web.ListTemplates)
{
if (template.InternalName.Equals(internalName)
{
t = template;
break;
}
}
web.Lists.Add("nameoflist", "description", t);
I just encountered the same situation today.
I saved a list as a template and i wanted to use that template in a new list.
On Sharepoint 2013, go to Site Contents > Add an App >
Scroll down and you will see a page numbering saying that you are on page 1
Click on the second page and all your saved templates will be there
It probably just took a while for the timer job to fire.
The template eventually showed up as an option under Lists > Create > Tracking section after a few minutes.
I'm surprised that Johan Leino's answer is marked as useful multiple times as it doesn't work in this particular case. If you create a template yourself, web.ListTemplates does not store it and you won't be able to create the list. It's only working for out-of-the-box templates.If you want to create a list based on your custom template you need to do it this way:
SPListTemplateCollection listTemplates = web.Site.GetCustomListTemplates(web);
SPListTemplate listTemplate = listTemplates["MyCustomTemplate"];
Guid listId = web.Lists.Add("My New List Name", "My Description", listTemplate);
if (listId != null) { //all good }
I have a list within Sharepoint, using a custom new form I have added a custom list form control ("New item form" for the list) and changed the SaveButton to a standard input HTML button, and added an 'onclick' event that is as follows:
onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={NewFormWizard2.aspx?id=}')}"
This works as in saves the data and redirects to the NewFormWizard2.aspx?id= page.
How do I get the ID of the created item to be passed to the redirected page?
Thus once the form is completed it would redirect to NewFormWizard2.aspx?id=23
jtherkel was close, but was missing a '}' on the end of the redirect url. I used an extra concat below
<input type="button" value="Submit" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent(concat('__commit;__redirect={lists/MyListName/DispForm.aspx?ID=',/dsQueryResponse/Rows/Row/#ID,'}'))}" />
I am not sure where the ID will exist on the page you host the Javascript from. Does it appear in the querystring or on a field on the page?
There is nothing in the request or response that will identify the item. I have had this issue when doing some web loadtesting.
I can only suggest that your create the item using the webservices as that at gives you some return xml.
This answer does not solve the "new form" issue, but it might help others with the syntax for screens that contain existing list items.
I tested this quickly in my SharePoint (MOSS 2007) environment.
onclick="javascript: {ddwrt:GenFireServerEvent(concat('__commit;__redirect={NewFormWizard2.aspx?id=',/dsQueryResponse/Rows/Row/#ID))}"
The concat syntax is an XSLT instruction that tells the processor to combine the values enclosed in single quotes. I adapted this answer from info I found here.
Loading Values in a Custom List Form
http://wssdevelopment.blogspot.com/2007_04_01_archive.html
I hope this would be helpfull:
1- In SharePoint Designer create new page, call it for example "LastItem.aspx" and place a dataview on it with a single form view for the destination list item.
2-Limit paging to just one record, set the sorting by ID and descending and filter the list to just show item which is created by [current user].
3-Now you do not need to pass any query string to this page. just replace the default "OK" button in NewForm.aspx of the list with a standard HTML input button and add this to its definition "onclick="javascript: {ddwrt:GenFireServerEvent(concat('__commit;__redirect={LastItem.aspx}". After submitting a new item to list you will be redirected to an edit view of the created item.
You can do the same for save button in LastItem.aspx to redirect to some other page after clicking on save button.
found an approach using pure javascript (JQuery) and the SPAPI code from http://darrenjohnstone.net/.
The list contains two fields, title and BodyCopy
I've thewn created a form that asks for a title and a question, both text fields, then the submit button calls the following function: (note that ServerAddress and LIST_question need to be updated to your own details).
The function then uploads the details using the SOAP service within LISTS.ASMX and using the response gets the ID of the new item and redirects the page.
var LIST_question = '{xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}';
var ServerAddress = 'http://xxx/';
function submitQuestion()
{
var title = new String($("#title").val());
var t = new String($("#question").val());
t=t.trim();
if(t=="")
return;
title=title.trim();
if(title=="")
return;
var lists = new SPAPI_Lists(ServerAddress) ;
//
var newItem = { Title : title, BodyCopy : t};
var items = lists.quickAddListItem(LIST_question, newItem);
var id=-1;
if (items.status == 200)
{
var rows = items.responseXML.getElementsByTagName('z:row');
if(rows.length ==1)
{
var r = rows[0];
var id = r.getAttribute('ows_ID');
window.location.href='DispForm.aspx?ID='+id;
}
else
{
alert("Error: No row added");
}
}
else
{
alert('There was an error: ' + items.statusText);
return;
}
}
You can achieve this using JavaScript http://www.sharepointdrive.com/blog/Lists/Posts/Post.aspx?ID=9