Adding a ListItem to a list in Sharepoint 2007 - sharepoint

I am trying to add an item to a list in Sharepoint. At the moment I am trying to add the item via CAML
I can read the list, and query the list but I have not been able to add to the list. All the examples that I have seen update the list, I would expect that it should be reasonably similar process to add an item.
this is how I am testing it at the moment.
SPLists is a web reference to http:///_vti_bin/lists.asmx
void Test(){
var listService = new SPLists.Lists();
string strBatch ="<Method ID='1' Cmd='New'><Field Name='Title'>Test</Field></Method>";
XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");
elBatch.SetAttribute("OnError", "Continue");
elBatch.SetAttribute("ListVersion", "1");
elBatch.InnerXml = strBatch;
XmlNode ndReturn = listService.UpdateListItems("TestList",elBatch);
Console.Write(ndReturn.OuterXml);
Console.WriteLine("");
}
someone already asked a similar/same question here on SO but not answered
Edit
This is the error that I get
<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<Result ID="1,New">
<ErrorCode>0x81020026</ErrorCode>
<ErrorText>The list that is referenced here no longer exists.</ErrorText>
</Result>
</Results>
When I setup the web reference pointed it at the correct site and even looked at the list in sharepoint to make sure that it is there.

Looks like you probably need a small addition to your strBatch (use this article as a reference): <Field Name='ID'>New</Field>
Which means you'll have something like:
string strBatch ="<Method ID='1' Cmd='New'><Field Name='ID'>New</Field><Field Name='Title'>Test</Field></Method>";
Also, if you have any required fields on your list, you'll probably have to specify those as well.

This is what I found that solved my problem.
When I set up the Web Reference in visual studio I pointed it to the http://sharepointSite/subweb1/subweb2/_vit_bin/lists.asmx as the reference.
However when I went back and checked today it was pointing to http://sharepointSite/_vit_bin/lists.asmx. manually changing it back to http://sharepointSite/subweb1/subweb2/_vit_bin/lists.asmx in the app.config file made all the difference.
#Kit +1 I also added in you suggestion as well. With your suggetion and what I discovered about the web reference, it worked first time.
I ended up just creating a sub web with only 1 field (Title) just to get it working.

Related

Get List Item by Guid without List in SharePoint

Could anybody help me to get List Item by unique Id in SharePoint without using List? I know the List Item unique Id, but I haven't information about List. Using Client Object Model I can do the following:
using (SP.ClientContext clientContext = new SP.ClientContext(...))
{
**SP.List list = clientContext.Web.Lists.GetById(listId);**
SP.ListItem listItem = list.GetItemById(listItemId);
clientContext.Load(listItem);
clientContext.ExecuteQuery();
...
}
Unfortunately, in this code I use listId, but the problem is that in my task I don't know listId, I have only ListItem Guid. Since I have unique Id, I believe that there must be a way to get this Item without using any additional information.
You've posted a snippet with a Client Object Model, so I suppose it's a preffered object model for the solution. However, if it's acceptable for You, I've found some information on how to achieve this using server side object model, which You may find helpful.
It seems that this can be done using SPWeb.GetFile(Guid itemGuid) if the item exist in the root site.
If you want it to work also for subsites, you can use SPWeb.GetSiteData method to invoke caml retrieving an item as explained in this article: http://www.chakkaradeep.com/post/Retrieving-an-Item-from-the-RootWeb-and-Subwebs-using-its-UniqueId.aspx.
You can also take a look at this thread on SO for some additional information:
SharePoint: Get SPListItem by Unique ID.
If you have any issues using those methods, let me know. I'll also look for alternatives for this to run with Client Object Model and I'll post them if I find some, however, it seems to be more difficult to achieve.

Programmatically adding columns to Sharepoint List Views

For a project I am working on, I am trying to do the following thing.
There's a Sharepoint 2010 environment, with a few Custom Lists created in Visual Studio. I am adding some fields to them using background code in the FeatureActivated function in the EventReceiver.
What I am doing there is adding a lookup field to the Sharepoint List, and setting the properties to allow it to lookup values from the other list I am adding to the Sharepoint Site.
However, I can't find a function to add it to one of the views. I've tried modifying the Schema Xml, but I can't seem to find a function to reinsert it to the List, and when using the Xml file from the View, I can't seem to make it work.
Is there an easy way to programatically add a field to a view? This would help me out, since there seems to be no way to do this correctly.
This can also be solved if one could explain my other question I have.
I would like to know how one could make Lookup fields in the Schema XML file. I have a Custom Content Type, and Custom Fields, and I am currently trying to look up the Naam field in the Intermediairs List. (This one is also created when deploying this solution). When searching Google, it seems I have to use either a name / the GUID of a List Instance here, but I don't know the GUID of the List Instance beforehand.
<Field ID="{7CC49D9D-F6F5-4A4A-851F-3152AAAAB158}" Type="Lookup"
List="Intermediairs" Name="IntermediairLookup" DisplayName="Intermediair"
StaticName="IntermediairLookup" Group="Onboarding" ShowField="Naam" />
You should know that this code seems to work:
SPWeb web = null;
SPSite site = null;
if (properties.Feature.Parent is SPWeb)
{
web = properties.Feature.Parent as SPWeb;
site = web.Site;
}
if (properties.Feature.Parent is SPSite)
{
site = properties.Feature.Parent as SPSite;
web = site.RootWeb;
}
web.AllowUnsafeUpdates = true;
SPList changeList = web.Lists.TryGetList("Onboarding");
SPList sourceList = web.Lists.TryGetList("Intermediairs");
if (changeList != null && sourceList != null)
{
changeList.Fields.Delete("IntermediairLookup");
var PrimaryColumnStr = changeList.Fields.AddLookup("Intermediair", sourceList.ID, true);
var PrimaryColumn = changeList.Fields.GetFieldByInternalName(PrimaryColumnStr) as SPFieldLookup;
PrimaryColumn.LookupField = sourceList.Fields["Naam"].InternalName;
PrimaryColumn.Update();
}
But yeah. I can't figure out how to do it in XML form. Anyone has any ideas? A solution to either of the questions would solve my core issue.
Greetings,
Mats
EDIT: Well, the question has now been answered, thanks again!
One thing though. I would really like to know at some point how to do something like this in XML / CAML. Does anyone know how to do that? Anyone who's still reading this thread?
Take a look at SPView.ViewFields
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spview.viewfields.aspx

