2

I have a web part code with no controls on it. This web part simply checks the current login user entry in a custom list. If found the user can access the home page else it redirects the user to a page where the user needs to accept the policy and code of conduct of company which is another web part.

Now when I insert the first web part on home page, after saving the page I am encountering with below error.

Error: This page contains content or formatting that is not valid. You can find more information in the affected sections

Below is the web part code. Please let me know what changes should I make below:

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace CheckPolicyAccept.CheckPolicyAccept
{
[ToolboxItemAttribute(false)]

public class CheckPolicy : WebPart
{
    // Visual Studio might automatically update this path when you change the Visual Web Part project item.
    private const string _ascxPath = @"~/_CONTROLTEMPLATES/CheckPolicyAccept/CheckPolicyAccept/CheckPolicyAccept.ascx";

    protected override void CreateChildControls()
    {
        WebPartManager wp = WebPartManager.GetCurrentWebPartManager(this.Page);

        if (wp.DisplayMode == WebPartManager.BrowseDisplayMode)
        {
            base.CreateChildControls();
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);
        }
    }
}

public partial class CheckPolicyAcceptUserControl : UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = string.Empty;

        LogMessage(TraceSeverity.None,"Executing Check Policy");

        try
        {
            if (IsPostBack != true)
            {
                Guid siteId = SPContext.Current.Site.ID;
                Guid webId = SPContext.Current.Site.OpenWeb().ID;
                SPUser spUser = SPContext.Current.Site.OpenWeb().CurrentUser;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string currentLoginName = string.Empty;
                    string currentUserDisplayName = string.Empty;

                    using (SPSite spSite = new SPSite(siteId))
                    {
                        using (SPWeb spWeb = spSite.OpenWeb(webId))
                        {
                            currentLoginName = spUser.LoginName;
                            currentUserDisplayName = spUser.Name;

                            SPList spList = spWeb.Lists["Policy Acceptance Status"];
                            SPQuery spQuery = new SPQuery();
                            LogMessage(TraceSeverity.None, "Executing Policy Check for: " + currentLoginName);
                            spQuery.Query = "<Where><Eq><FieldRef Name='EmpName' /><Value Type='Text'>" + currentLoginName + "</Value></Eq></Where>";
                            SPListItemCollection spListItemCollection = spList.GetItems(spQuery);

                            if (spListItemCollection.Count == 0)
                            {
                                url = returnPolicyAcceptancePageURL();
                                LogMessage(TraceSeverity.None, "Check Policy User: " + currentLoginName + " now redirecting to URL: " + url);
                                if (!string.IsNullOrEmpty(url))
                                {
                                    Response.Redirect(url, false);
                                }
                            }
                        }
                    }
                });
            }
        }


        catch (Exception ex)
        {
            LogMessage(ex);
        }
    }

    public string returnPolicyAcceptancePageURL()
    {
        string siteURL = string.Empty;
        Guid siteId = SPContext.Current.Site.ID;
        Guid webId = SPContext.Current.Site.OpenWeb().ID;
        SPSecurity.RunWithElevatedPrivileges(delegate()
           {
               SPSite spSite = new SPSite(siteId);
               SPWeb spWeb = spSite.OpenWeb(webId);

               SPList spList = spWeb.Lists["RedirectUrl"];

               SPListItemCollection itemColl = spList.Items;

               foreach (SPListItem item in itemColl)
               {
                   if (Convert.ToString(item["Title"]) == "Policy Acceptance")
                   {
                       siteURL = Convert.ToString(item["Url"]);
                   }

               }
           });
        return siteURL;
    }

    private void LogMessage(TraceSeverity severity,string message)
    {
        SPSecurity.RunWithElevatedPrivileges(delegate()
          {
              uint uintEventID = 700;//event ID
              string CategoryName = "Check Policy Webpart";
              SPDiagnosticsCategory category = new SPDiagnosticsCategory(CategoryName, TraceSeverity.Medium, EventSeverity.Error);
              SPDiagnosticsService.Local.WriteTrace(uintEventID, category, TraceSeverity.Unexpected, message);
          });
    }

    private void LogMessage(Exception ex)
    {
        LogMessage(TraceSeverity.High, ex.Message + ex.StackTrace);
    }

}

}

