Solved

SharePoint list error - FileNotFoundException

Posted on 2011-02-23
26
948 Views
Last Modified: 2012-05-11
Hello Gurus,

I am trying to update a sharepoint list via the web.

What am I doing wrong with the code below?

I get the following error:

"FileNotFoundException was unhandled by user code
Ther is no Web named '/Lists/Parts'. "

Here's a link to the actual link:
http://localhost/Lists/Parts/AllItems.aspx

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.SharePoint;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //String parameters to enable site and list access
        const string siteUrl = "http://landis";
        const string siteName = "/Lists/Parts/";
        const string listName = "Parts";

        //Return a site collection using the SPSite constructor providing the site URL
        SPSite siteCollection = new SPSite(siteUrl); //

        //Return the target web site based on site name
        SPWeb site = siteCollection.AllWebs[siteName];

        //Return a collection of list items based on the Items property
        //for the specific named list
        SPListItemCollection listItems = site.Lists[listName].Items;

        //Add a list item to the list items collection
        SPListItem item = listItems.Add();

        //Populate item data via user indexers with form input data
        item["Title"] = title.Text;
        item["Part Number"] = Convert.ToInt16(partNum.Text);
        item["Price"] = Convert.ToInt16(price.Text);

        //Update SP database with changes made to this item
        item.Update();

        //UI clean-up
        Label1.Text = "Done!";


    }
}

Open in new window

0
Comment
Question by:Isaac
  • 15
  • 11
26 Comments
 
LVL 6

Expert Comment

by:psv1973
ID: 34962387
Is this correct?

const string siteName = "/Lists/Parts/";
const string listName = "Parts";

It looks like SiteName is pointing to a list.

0
 
LVL 5

Author Comment

by:Isaac
ID: 34962653
Ok.... Maybe I'm confused.  Is it supposed to be the url which is already siteUrl?  How do I find the siteName?
0
 
LVL 5

Author Comment

by:Isaac
ID: 34964131
Ok.  I did a little research and modified and now I get this error: SPException was unhandled by user code.  The security validation for this page is invalid.  Click Back in your web browser, refresh the page, and try your operation again.

        using (SPSite mySiteCollection = new SPSite("http://landis/"))
        {
            using (SPWeb myWeb = mySiteCollection.OpenWeb())
            {
                SPList PartsList = myWeb.Lists["Parts"];
                SPListItem newPartItem = PartsList.Items.Add();

                newPartItem["Title"] = title.Text;
                newPartItem["Part Number"] = Convert.ToInt16(partNum.Text);
                newPartItem["price"] = Convert.ToDecimal(price.Text); 

               [b] newPartItem.Update();   [/b]<-- Error points here
            }
        }

Open in new window

0
 
LVL 5

Author Comment

by:Isaac
ID: 34964570
I modified the code using RunWithElebatedPrivileges but I still get an error:

Here's the error:

invalidoperationexception was unhandled by user code
operation is not valid due to the current state of the object.

string errVal = "";
         try  
          {              
             SPSecurity.RunWithElevatedPrivileges(delegate()
             {
                using (SPSite mySiteCollection = new SPSite("http://landis/"))
                {
                    using (SPWeb myWeb = mySiteCollection.OpenWeb())
                    {
                        SPList PartsList = myWeb.Lists["Parts"];
                        SPListItem newPartItem = PartsList.Items.Add();

                        newPartItem["Title"] = title.Text;
                        newPartItem["Part Number"] = Convert.ToInt16(partNum.Text);
                        newPartItem["Price"] = Convert.ToDecimal(price.Text);

                        newPartItem.Update();
                    }
                }
             });
         }
         catch (Exception f) 
         { 
             errVal = f.Message;

Open in new window

0
 
LVL 6

Expert Comment

by:psv1973
ID: 34968608
Can you set SPWeb.AllowUnsafeUpdates to true before the update and back to false afterwards?
0
 
LVL 5

Author Comment

by:Isaac
ID: 34969673
I actually tried that but still got the same error.
0
 
LVL 6

Expert Comment

by:psv1973
ID: 34969912
Do you have checkin/checkout enabled on your list?
0
 
LVL 6

Expert Comment

by:psv1973
ID: 34969932
Can you try doing the same throguh the interface.

Create a new item and fill only Title, Part number and Price. Does the item save ok?
0
 
LVL 5

Author Comment

by:Isaac
ID: 34971217
>> Do you have checkin/checkout enabled on your list?  <<
Not sure how to disable/enable it

I am able to create and save a new item through the interface.
0
 
LVL 6

Accepted Solution

by:
psv1973 earned 500 total points
ID: 34971309
Can you replace

using (SPWeb myWeb = mySiteCollection.OpenWeb())

with

SPWeb myWeb = mySiteCollection.Rootweb;

0
 
LVL 5

Author Comment

by:Isaac
ID: 34971656
Now I get this error:
Error      2      'Microsoft.SharePoint.SPSite' does not contain a definition for 'Rootweb' and no extension method 'Rootweb' accepting a first argument of type 'Microsoft.SharePoint.SPSite' could be found (are you missing a using directive or an assembly reference?)      C:\Users\ISogunro\Documents\Visual Studio 2008\WebSites\partNum\Default.aspx.cs      31      52      C:\...\partNum\
0
 
LVL 6

Expert Comment

by:psv1973
ID: 34971809
That should have been RootWeb
0
 
LVL 5

Author Comment

by:Isaac
ID: 34971818
Ignore my last post.

I'm actually getting the same error as above.

invalidoperationexception was unhandled by user code
operation is not valid due to the current state of the object.
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 6

Expert Comment

by:psv1973
ID: 34971844
On the following link:
http://msdn.microsoft.com/en-us/library/ms467435.aspx

I found this example:

SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;

SPListItem item = listItems.Add();

item["Title"] = TextBox2.Text;
item["Stock"] = Convert.ToInt32(TextBox3.Text);
item["Return Date"] = Convert.ToDateTime(TextBox4.Text);
item["Employee"] = TextBox5.Text;

item.Update();

Open in new window



If your code is run from the site ( i.e. not a tiemr job or sothing like that) can you try using SPContext.Current.Web;
0
 
LVL 5

Author Comment

by:Isaac
ID: 34971884
If someone doesn't mind, could you create a list in your SharePoint environment that has 3 columns:
1)Title
2)Part Number
3)Price

