tags:

views:

28

answers:

1

Hey all,

I need to test a sharepoint solution my business has created. I have created a simple exe to be run on the actual sharepoint server.

I am trying to figure out how to use the Sharepoint Server OM to do my tests. At this point all I am trying to do is simply add an item to the library.

My first solution did something like this:

SPSite site = SPContext.Current.Site;
SPWeb web = site.OpenWeb();
etc...

The problem here is SPCOntext.Current.Site is always null.

My next attempt looked something like this:

SPSite site = new SPSite(url);
SPWeb web = site.OpenWeb();
SPList list = web.Lists[listName];
SPListItem item = list.AddItem();
item["Title"] = "Some Title";
item.Update();

This runs without any error, but when I check the list in question, the item I added isn't there.

Can anyone help guide me into where I am going wrong?

+1  A: 

Try the following code:

using(SPSite site = new SPSite(url))
using(SPWeb web = site.OpenWeb())
{
    SPList list = web.Lists[listName];
    SPListItem item = list.AddItem();
    item["Title"] = "Some Title";

    web.AllowUnsafeUpdates = true;
    item.Update();
    list.Update();
    web.AllowUnsafeUpdates = false;
}

You may not need the AllowUnsafeUpdates (can't remember right now) but I'm almost positive you have to update the list as well.

knight0323
Worked like a charm. Thanks a ton! I did need to include AllowUnsafeUpdates. What is the a reason for this? Can I attach a username and pwd to it somehow to avoid this?
cmptrer
It has to with the fact that your calling the constructor instead of getting your objects from SPContext. By the way, SPContext is null because you're using it outside the context of an HTTP request. SPContext is the SharePoint version of HTTPContext.Also, I've updated my original code block to include using statements to ensure correct object disposal.
knight0323
AllowUnsafeUpdates allows you to update things in teh context of a HTTP request where it hasn't gone through the form digest checking. E.g. on the display of a web part rather than in response to a postback.You DO NOT need it for a console type app where there is no HTTP context (which is the same reason why SPContext will not work).http://hristopavlov.wordpress.com/2008/05/16/what-you-need-to-know-about-allowunsafeupdates/
Ryan
Ryan did you read that article? Even that article states that when creating your own you may need to AllowUnsafeUpdates. Yes it's supposed to be null but it doesn't always work that way when instantiating the objects. I went back and looked at some old code and whether it's a bug or not it won't work without AllowUnsafeUpdates sometimes.
knight0323
the list.update() is not needed.
x0n