Wednesday, 27 June 2012

Clear Team Site home.aspx by c# code

Here's how you clear the home.aspx page of a default Team Site programmatically
        public void clearContentOnMain()
        {
            try
            {
                using (SPSite site = new SPSite(TEAMSITEURL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPFile homePage = web.GetFile("SitePages/Home.aspx");
                        if (homePage.Exists)
                        {
                            homePage.Item[SPBuiltInFieldId.WikiField] = "";
                            homePage.Item.Update();

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SPException("Error getting SitePages/Home.aspx " + ex.ToString());
            }

        }

Tuesday, 26 June 2012

User vs UserMulti

I spent almost a whole day trying to figure out why ViewFieldsOverride only imports the UserName of AssignedTo field in Content Query Web Part.

After trying various ways and banging my head against the table, it turns out that by changing Type="UserMulti" from Type="User", AssignedTo field will have the format 'ID;#UserName'.

Friday, 8 June 2012

Add Presence Icon to SPGridview

I spent hours trying to figure out why my presence image only appears for the last instance of the particular user, and I finally figured out why, id has to be unique.
to show image presence, I attached to rowdatabound event with the required javascript

       protected void gvProjOverview_RowDataBound(object sender, GridViewRowEventArgs e)
        { 
            if(e.Row.DataItem!=null)
            {
                SPWeb web = SPContext.Current.Web; 

                SPUser user = web.EnsureUser("DOMAIN\login");
 
                e.Row.Cells[4].Text = ""
                    + " "
                    + ""
                    + "" + user.Name +  ""
                    + "";
            }
        }

id='imn_" + e.Row.RowIndex <- this was where I had used user.ID which was not unique and thus the presence icon was only showing for one of the available users.

The lack of distinct ID causes some presence icon to disappear, that is, if user Andy is on two of the rows, the presence icon only appears for the last row where Andy is in.

Thursday, 7 June 2012

EditorWebPart wierd behavior

I was trying to implement EditorPart and I find that the webpart doesn't update when OK or Apply is clicked. Only when it's been refreshed then the changes appear.
Going through the code shows that the cycle order is : CreateChildControls ApplyChanges OnPreRender
So since I am setting the value in CreateChildControls, it was using the old value before the changes happen in ApplyChanges.
Moving code under CreateChildControls to be in OnPreRender sets automatic update when Apply/OK is clicked.

Wednesday, 6 June 2012

Extending the Content Query Web Part (ContentByQueryWebPart)

I was assigned a task to allow filtering of CQWP results without requiring the user to edit the webpart.
I figured out the following simple way to extend the CQWP by having the filtering done with a drop down list on the webpart itself.
At first I wanted to use the consumer/provider method but decided this was easier...
Here's the code:
namespace ExtendCQWP.FilterWP
{
    [ToolboxItemAttribute(false)]
    public class FilterWP: Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart
    {
        protected override void OnLoad(EventArgs e)
        { 
            if (this.Page.Request.QueryString["FilterField1"]!=null && this.Page.Request.QueryString["FilterValue1"]!=null)
            {
                this.FilterField1 = this.Page.Request.QueryString["FilterField1"].ToString(); 
                this.FilterValue1 = this.Page.Request.QueryString["FilterValue1"].ToString();
            }
        }
        protected override void CreateChildControls()
        {             
            DropDownList ddl = new DropDownList();
            ddl.Items.Add(new ListItem("All", "All"));            
            ddl.Items.Add(new ListItem("HR", "HR"));
            ddl.Items.Add(new ListItem("Finance", "Finance"));
            ddl.Items.Add(new ListItem("IT", "IT"));

            ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
            ddl.AutoPostBack = true;
            ddl.EnableViewState = true;

            if (this.Page.Request.QueryString["FilterValue1"] != null)
            { 
                foreach(ListItem item in ddl.Items)
                    if(item.Text.Equals(this.Page.Request.QueryString["FilterValue1"].ToString()))
                    {
                        item.Selected = true;
                        break;
                    }
            }

            this.Controls.Add(ddl);            
            base.CreateChildControls();
        }

        void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList tmpddl = (DropDownList)sender;
            if(tmpddl.SelectedValue.Equals("All"))
                SPUtility.Redirect("http://mysite/SitePages/cq.aspx", SPRedirectFlags.Trusted, HttpContext.Current);
            else
                SPUtility.Redirect("http://mysite/SitePages/cq.aspx?FilterField1=Division&FilterValue1=" + tmpddl.SelectedValue, SPRedirectFlags.Trusted, HttpContext.Current);
        }
    }
}

Here's how the list and web part looks like.

Monday, 4 June 2012

Attempted to use an object that has ceased to exist

I received this error when trying to insert/edit web part
Attempted to use an object that has ceased to exist

The resolution was to remove USING statement when using SPContext.Current.Web;

This issue happened because SPContext.Current.Web disposes the web object automatically, and by adding a

using
statement, it will try to dispose it again when there's nothing to dispose.

SPMenuField disappears when/after Edit Mode

There has been an issue that has been bugging me when I create an SPMenuField, editing the page will result in the menu field columns disappearing.

After spending hours trialing and erroring, it was resolved by adding a .DataBind() in the Page_Load method.

UserControl.ascx.cs

        protected void Page_Load(object sender, EventArgs e)
        { 
          gvPPL.DataBind();
        }

UserControl.ascx


<SharePoint:MenuTemplate ID="gvPPLMenu" runat="server">
    <SharePoint:MenuItemTemplate ID="editMenu" runat="server" Text="Edit" ClientOnClickNavigateUrl="/_layouts/BPOSproperties/ProjectSettings.aspx?type=edit&url=%EDIT%" />
</SharePoint:MenuTemplate>
<SharePoint:SPGridView ID="gvPPL" runat="server" AutoGenerateColumns="false" DataSourceID="pplDataSource">
    <Columns>
        <SharePoint:SPMenuField HeaderText="NameMenu" TextFields="Name" MenuTemplateId="gvPPLMenu"
        NavigateUrlFields="Email" NavigateUrlFormat="{0}" TokenNameAndValueFields="EDIT=Email" />
        <SharePoint:SPBoundField HeaderText="Name" DataField="Name"  />
    </Columns>
</SharePoint:SPGridView>

<asp:ObjectDataSource ID="pplDataSource" runat="server" TypeName="BPOSsite.PeopleManager, BPOSsite, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c9ab07f514f0925b" SelectMethod="GetPeople"  />

People.cs


namespace BPOSsite
{
    public class People
    {
        private string name;
        private string email;

        public People(string n, string e)
        {
            this.email = e;
            this.name = n;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Email
        {
            get { return email; }
            set { email = value; }
        }
    }

    public class PeopleManager
    {
        public List<People> GetPeople()
        {
            List<People> list = new List<People>();
            list.Add(new People("John", "john@mail.com"));
            list.Add(new People("Nick", "nick@mail.com"));
            list.Add(new People("Tracy", "tracy@mail.com"));
            list.Add(new People("Dick", "dick@mail.com"));
            return list; 
        }    
    }
}

Friday, 1 June 2012

ObjectDataSource TypeName not found

In sharepoint i had to list ObjectDataSource this way

<asp:ObjectDataSource ID="pplDataSource" runat="server" TypeName="MyNameSpace.PeopleManager, MyNameSpace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c9ab07f514f0925b" SelectMethod="GetPeople"  />

else I will get 'TypeName not found' error.