Then try my code below.  I'm starting to wonder if it's the environment I'm in.  Just doesn't make sense why it's not working.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      
        string errVal = "";
         try  
          {              
             SPSecurity.RunWithElevatedPrivileges(delegate()
             {
                 using (SPSite mySiteCollection = new SPSite("http://landis/Lists/Parts/"))
                {
                    using (SPWeb myWeb = mySiteCollection.RootWeb)
                    {
                        myWeb.AllowUnsafeUpdates = true;
                        SPList PartsList = myWeb.Lists["Parts"];
                        SPListItem newPartItem = PartsList.Items.Add();

                        newPartItem["Title"] = title.Text;
                        newPartItem["Part Number"] = Convert.ToInt16(partNum.Text);
                        newPartItem["Price"] = Convert.ToDecimal(price.Text);

                        newPartItem.Update();
                        myWeb.AllowUnsafeUpdates = false;
                    }
                }
             });
         }
         catch (Exception f) 
         { 
             errVal = f.Message; 
         }
 


    }
}

Open in new window

0
 
LVL 6

Expert Comment

by:psv1973
ID: 34972056
That code worked for me. I stepped through the code witht he debuger and no problems at all. I added the button to a VisualWebpart project.
0
 
LVL 5

Author Comment

by:Isaac
ID: 34972107
DANG!
It might be my environment.
I'm with a certain branch of the government and they just implement HOST BASED SECURITY SYSTEM(HBSS) which seems to be breaking everything.  That's just a guess though.
0
 
LVL 5

Author Comment

by:Isaac
ID: 34972140
>> I added the button to a VisualWebpart project. <<
Did you use the exact same code I used?

>> SPWeb mySite = SPContext.Current.Web; <<
This won't work for me because I'm creating from a .aspx page.  see below:


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server" Text="Title"></asp:Label>
        <asp:TextBox ID="title" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Part Number"></asp:Label><asp:TextBox ID="partNum" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="Label3" runat="server" Text="Price"></asp:Label><asp:TextBox ID="price" runat="server"></asp:TextBox>
        <br />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    
    </div>
    </form>
</body>
</html>

Open in new window

0
 
LVL 6

Expert Comment

by:psv1973
ID: 34972163
Yes, the code is the same ( I just changed the Url and list name)
0
 
LVL 5

Author Comment

by:Isaac
ID: 34972230
How did you get the VisualWebPart project?
0
 
LVL 6

Expert Comment

by:psv1973
ID: 34972283
I created it in Visual Studio.

You can install the web part through the wsp attached if you like.
0
 
LVL 5

Author Comment

by:Isaac
ID: 34972336
Did you do it with visual studio 2008 on SharePoint 2007?
0
 
LVL 6

Expert Comment

by:psv1973
ID: 34972608
VS 2010
0
 
LVL 5

Author Comment

by:Isaac
ID: 34972824
I will try the code when I get home in my SharePoint environment to make sure it's not my work environment.
0
 
LVL 5

Author Comment

by:Isaac
ID: 34985324
This worked for me
try  
          {              


                 using (SPSite mySiteCollection = new SPSite(@"http://localhost:8716/sites/SolutionPortal"))
                 {
                        SPWeb myWeb = mySiteCollection.OpenWeb("SolutionSiteTemplate");
                        myWeb.AllowUnsafeUpdates = true;
                        SPList PartsList = myWeb.Lists["Parts"];
                        SPListItemCollection col = PartsList.Items;
                        Int32 itest = col.Count;
                        SPListItem newPartItem = col.Add();

                        newPartItem["Title"] = title.Text;
                        newPartItem["Part Number"] = Convert.ToInt16(partNum.Text);
                        newPartItem["Price"] = Convert.ToDecimal(price.Text);

                        newPartItem.Update();
                        itest = col.Count;
                        myWeb.AllowUnsafeUpdates = false;
                        myWeb.Close();
                }
         }
         catch (Exception f) 
         { 
             errVal = f.Message; 
         }
    }

Open in new window

0
 
LVL 5

Author Closing Comment

by:Isaac
ID: 34985336
My solution also worked which is the last comment
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now