sharepointweb-partssandbox-solution

Error when adding a sandbox solution Webpart to a page in Sharepoint 2010


I have compiled a Sandboxed webpart and deployed it to the Sharepoint 2010 server. However, when I try to add it to a page I get the following error

Unhandled exception was thrown by the sandboxed code wrapper's Execute method in the partial trust app domain: $Resources:core,ImportErrorMessage

I've included my Sandboxed Webpart code below. I can't work out how to fix this error, or work out what is causing the problem

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;

namespace Competency_Assessment.wp_selectRatings
{
[ToolboxItemAttribute(false)]
public class wp_selectRatings : WebPart
{

    [Serializable]
    private class Rating
    {
        public String rating;
        public String competency;
        public String accountname;
        public String revieweraccount;
        public String itemid;
        public Boolean updatable;
    }

    //Start by declaring ASP.NET controls in the class scope
    SPWeb thisWeb = SPContext.Current.Web;
    SPList ratingsList;
    SPList competencyList;
    Panel hiddenPanel;
    Button submitRatingsButton;
    RadioButtonList exampleRadioButtonList;
    TextBox t1;
    //TextBox t2;
    Button refreshPersonButton;
    String cuser = "";
    String cusername = "";
    List<Rating> ratings = new List<Rating>();
    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();


    protected override void OnInit(EventArgs e)
    {
        ratingsList = thisWeb.Lists["Competency Ratings"];
        competencyList = thisWeb.Lists["Competencies"];
        LoadRatings();
        base.OnInit(e);
    }

    //protected override void RenderContents(HtmlTextWriter writer)
    //{
    //    StringBuilder js = new StringBuilder();

    //    js.AppendLine("  var head = document.getElementsByTagName(\"head\")[0];");
    //    js.AppendLine("  if(document.createStyleSheet)");
    //    js.AppendLine("  {");
    //    js.AppendLine("    document.createStyleSheet('" + SPContext.Current.Site.Url + "/Lists/Assets/Styles1.css" + "');");
    //    js.AppendLine("  } else {");
    //    js.AppendLine("    var css = document.createElement('link');");
    //    js.AppendLine("    css.type = 'text/css';");
    //    js.AppendLine("    css.rel = 'stylesheet';");
    //    js.AppendLine("    css.href = '" + SPContext.Current.Site.Url + "/Lists/Assets/Styles1.css" + "';");
    //    js.AppendLine("    head.appendChild(css);");
    //    js.AppendLine("  }");

    //    base.RenderContents(writer);

    //    writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
    //    writer.RenderBeginTag(HtmlTextWriterTag.Script);
    //    writer.WriteLine(js.ToString());
    //    writer.RenderEndTag();
    //}

    protected override void CreateChildControls()
    {

        //Testing textboxes
        t1 = new TextBox();
        //t2 = new TextBox();

        this.Controls.Add(t1);
        //this.Controls.Add(t2);

        refreshPersonButton = new Button();
        refreshPersonButton.Text = "Search";
        refreshPersonButton.Click += new EventHandler(refreshPersonButton_Click);
        this.Controls.Add(refreshPersonButton);

        //Set up the panel control
        hiddenPanel = new Panel();
        hiddenPanel.GroupingText = "Competency Ratings";
        //We'll hide it by default.
        hiddenPanel.Visible = false;
        this.Controls.Add(hiddenPanel);

        hiddenPanel.Controls.Add(new LiteralControl("<br/>"));
        hiddenPanel.Controls.Add(new LiteralControl("<table id='table-6'>"));


        //iterate the matching entries
        string prevname = "";
        string currentname = "";
        foreach (Rating rating in ratings)
        {
            currentname = rating.accountname;
            if (!currentname.Equals(prevname))
            {
                //Table Heading
                hiddenPanel.Controls.Add(new LiteralControl("<tr>"));
                hiddenPanel.Controls.Add(new LiteralControl("<td colspan='2' class='namestyle'>" + currentname.ToUpper() + "</td>"));
                hiddenPanel.Controls.Add(new LiteralControl("</tr>"));
            }
            prevname = rating.accountname;

            hiddenPanel.Controls.Add(new LiteralControl("<tr>"));

            hiddenPanel.Controls.Add(new LiteralControl("<td>"));

            Label l1 = new Label();
            l1.Text = rating.competency;
            hiddenPanel.Controls.Add(l1);

            hiddenPanel.Controls.Add(new LiteralControl("</td><td>"));

            //Set up the radio button list
            exampleRadioButtonList = new RadioButtonList();

            exampleRadioButtonList.ID = rating.itemid;

            exampleRadioButtonList.RepeatDirection = RepeatDirection.Horizontal;

            exampleRadioButtonList.Items.Add("1");
            exampleRadioButtonList.Items.Add("2");
            exampleRadioButtonList.Items.Add("3");
            exampleRadioButtonList.Items.Add("4");
            exampleRadioButtonList.Items.Add("5");
            exampleRadioButtonList.SelectedValue = rating.rating;
            exampleRadioButtonList.Enabled = rating.updatable;

            hiddenPanel.Controls.Add(exampleRadioButtonList);

            hiddenPanel.Controls.Add(new LiteralControl("</td>"));
            hiddenPanel.Controls.Add(new LiteralControl("</tr>"));
        }
        hiddenPanel.Controls.Add(new LiteralControl("</table>"));

        //Set up the Submit Ratings button
        submitRatingsButton = new Button();
        submitRatingsButton.Text = "Submit ratings";
        //handle the button's click event
        submitRatingsButton.Click += new EventHandler(submitRatingsButton_Click);
        hiddenPanel.Controls.Add(submitRatingsButton);
    }


