Thursday, July 28, 2011

Passing Property Value from WebPart to USer Control in MOSS

Any time came across a scenario where you have to pass property value from WebPart hosting the UserControl to pass value in SharePoint 2007.
Here is a small example how you can achive this.
The Solution structure
As you see by default you can't see the User Control template ,the easiest way of  doing this Unload the project "Right Click"  click as shown in the image
Add this GUID under the section where it says <ProjectTypeGuids>
{349C5851-65DF-11DA-9384-00065B846F21};
Save it and reload the project "Bingo" you can see the User Control template.
WebPart Code :
 public class ValueToUC : System.Web.UI.WebControls.WebParts.WebPart
    {
        private bool _error = false;
        private string _myName = null;
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/ValueToUC/ValueUC.ascx";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("My Properties")]
        [WebDisplayName("MyName")]
        [WebDescription("MyName")]
        public string MyProperty
        {
            get { return _myName;  }
            set { _myName = value; }
        }
     
        public ValueToUC()
        {
            this.ExportMode = WebPartExportMode.All;
            this.ChromeType = PartChromeType.None;
        }     

        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {
                    base.CreateChildControls();

                    ValueUC uc = (ValueUC)Page.LoadControl(_ascxPath);
                    uc.parentWp = this;
                    this.Controls.Add(uc);                                                     
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }
     
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
    }

User Control Code:
public partial class ValueUC : System.Web.UI.UserControl
    {
        public ValueToUC parentWp
        {
            get;
            set;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            lblName.Text = parentWp.MyProperty;
        }
    }
As you observe I am using the WebPart class as a property which will help in getting the value to the User Control.

Thursday, July 21, 2011

Create a Application Page with code behind

We can create an application page using inline code but I think its more elegant to use code behind.
I am using WSPbuilder for the project.The solution structure
Some things to be taken care of in the aspx page are
  • Get Full Assembly name information
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Inherits="codeBehindPage.codeBehindPage,codeBehindPage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=afd867e29b3b4c59" %>

<asp:content  contentplaceholderid="PlaceHolderMain" runat="server">
<asp:button id="Button1" onclick="Button1_Click" runat="server" text="Button"/>
<br/>
<asp:GridView ID="gv" runat="server"/>
<asp:Content>

And now the code Behind for the button click event.
Important things to note
General Tendency is to get item from SharePoint List using the SPListItemCollection and bind to the GridView as it can understand the collections and display in tabular format which is where it gives the famous error irrespective of the collection containing results
Value does not fall within the expected range.   at Microsoft.SharePoint.SPFieldMap.GetColumnNumber(String strFieldName)
   at Microsoft.SharePoint.SPListItemCollection.GetRawValue(String fieldname, Int32 iIndex)
   at Microsoft.SharePoint.SPListItem.GetValue(SPField fld, Int32 columnNumber, Boolean bRaw)
   at Microsoft.SharePoint.SPListItem.GetValue(String strName, Boolean bThrowException)
   at Microsoft.SharePoint.SPListItem.get_Name()


So the best way to deal is as shown below

namespace codeBehindPage
{
    public partial class codeBehindPage : System.Web.UI.Page
    {      
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            SPWeb site = SPContext.Current.Web;
            SPList list = site.Lists["Customer Service Events"];
            SPQuery query = new SPQuery();
            query.Query = "";
            query.ViewFields = "";
                //""+
            SPListItemCollection itemcol = list.GetItems(query);

            gv.DataSource = list.GetItems(query).GetDataTable();
            //gv.DataSource = list.GetItems(query);
            gv.DataBind();
        }
    }
}

Friday, July 8, 2011

How to delete items from SharePoint List

Many of us might think whats new in deleting the item from Sharepoint List but there are some interesting facts to understand about this process.
You might come across this wierd error
  "Collection was modified; enumeration operation may not execute"
The error is same irrespective of  using a for or a foreach loop.
Let me Explain what happens in the background when delete using the follolwing code
                    SPList gallery = site.Lists["Your List"];
                    SPListItemCollection itemCol = gallery.Items;
                    foreach(SPListItem item in itemCol)
                    {
                        item.Delete();
                       gallery.update();                     
                    }                                   
Now whenever this code executes for each item deletion as the number of items gets deleted ,the second item gets the first index and that the reason for error.
You can also do the same like this
for (int i = 0; i < list.Items.Count; i++) {    
    list.Items.Delete(0);
}
This skips the items or randomly deletes the items in some scenarios.
So Best ways for deletion process:
Method 1 when deleting all items :
for (int i = list.Items.Count - 1; i >= 0; i--) {
    list.Items.Delete(i);
}
Method 2:IF a condition as to be met before deletion
So the best way of doing the deletion process is      
                    SPList gallery = site.Lists["YourList"];
                    SPListItemCollection itemCol = gallery.Items;
                    for (int i = itemCol.Count -1;i>=0; i--)
                 {
                        if (itemCol[i].Title.Equals("SomeName"))
                        {
                           itemCol[i].Delete();
                           gallery.Update();
                        }
                    }
              

Thursday, July 7, 2011

How to add List Template to SharePoint Site

So far we might came across adding WebParts,Pages,Page Layout,CSS you name it any SharePoint artifacts are deployed using the famous Feature.xml and Elements.xml.
Here is how you should define your Elements.xml
  <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Url="_catalogs/lt" Name="Summary Links.stp" Path="SummaryListTemplate">
        <File Url="Summary Links.stp" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE">
        <Property Name="Title" Value="StpTest" />
        <Property Name="Language" Value="1033" />
        <Property Name="FeatureID" Value="{00BFEA71-2062-426C-90BF-714C59600103}" />
        File>
    Module>
Elements>
In My Project I have kept the list template under Features/SummaryListTemplate hence the path in the elements.xml