Sunday, April 7, 2013

Trying to use an SPWeb object that has been closed or disposed and is no longer valid


Hi,

I got the below error post deploying my web part on the page.
Finally I got the issue from our Lead
In the code I was writing code as below
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
       {
       }
}

Generally once control comes out of the using block,it disposes all the objects inside that automatically.
so when I was writing code as below,it means I am saying to dispose the current context object which is not suppose to   
using(SPSite objsite = SPContext.Current.Site)

That’s why I have been guided to write as below
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                     {
                     }
                                      }
It means,we are instanatiating new SPSite object by using in using block,while coming out of loop it disposes the newly created SPSite object.



Error Creating Control:Microsoft.SharePoint.Proxy dll is being used by another process


Hi,

Some times when we open master page through SharePoint  designer, we get an error as below screen shot

Resolution: To overcome got one and only solution from our solution i.e. ‘RESTART’ the machine.

Post this it went fine and am able to open the master page without any issues.


Share Feedback WebPart


Hi,

There was a requirement on sharing the feedback on the current page. For this web part has been developed and placed on the master page as below

For this, list has been setup  where Email Subject, To Field will be taken as inputs to compose the mail as below.

In the list, Email Subject field just hold 0.this has to been replaced with Current Page Name.
Below is the code that has been written so that user clicks on ‘ShareFeedBack’ link, new email will be opened in the outlook to share feedback on current page.

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

using System.Globalization;
using AZ.SharePoint.Common.Logging;
using Microsoft.Practices.SharePoint.Common.Logging;
using Microsoft.Practices.SharePoint.Common.ServiceLocation;


namespace SharePoint.MLZ.ShareFeedback.ShareFeedback
{
    public partial class ShareFeedbackUserControl : UserControl
    {
        #region Private Variables       
        string strEmailAddress = string.Empty;
        string strSubject = string.Empty;
        string strTo = string.Empty;
        /// <summary>
        /// Initialises logger object
        /// </summary>
        private Microsoft.Practices.SharePoint.Common.Logging.ILogger logger = SharePointServiceLocator.GetCurrent().GetInstance<Microsoft.Practices.SharePoint.Common.Logging.ILogger>();
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            SendSupportEmail();
        }

        #region Private Methods
        /// <summary>
        /// Create an Email to share FeedBack on current page
        /// </summary>
        /// <returns>DataTable</returns>
        private void SendSupportEmail()
        {
            try
            {
                string pageUrl = this.Page.Request.Url.ToString();
                string[] pageStrings = pageUrl.Split('/');
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList objlist = web.Lists.TryGetList("EmailConfigurations");
                        SPQuery query = new SPQuery();
                        query.Query = "<Where><Eq><FieldRef Name='ComponentName'/><Value Type='Choice'>Share Feedback</Value></Eq></Where>";

                        SPListItemCollection itemcoll = objlist.GetItems(query);                       

                        foreach (SPListItem item in itemcoll)                      
                        {
                            if (item["EmailSubject"].ToString() != null && item["To"].ToString()!=null)                            
                            {
                                string subject = item["EmailSubject"].ToString();
                                strSubject = subject.Replace("{0}", pageStrings[pageStrings.Length - 1].Split('.')[0].ToString());
                                strTo = item["To"].ToString();
                            }
                        }
                        SPGroup grp = web.SiteGroups[strTo];
                        foreach (SPUser user in grp.Users)
                        {
                            strEmailAddress = string.Concat(strEmailAddress, user.Email, ";");
                        }
                        AnchorShareFeedback.HRef = string.Concat("mailto:", strEmailAddress, "?subject=", strSubject);
                    }
                }
            }
            catch (ArgumentException ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, "Failed to Send an Email"Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }
            catch (InvalidOperationException ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, "Failed to Send an Email"Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }
            catch (Exception ex)
            {
                ////Log to ULS and Windows Event Logs
                this.logger.LogToOperations(ex, "Failed to Send an Email"Convert.ToInt32(EventLogEventId.TimerJobEvent, CultureInfo.CurrentCulture), Microsoft.SharePoint.Administration.EventSeverity.Error, null);
            }



        }
        #endregion
    }
}



Sunday, March 31, 2013

Displaying Subsites as per the Access


Hi,

Last week I got a new task i.e. in the web part it should display all the sub sites under the site collection.
If user has an access to the sub site, then it should display only Site Name, description and
If user hasn't got access to the site, then it should display only Site Name, description along with ‘Request To Join’ as below