    private void LoadRatings()
    {
        //clear ratings
        ratings.Clear();

        //Set the query to search for existing ratings
        SPQuery query = new SPQuery();
        query.ViewFields = "<FieldRef Name='Rating'/>" + "<FieldRef Name='Title'/>" + "<FieldRef Name='Employee'/>";
        if (cuser.Equals(""))
        {
            query.Query = "<OrderBy><FieldRef Name='Employee' /></OrderBy>";
        }
        else
        {
            query.Query = "<Where><Contains><FieldRef Name='Title' /><Value Type='Text'>" + cuser + "</Value></Contains></Where>" + "<OrderBy><FieldRef Name='Employee' /></OrderBy>";

        }


        SPListItemCollection collListItems = ratingsList.GetItems(query);

        foreach (SPListItem item in collListItems)
        {
            Rating thisrating = new Rating();
            SPFieldUser field = item.Fields["Employee"] as SPFieldUser;

            if (field != null)
            {
                SPFieldUserValue fieldValue = field.GetFieldValue(item["Employee"].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    thisrating.accountname = fieldValue.User.Name;
                }
                else
                {
                    thisrating.accountname = "";
                }
            }
            else
            {
                thisrating.accountname = "";
            }
            //thisrating.accountname = cuser;
            thisrating.rating = ((double)item["Rating"]).ToString();
            thisrating.competency = item.Title;
            thisrating.itemid = item.ID.ToString();
            thisrating.revieweraccount = "SHAREPOINT\\system";
            if (canPersonRate(thisrating.competency))
            {
                thisrating.updatable = true;
            }
            ratings.Add(thisrating);
        }


    }


    private Boolean canPersonRate(string competencyname)
    {
        Boolean canrate = false;
        SPQuery query = new SPQuery();
        query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + competencyname + "</Value></Eq></Where>";
        query.ViewFields = "<FieldRef Name='Owner'/>";

        SPListItemCollection collListItems = competencyList.GetItems(query);

        foreach (SPListItem item in collListItems)
        {

            SPFieldUser field = item.Fields["Owner"] as SPFieldUser;

            if (field != null)
            {
                SPFieldUserValue fieldValue = field.GetFieldValue(item["Owner"].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    string str = fieldValue.User.LoginName;
                    if (str  == SPContext.Current.Web.CurrentUser.LoginName)
                    {
                        canrate = true;
                    }
                }
            }
        }
        return canrate;
    }


    protected override object SaveViewState()
    {
        object[] state = new object[4];
        state[0] = cuser;
        state[1] = cusername;
        state[2] = js.Serialize(ratings);
        state[3] = base.SaveViewState();
        return state;
    }

    protected override void LoadViewState(object savedState)
    {
        if (savedState != null)
        {
            object[] state = (object[])savedState;
            cuser = (string)state[0];
            cusername = (string)state[1];
            //Rating[] myArray = (Rating[])state[2];
            //ratings = (List<Rating>)state[2];
            //ratings = new List<Rating>(myArray);
            ratings = js.Deserialize<List<Rating>>((string)state[2]);
            base.LoadViewState(state[3]);
        }
        else
        {
            base.LoadViewState(savedState);
        }
    }

    void refreshPersonButton_Click(object sender, EventArgs e)
    {

        Controls.Clear();
        ClearChildViewState();
        ChildControlsCreated = false;

        //Refresh ratings display
        cuser = t1.Text;
        //cusername = t2.Text;
        LoadRatings();

        EnsureChildControls();
        t1.Text = cuser;
        //t2.Text = cusername;
        //Show the hidden panel
        hiddenPanel.Visible = true;

    }

    void submitRatingsButton_Click(object sender, EventArgs e)
    {
        //hiddenPanel.Visible = false;

        foreach (Rating rating in ratings)
        {
            //get current value of control to check if value has changed
            Control ratingctrl = (FindControl(rating.itemid));
            if (ratingctrl == null)
            {
                //No matching rating control found
            }
            else
            {
                String cval = ((RadioButtonList)ratingctrl).SelectedValue;
                //Only update List item if the rating has changed!
                if (cval != rating.rating)
                {
                    SPItem itemtoupdate = ratingsList.GetItemById(Convert.ToInt32(rating.itemid));
                    itemtoupdate["Rating"] = cval;
                    itemtoupdate.Update();

                }
            }

        }
    }
}

}


Solution

  • JavaScriptSerializer requires ReflectionPermission to run. I don't think sandbox solution is granted with this permission according to this article about restrictions on Sandboxed Solutions in SharePoint 2010.