Wednesday 28 September 2011

Adding Properties to Visual Web Parts and maintains its value while iisreset

Adding Properties to Visual Web Parts

Visual Studio 2010 introduces a new feature called “Visual Web Parts”, which allows a developer to create a web part by using a user control as a base. SharePoint 2007 developers will find this very familiar, as they’ll see that Visual Studio 2010 simply does what we had done in the past, which is to create a web part to host the user control. So a Visual Web Part is a user control inside a web part.
VisualWebPartStructure
Let’s walk through creating a Visual Web Part and allow user customization of it. We’ll start by adding a Visual Web Part to a SharePoint project. After you add the Visual Web Part to your SharePoint project, you’ll notice Visual Studio adds many items to support the new web part.
VisualWebPartParts
There are three main items in here of interest:
  • HelloVisualWebPart.cs -This is the actual web part. The class contained in this code file inherits from WebPart and overrides CreateChildControls.
  • HelloVisualWebPartUserControl.ascx - This is the user control that will make up the interface for the web part.
  • HelloVisualWebPartUserControl.ascx.cs - This is the code behind for the user control. This is where any event handlers and other code to add functionality to the web part will be placed.
If you view the code in the HelloVisualWebPart.cs file, you’ll notice it simply loads the user control and places it inside the web part. Again – a Visual Web Part is simply a user control hosted in a web part.
// Code from HelloVisualWebPart.cs private const string _ascxPath = @"<<really long string omitted>>";
protected override void CreateChildControls()
{
    Control control = Page.LoadControl(_ascxPath);
    Controls.Add(control);
}

When creating a web part, one of the most common requirements is to allow the end user to customize it. Typically this is done by adding properties to the web part and using those properties to customize the display. This is where things change for a Visual Web Part.
Remember there are two moving parts making the magic happen here – the web part class, which SharePoint will see, and the user control, which houses the UI. If we add the property to the web part class, the user control won’t be able to access it. If we add the property to the user control, SharePoint won’t see it.
The solution is to add the property to the web part, and to add an instance of the web part to the user control. By adding the property to the web part, SharePoint can then prompt the user for a value. By passing the web part into the user control, you can then access these properties.
The first step, adding the property to the web part, is done as normal for a web part property.
// Added to HelloVisualWebPart.cs
[WebBrowsable(true)]
[WebDisplayName("Message")]
[WebDescription("Message to display to users")]
[Personalizable(PersonalizationScope.User)]
[Category("Message Configuration")]
public string Message
{
    get; set;
}

The second step, passing the web part into the user control takes just a little more work. First, we need somewhere to store the web part. We’ll accomplish this by adding a property to the user control of the web part type.
// Added to HelloVisualWebPartUserControl.ascx.cs
public HelloVisualWebPart
ParentWebPart
{
    get; set;
}

Then we need to change the code in the web part that’s adding the user control. The problem is it’s adding a normal user control, and not our specific user control. We need our specific user control as that’s the one with the property. We also then need to pass the web part into the user control.
// Modified in HelloVisualWebPart.cs
protected override void
CreateChildControls()
{
    HelloVisualWebPartUserControl control =
         (HelloVisualWebPartUserControl) Page.LoadControl(_ascxPath);

    control.ParentWebPart = this;
    Controls.Add(control);
}

Finally, we can now access the properties from the web part in the user control. In my little example, I’m just going to add that in as a label.
<%—Added to HelloVisualWebPartUserControl—%>
<asp:Label runat=”server” ID=”lblMessage” />

//Added to HelloVisualWebPartUserControl.ascx.cs protected void Page_Load(object sender, EventArgs e) {
    lblMessage.Text = ParentWebPart.Message;
}

After deploying the web part and adding it to a page, we then get the normal interface in SharePoint.
VisualWebPartFinal
So when we create a Visual Web Part we actually get two moving parts – the web part and a user control. If we want to add properties to the Visual Web Part, we need to add the property to the web part, and then pass an instance of the web part into the user control so the user control can access the values.

Webpart Properties