Ascx code (In ascx file I have used no controls since my web part only checks the user detail as given above in ascx.cs code)

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CheckPolicy.ascx.cs" Inherits="CheckPolicy.CheckPolicy.CheckPolicyUserControl" %>
3
  • Could you show us also the ASCX file, please?
    – Norbert
    Aug 26, 2013 at 5:54
  • Hi Norbert, I have added ascx code to my above question. Kindly check.
    – Zakir HC
    Aug 26, 2013 at 6:17
  • I'm curious to know what the StackTrace says. Could please paste in the StackTrace thrown when this error occurs? Also, have you tried debugging your code?
    – user2536
    Aug 26, 2013 at 6:33

2 Answers 2

0

According to your updated question, I can tell you, that something is not right in your code :)

Your ASCX file inherits from CheckPolicy.CheckPolicy.CheckPolicyUserControl class, but your UserControl class in your CheckPolicy.ascx.cs file is CheckPolicyAccept.CheckPolicyAccept.CheckPolicyAcceptUserControl. It might be a typo, but it could also cause the error you see.

In your case I would create a new web part, but this time I wouldn't choose the Visual Web Part template, but the simple one, as you don't have anything "visual" to add to your web part, just code. This way you will not have to complicate yourself with the ASCX file and the CreateChildControls method, etc.

Also, though it's probably not the cause of the error, I would like to point it out to you, that you are leaving undisposed SPSite and SPWeb instances, which is a very wrong habit for a Sharepoint Developer. You can see more about this topic with examples, here.

To avoid any memory leaks and to improve a little the performance of your code, I would rewrite the returnPoliciyAcceptancePageUrl as follows:

public string returnPolicyAcceptancePageURL()
{
    string siteURL = string.Empty;
    
    Guid siteId = SPContext.Current.Site.ID;
    // When you do OpenWeb(), you create a new SPWeb, which is never disposed.
    // Guid webId = SPContext.Current.Site.OpenWeb().ID;
    SPSecurity.RunWithElevatedPrivileges(delegate()
       {
           using(SPSite spSite = new SPSite(siteId)){
             SPWeb spWeb = spSite.RootWeb;

             SPList spList = spWeb.Lists.TryGetList("RedirectUrl");
             if(spList==null){
                // Throw exception or log message and return
             }
             // Using a query to limit the number of rows to exactly the ONE row you need
             SPQuery query = new SPQuery();
             query.Query="<Where><Eq><FieldRef Name="Title"/><Value Type=\"Text\">Policy Acceptance</Value></Eq></Where><OrderBy><FieldRef Name=\"Created\" Ascending=\"FALSE\"/></OrderBy>";
             query.ViewFields="<FieldRef Name=\"Title\"/><FieldRef Name=\"Url\"/>";
             SPListItemCollection itemColl = spList.GetItems(query);
             if(itemColl.Count>0){
               siteURL = itemColl[0]["Url"] == null ? string.Empty : itemColl[0]["Url"].ToString();
             }
           }
       });
    return siteURL;
}

I have written this code from memory, so please forgive me if something is not working right from the beginning or if it's not compiling. It is meant to give you an idea about how should you do it :) I hope this solved your problem. If not, please feel free to come back to me.

Cheers!

0

Use SPUtility.Redirect instead Response.Redirect - i assume your redirect breaks the webpart.

1
  • I honestly doubt that Response.Redirect brakes the web part, because the two of them are basically the same. I didn't check, but I am pretty sure that SPUtility.Redirect calls Response.Redirect at one point.
    – Norbert
    Aug 26, 2013 at 7:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.