If user clicks ‘Request To Join’ button, email has to be triggered to User group ‘Key Contacts’ members and maiBody,subject should be fetched from ‘EmailConfigurations’ list.
In that list, there will be column name as ‘Community Site Request To Join’
Mail Body, Mail Subject details should be fetched from the row as below
Below is the code that has been written to achieve this functionality
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Globalization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Diagnostics;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Specialized;
 namespace DataListSample.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        #region  Variables
        PagedDataSource PageDataSource= new PagedDataSource();
        private DataTable dTableAllSites;
        private DataTable dTableMatchingSites;
        #endregion       

        #region Private Properties
        private int CurrentPage
        {
            get
            {
                object objPage = ViewState["_CurrentPage"];
                int _CurrentPage = 0;
                if (objPage == null)
                {
                    _CurrentPage = 0;
                }
                else
                {
                    _CurrentPage = (int)objPage;
                }
                return _CurrentPage;
            }
            set { ViewState["_CurrentPage"] = value; }
        }

        private int firstIndex
        {
            get
            {

                int _FirstIndex = 0;
                if (ViewState["_FirstIndex"] == null)
                {
                    _FirstIndex = 0;
                }
                else
                {
                    _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
                }
                return _FirstIndex;
            }
            set { ViewState["_FirstIndex"] = value; }
        }

        private int lastIndex
        {
            get
            {

                int _LastIndex = 0;
                if (ViewState["_LastIndex"] == null)
                {
                    _LastIndex = 0;
                }
                else
                {
                    _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
                }
                return _LastIndex;
            }
            set { ViewState["_LastIndex"] = value; }
        }
       

        #region Private Methods
        /// <summary>
        /// Build DataTable to bind Main Items List
        /// </summary>
        /// <returns>DataTable</returns>
        private DataTable GetTable()
        {
            dTableAllSites = new DataTable();
            dTableAllSites.Locale = CultureInfo.InvariantCulture;
            dTableAllSites.Columns.Add("SiteName"typeof(string));
            dTableAllSites.Columns.Add("Description"typeof(string));
            dTableAllSites.Columns.Add("Url"typeof(string));
            dTableAllSites.Columns.Add("RequestAccess"typeof(bool));
            return dTableAllSites;
        }

        private DataTable GetTableForSearch()
        {
            dTableMatchingSites = new DataTable();
            dTableMatchingSites.Locale = CultureInfo.InvariantCulture;
            dTableMatchingSites.Columns.Add("SiteName"typeof(string));
            dTableMatchingSites.Columns.Add("Description"typeof(string));
            dTableMatchingSites.Columns.Add("Url"typeof(string));
            dTableMatchingSites.Columns.Add("RequestAccess"typeof(bool));
            return dTableMatchingSites;
        }
    #endregion

        /// <summary>
        /// Binding Main Items List
        /// </summary>
        private void BindItemsList()
        {
            dTableAllSites = GetSites();

            dListItems.DataSource = dTableAllSites;
            dListItems.DataBind();


            PageDataSource.DataSource = dTableAllSites.DefaultView;
            PageDataSource.AllowPaging = true;
            PageDataSource.PageSize = 10;
            PageDataSource.CurrentPageIndex = CurrentPage;
            ViewState["TotalPages"] = PageDataSource.PageCount;

            this.lblPageInfo.Text = (CurrentPage + 1) + " | " + PageDataSource.PageCount;
            this.lbtnPrevious.Enabled = !PageDataSource.IsFirstPage;
            this.lbtnNext.Enabled = !PageDataSource.IsLastPage;


            this.dListItems.DataSource = PageDataSource;
            this.dListItems.DataBind();
            this.doPaging();
        }

        /// <summary>
        /// Binding Paging List
        /// </summary>
        private void doPaging()
        {
            DataTable dtPaging = new DataTable();
            dtPaging.Columns.Add("PageIndex");
            dtPaging.Columns.Add("PageText");

            firstIndex = CurrentPage - 5;

            if (CurrentPage > 5)
            {
                lastIndex = CurrentPage + 5;
            }
            else
            {
                lastIndex = 10;
            }
            if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
            {
                lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                firstIndex = lastIndex - 10;
            }

            if (firstIndex < 0)
            {
                firstIndex = 0;
            }

            for (int i = firstIndex; i < lastIndex; i++)
            {
                DataRow dr = dtPaging.NewRow();
                dr[0] = i;
                dr[1] = i + 1;
                dtPaging.Rows.Add(dr);
            }

            this.dlPaging.DataSource = dtPaging;
            this.dlPaging.DataBind();
        }     


      

        private DataTable GetSites()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {               
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb oWebsite = site.OpenWeb())
                    {  
                        dTableAllSites = GetTable();

                        foreach (SPWeb subSite in oWebsite.Webs)
                        {
                            DataRow dtRow = null;

                            dtRow = dTableAllSites.NewRow();
                            if (subSite.Title != null)
                            {
                                dtRow["SiteName"] = Convert.ToString(subSite.Title);
                            }
                            if (subSite.Description != null)
                            {
                                dtRow["Description"] = Convert.ToString(subSite.Description);
                            }
                            if (subSite.Url != null)
                            {
                                dtRow["Url"] = Convert.ToString(subSite.Url);
                            }
                            if (subSite.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser.LoginName,SPBasePermissions.Open) == true)
                            {
                                dtRow["RequestAccess"] = false;
                            }
                            else
                            {
                                dtRow["RequestAccess"] = true;
                            }
                            dTableAllSites.Rows.Add(dtRow);
                        }
                    }
                }
            });

            dTableAllSites.AcceptChanges();

            return dTableAllSites;

        }

        private DataTable GetMatchingSites()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
               

                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb oWebsite = site.OpenWeb())
                    {
                        dTableMatchingSites = GetTableForSearch();

                        foreach (SPWeb subSite in oWebsite.Webs)
                        {
                            DataRow dtRow = null;
                                                       
                            if ((subSite.Title.ToLower()).Contains(txtSites.Text.ToLower()))
                            {
                                dtRow = dTableMatchingSites.NewRow();

                                dtRow["SiteName"] = Convert.ToString(subSite.Title);
                                dtRow["Description"] = Convert.ToString(subSite.Description);
                                dtRow["Url"] = Convert.ToString(subSite.Url);
                                if (subSite.DoesUserHavePermissions(SPContext.Current.Web.CurrentUser.LoginName,SPBasePermissions.Open) == true)
                                {
                                    dtRow["RequestAccess"] = false;
                                }
                                else
                                {
                                    dtRow["RequestAccess"] = true;
                                }
                                dTableMatchingSites.Rows.Add(dtRow);
                            }                           
                        }

                    }
                }
            });

            dTableMatchingSites.AcceptChanges();

            return dTableMatchingSites;
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {
                BindItemsList();


            }

        }

        protected void ImgSearch_Click(object sender, ImageClickEventArgs e)
        {
            dTableMatchingSites = GetMatchingSites();
            dListItems.DataSource = dTableMatchingSites;
            dListItems.DataBind();
        }             

        protected void lbtnNext_Click(object sender, EventArgs e)
        {
            CurrentPage += 1;
            this.BindItemsList();
        }

        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            this.BindItemsList();
        }
        protected void lbtnRequestToJoin_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPGroup grp = web.SiteGroups["KeyContacts"];
                    {
                        foreach (SPUser user in grp.Users)
                        {
                            SPList objlist = web.Lists["EmailConfigurations"];
                           
                            foreach (SPListItem item in objlist.Items)
                            {
                                
                                if (item["ComponentName"].ToString() == "Community Site Request To Join")
                                {
                                StringDictionary headers = new StringDictionary();
                                headers.Add("To", user.Email);
                                headers.Add("subject", item["EmailSubject"].ToString());                              

                                System.Text.StringBuilder strMessage = new System.Text.StringBuilder();                               
                                strMessage.Append(item["EmailBody"].ToString());
                                SPUtility.SendEmail(web, headers, strMessage.ToString());
                                }
                            }
                        }
                    }
                }
            }

        }     

      

    }
}


Testing
Coming to testing part,before testing below steps have been followed to view the result
1.       User id needs to be added as site collection administrator
2.       User id needs to be added in the ‘Owner’ group of the site collection
3.       In all the subsites ‘Stop inheriting permissions’ have been removed all groups have been removed by ‘Remove permissions’
4.       In some subsites User id has been added by providing ‘Full Control’
5.       User id has been removed as administrator of the site collection and web part has been added to site collection page