Visual Studio 2010 has a new template allowing you to create Visual Web Parts. One advantage of Visual Web Part as opposed to a regular web part is the ability to add user controls and markup of the web part right in the visual mode without having to provision it in your code-behind file.
If you developed web parts before, you know that hardly ever your web part will not need to accept properties. Usually the whole purpose of creating one is to allow your users or administrators to customize the properties.
When you create a new Visual WebPart (say call it SampleWP), among other files you will see the following key files:
1. SampleWP.CS
2. SampleWPUserControl.ascx
3. SampleWPUserControl.ascx.cs
In traditional web part you would define your properties in the file that inherits from WebPart class. In our case it’s SampleWP.CS. However, your entire logic is happening in your user control code behind file and therefore you need to reference web part properties in there.
Here is how to define properties that will be used in your code user control behind file.
1. In your SampleWP.CS set the following value of class identifier [ToolboxItemAttribute(true)]
2. In your class define the property that will be displayed to a user:
[WebBrowsable(true),
Category("Configuration"),
Personalizable(PersonalizationScope.Shared),
DefaultValue(""),
WebDisplayName("Property Title"),
WebDescription("Property Description")]
public string MyProperty
{
get { return myprop; }
set { myprop = value; }
}
public static string myprop;
Above, the ‘myprop’ static variable is the variable that will be referenced in your user control code behind class. like this:
someLabelOnForm.Text = SampleWP.myprop;
As you can see we can assign the value of our property from SampleWP.CS that will be collected from a user to be used in our user control.

Tuesday 6 September 2011

Lists: Retriveing datas from lists

 protected override void CreateChildControls()
        {
            if (!_error)
            {
              
                SPWeb web = SPContext.Current.Site.OpenWeb();
           
                try
                {
                    base.CreateChildControls();
                    // Your code here...
             
       
                    SPList li = web.Lists["123"];
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>aaa</Value></Eq></Where>";
                    SPListItemCollection collist = li.GetItems(query);
                    foreach (SPListItem i in collist)
                    {
                        Label l = new Label();
                        l.ID = i.ID.ToString();
                        l.Text = i.Title.ToString();
                       
                        this.Controls.Add(l);
                    }
                   
                }

                catch (Exception ex)
                {
                    HandleException(ex);
                }
                finally
                {
                    web.Dispose();
                }
            }
        }


Creating Lists Programatically:

 public void createList()
        {
            // choose your site
            SPSite site = new SPSite("http://merdev-moss:5050");
            SPWeb web = site.OpenWeb();
            SPListCollection lists = web.Lists;

            // create new Generic list called "My List"
            lists.Add("My List", "My list Description", SPListTemplateType.GenericList);

            SPList list = web.Lists["My List"];

            // create Text type new column called "My Column"
            list.Fields.Add("My Column", SPFieldType.Text, true);

            // make new column visible in default view
            SPView view = list.DefaultView;
            view.ViewFields.Add("My Column");
            view.Update();
        }



Creating and retrieving listsin c# webpart

 protected override void CreateChildControls()
        {
            if (!_error)
            {
              
                SPWeb web = SPContext.Current.Site.OpenWeb();
           
                try
                {
                  
                    base.CreateChildControls();
                     web.AllowUnsafeUpdates = true;
                    // creating list
                    SPListCollection newlist = web.Lists;
                    newlist.Add("2", "asd", SPListTemplateType.GenericList);
                    SPList li = web.Lists["2"];
                    li.Fields.Add("Title", SPFieldType.Text,true);
                    SPListItemCollection listitemcol= web.Lists["2"].Items;
                    SPListItem item = listitemcol.Add();
                    item["Title"] = "aa9a";
                  
                    item.Update();
                    web.AllowUnsafeUpdates = false;
                   // retrieving datas from list
                 //   SPQuery query = new SPQuery();
                //    query.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>";
                //    SPListItemCollection collist = li.GetItems(query);
                    SPListItemCollection collist = li.Items;
                    foreach (SPListItem i in collist)
                    {
                        Label l = new Label();
                        l.ID = i.ID.ToString();
                        l.Text = i.Title.ToString();                    
                        this.Controls.Add(l);
                    }
                   
                }

                catch (Exception ex)
                {
                    HandleException(ex);
                }
                finally
                {
                    web.Dispose();
                }
            }
        }

Ajax tool kid in sharepoint

http://weblogs.asp.net/jan/archive/2007/02/26/using-the-ajax-control-toolkit-in-sharepoint.aspx


Actually SharePoint doesn't differ from any other ASP.NET web site to use the Control Toolit, there are only three things that you need to do:

Make sure SharePoint has access to AjaxControlToolkit.dll
You can do this in two ways: either you deploy the assembly to the Global Assembly Cache (GAC) or you put in the \BIN folder of the SharePoint site's folder.
Add an assembly reference in the web.config (note: for the future versions of the Control Tookit, the version number can change!):
<assemblies>
    ...
    <add assembly="AjaxControlToolkit, Version=1.0.10201.0, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
    ....
</assemblies>
Add the tagprefix for the Control Toolkit in the web.config:
<controls>
    ...
    <add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit"/>
    ....
</controls>