Updating the Internal Name using the Content Database

We currently have a field which has the wrong ID. the IDs and Internal Names of Sharepoint Fields are readonly on the domain model. I was wondering if there is a way to update them even by using the content database.
One sure way is to delete the field and recreate it. but it already has data and there are thousands of pages. I was wondering if there is a way just to update the IDs and Internal Name without doing the dropping and recreation of fields.
Thanks
Even if it may work, don't do it.
It's:
Dangerous, as you may skip dependencies
Not supported
Recreating the field using some script to keep data is safer.
We ran into the same problem. Messing with the DB was not an option for us (and shouldn't be for you either), but you can work around it. Unfortunately, it will require touching each page to update the metadata.
First, create the column like it should be in the list. Then, you can copy the data from the old column to the new column in a variety of ways:
DataSheet view
Programmatically via web services (don't need to have access to the server)
Programmatically via console app (will need to run locally on the server)
Honestly, writing a small console app will be the quickest. For example:
string siteUrl = "http://server/sitecollection/";
string webUrl = "subsite1/subsite2/";
string listName = "Your List Name";
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb(webUrl))
{
SPList list = web.Lists[listName];
foreach (SPListItem item in list.Items)
{
item["New_x0020_Column_x0020_Name"] = item["Old_x0020_Column_x0020_Name"];
}
}
}
Also, it would HIGHLY recommend trying this in a DEV environment first. Just do an STSADM restore from your production environment and test your console app. Then, validate your data and delete the old column!
I would not suggest modifying the content database, since it is:
unsupported (if you do it, Microsoft will not help you when you're in real trouble even if you have MS Premier Support)
very complicated to do. You'd have to update a number of tables and you would never be sure if you actually updated all the required things.
What you can try to do - see if the internal name property is actually "read only" or it is defined as "friend" and you cannot call it from a different code assembly. If it's the latter case, you can use .Net reflection to set the property value. See this MSDN documentation link for details.

GetListitems results from SharePoint?

The GetListitems web service relies on XML to retrieve data from SharePoint.
Some actual working code is:
var doc = new XmlDocument();
doc.LoadXml("<Document><Query><Where><Contains><FieldRef Name=\"DeliveryStatus\" /><Value Type=\"Text\">Created</Value></Contains></Where></Query><ViewFields /><QueryOptions /></Document>");
XmlNode listQuery = doc.SelectSingleNode("//Query");
XmlNode listViewFields = doc.SelectSingleNode("//ViewFields");
XmlNode listQueryOptions = doc.SelectSingleNode("//QueryOptions");
XmlNode items = wsLists.GetListItems(ListName, string.Empty, listQuery, listViewFields, string.Empty, listQueryOptions, null);
Once XMLNode is populated, is there a tried and tested way to traverse the collection of childnodes?
I know how to do this using .net general techniques, but what concerns me is that there might be some pitfalls I am unaware of. For example, I noticed the firstChild and lastChild are empty during some of my tests. I wonder if this is an exception rather than a rule. Its impossible to know from MSDN documentation, so if any of you guys have experience with this please share.
Thanks in advance
You mean FirstChild and LastChild sometimes are empty? Well, if you have tags like <QueryOptions /> and such, then it means they have no childs. By logic I guess that those properties must be empty then.
Or is there any other problem than that?

Content Query Web Part - How do you OrderBy when you QueryOverride?

How do you order items when you override the QueryOverride property of the Content Query Web Part?
I have been given responsibility for a Web Part which extends the Content Query Web Part. The QueryOverride property of this Web Part is programmatically changed. Currently, the Web Part does not function as designed, as it does not order the items according to the appropriate field.
If I add an <OrderBy> node to the QueryOverride property I get an error message along the lines of 'something wrong with the query this web part is...' and the Content Query Web Part doesn't seem to have an OrderBy property which I could use instead.
The "QueryOverride property" part of this msdn article seems to suggest I should be able to add an <OrderBy> node to the QueryOverride but a number of web sites I've been reading suggest that this is not true.
So, how do you order items when you override the QueryOverride property of the Content Query Web Part?
Does your QueryOverride statement contain any Whitespace/linebreaks by any chance? I think I recall a while back having a situation where the QueryOverride needed to be all contained on one line, with no spaces between xml tags.
Weird I know, but try it out.
Also, for reference see the first community comment on the MSDN page http://msdn.microsoft.com/en-us/library/aa981241.aspx
THanks for this. Just to clarify, there should be no white spaces before or after the tags as well.
This did not work:
<![CDATA[
<OrderBy><FieldRef Name="EndDate" Ascending="False"/></OrderBy>
<Where>
But this did:
<![CDATA[<OrderBy><FieldRef Name="EndDate" Ascending="False"/></OrderBy><Where>
Wierd but thanks again for posting this answer, it saved me a lot of time.

Resources