Monday, April 30, 2012

Web Parts

WebPart Life Cycle
OnInit: This method handles initialization of the control.
OnLoad: This event handles the Load event. This is also used for initialize the control but is not intended for loading data or other processing functionality.
CreateChildControls: This is the most popular event in web part life cycle. This creates any child controls. So if you are adding any control to display then you have to write in this method.
EnsureChildControls: This method ensures that CreateChildControls has executed. EnsureChildControls method must be called to prevent null reference exceptions.
SaveViewState: View state of the web part saved.
OnPreRender: This method handles or initiates tasks such as data loading that must complete before the control can render.
Page.PreRenderComplete: The page fires the PreRenderComplete event after all controls have completed their OnPreRender methods.
Render: This method is used to render everything.
RenderContents: Renders the contents of the control only, inside of the outer tags and style properties.
OnUnload: Performs the final cleanup.

Visual Web Part Limitations

Starting in Visual Studio, you can add visual web parts to sandboxed SharePoint solutions and farm solutions. However, visual web parts have the following limitations:
  • Visual web parts don't support replaceable parameters. For more information, see Replaceable Parameters.
  • User controls or visual web parts can't be dragged and dropped or copied onto visual web parts. This action causes a build error.
  • Visual web parts don't directly support SharePoint server tokens such as $SPUrl. For more information, see "Token Restrictions in Sandboxed Visual Web Parts" in the topic Troubleshooting SharePoint Solutions.
  • Visual web parts in a sandboxed solution occasionally get the error, "The sandboxed code execution request was refused because the Sandboxed Code Host Service was too busy to handle the request." For more information about this error, see this post in the SharePoint Developer Team Blog.
  • Server-side JavaScript debugging isn't supported in Visual Studio, but client-side JavaScript debugging is supported.
    Although you can add inline JavaScript to a server-side markup file, debugging isn't supported for breakpoints added to the markup. To debug JavaScript, reference an external JavaScript file in the markup file, and then set the breakpoints in the JavaScript file.
  • Debugging of inline ASP.NET code must be done in the generated code file instead of in the markup file.
  • Visual web parts don't support the use of the <@ Assembly Src= directive.
  • SharePoint web controls and some ASP.NET controls aren't supported in the SharePoint sandboxed environment. If unsupported controls are used on a visual web part in a sandboxed solution, the error, "The type or namespace name 'Theme' does not exist in the namespace 'Microsoft.SharePoint.WebControls'" appears.
 
 
Good Example:
 
 
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;

namespace SharepointTraingSolution.BasicWebPart
{
    [ToolboxItemAttribute(false)]
    public class BasicWebPart : WebPart
    {
        private DataGrid grid;
        private static string verbText = "Show Managers Only";
        private Label errorMessage = new Label();
        protected string xmlFilePath;

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
         WebDisplayName("Path to Employee Data File"),
         WebDescription("Location of the XML file that contains employee data")]
        public string DataFilePath
        {
            get
            {
                return xmlFilePath;
            }
            set
            {
                xmlFilePath = value;
            }
        }
        public override WebPartVerbCollection Verbs
        {
            get
            {
                WebPartVerb customVerb = new WebPartVerb("Manager_Filter_Verb",
                    new WebPartEventHandler(CustomVerbEventHandler));
                customVerb.Text = verbText;
                customVerb.Description = "Shows only employees that are managers";
                WebPartVerb[] newVerbs = new WebPartVerb[] { customVerb };
                return new WebPartVerbCollection(base.Verbs, newVerbs);
            }
        }
        protected void CustomVerbEventHandler(object sender, WebPartEventArgs args)
        {
            int titleColumn = 2;
            foreach (DataGridItem item in grid.Items)
            {
                if (item.Cells[titleColumn].Text != "Manager")
                {
                    if (item.Visible == true)
                    {
                        item.Visible = false;
                    }
                    else
                    {
                        item.Visible = true;
                    }
                }
            }
            if (verbText == "Show Managers Only")
            {
                verbText = "Show All Employees";
            }
            else
            {
                verbText = "Show Managers Only";
            }
        }
       
        protected override void CreateChildControls()
        {
            // Define the grid control that displays employee data in the Web Part.
            grid = new DataGrid();
            grid.Width = Unit.Percentage(100);
            grid.GridLines = GridLines.Horizontal;
            grid.HeaderStyle.CssClass = "ms-vh2";
            grid.CellPadding = 2;
            grid.BorderWidth = Unit.Pixel(5);
            grid.HeaderStyle.Font.Bold = true;
            grid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            // Populate the grid control with data in the employee data file.
            try
            {
                DataSet dataset = new DataSet();
                dataset.ReadXml(xmlFilePath, XmlReadMode.InferSchema);
                grid.DataSource = dataset;
                grid.DataBind();
            }
            catch (Exception x)
            {
                errorMessage.Text += x.Message;
            }
            // Add control to the controls collection of the Web Part.
            Controls.Add(grid);
            Controls.Add(errorMessage);
            base.CreateChildControls();
        }
      
       
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            writer.Write("<HTML><HEAD><BODY><TABLE BORDER=1><TR><TD>RAJ SHARMA</TD></TR><TD>RAJ SHARMA</TD></TR><TD>RAJ SHARMA</TD></TR></TABLE></BODY></HEAD></HTML>");
        }
    }
}
 
<?xml version="1.0" encoding="utf-8" ?>
    <employees xmlns="http://schemas.microsoft.com/vsto/samples">
       <employee>
           <name>David Hamilton</name>
           <hireDate>2001-05-11</hireDate>
           <title>Sales Associate</title>
       </employee>
       <employee>
           <name>Karina Leal</name>
           <hireDate>1999-04-01</hireDate>
           <title>Manager</title>
       </employee>
       <employee>
           <name>Nancy Davolio</name>
           <hireDate>1992-05-01</hireDate>
           <title>Sales Associate</title>
       </employee>
       <employee>
           <name>Steven Buchanan</name>
           <hireDate>1955-03-04</hireDate>
           <title>Manager</title>
       </employee>
       <employee>
           <name>Suyama Michael</name>
           <hireDate>1963-07-02</hireDate>
           <title>Sales Associate</title>
       </employee>
    </employees>


Understanding SharePoint Delegate Control

8 December, 2010 (15:25) | SharePoint 2010 - Object Model | By: G Vijai Kumar
In this article I’m going to explain about delegate control, before we jump start into the technical talk we will understand first what is the meaning of Delegates
As I believe most of us we know that in general delegates are also called as ambassadors, diplomats, representatives etc.
A delegate having high ranks has most importance for example ranks like 1, 2, 3. Rank1 delegate officer has most significant role than rank2 delegate officer.
There can be so many delegate officers or ambassadors serving for Country X for example: A delegate officer may look after the relations between Country X and Country A, another delegate ambassador may look after the relations between Country X and Country B, even some times the delegate officers have to visit to the Country A or Country B depending upon the call.
Now we will speak real technical vocabulary of delegates, SharePoint has a couple of delegate controls like
AdditionalPageHead
GlobalSiteLink0
GlobalSiteLink1
GlobalSiteLink2
PublishingConsole
QuickLaunchDataSource
SmallSearchInputBox
TopNavigationDataSource
Apart from the above controls, we can also create our own custom delegate controls
The XML schema for delegate control is below:
1
2
3
<?xml version="1.0" encoding="utf-8" ?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
 <Control Id="SmallSearchInputBox" Sequence="100" Url="/templates/mysearchcontrol.ascx"/>
</Elements>
In the above schema you can view the properties for the delegate control as Control Id, Sequence and URL. We identify the delegate controls based on Control Id, Sequence number. The Sequence number defines the rank of the delegate, URL describes the source location of the control.
As we discussed already above that “Delegates having high ranks has most importance” in the same way delegate control who’s Sequence id is less has most significant role in SharePoint site and will render on the site as first preference.
Also we have discussed that “some times the delegate officers have to visit to the Country A or Country B depending upon the call” in the same way if we have custom delegate control deployed on site and activated, the least Sequence control will load on site depending upon the user action.
What is the use of delegate control?
Using the delegate control a developer can customize the SharePoint site controls without editing or even touching the master page.
Note: We are not customizing the existing (default) delegate control but we are creating our own control loading onto the SharePoint site.
Let’s suppose assume one scenario, if we want to customize the SharePoint search box (by default SharePoint 2010 site has got input search box with one textbox and one button beside) see figure 1
Figure 1 - SharePoint 2010 Default Search Box
Figure 1 - SharePoint 2010 Default Search Box
Now I will try to customize the default search box, the requirement is to display the search box with scope drop down list, and also customizing the search button image with a arrow image button.
First open Visual Studio 2010 and click New > Project see figure 2
Figure 2 - Creating New Visual Studio 2010 Project
Figure 2 - Creating New Visual Studio 2010 Project
After project got created, I have deleted the not in use file (you can keep it there won’t be any problem if you don’t delete) because of maintaing clean solution I have removed user control, webpart related files see figure 3
Figure 3 - Solution Explorer File Structure
Figure 3 - Solution Explorer File Structure
Then add the following code in Elements.xml file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
  <!--<Module Name="VisualWebPart1" List="113" Url="_catalogs/wp">
    <File Path="VisualWebPart1\VisualWebPart1.webpart" Url="CustomDelegateControl_VisualWebPart1.webpart" Type="GhostableInLibrary" >
      <Property Name="Group" Value="Custom" />
    </File>
  </Module>-->
  <Control
     Id="SmallSearchInputBox"
     Sequence="23"
     ControlClass="Microsoft.SharePoint.Portal.WebControls.SearchBoxEx"
     ControlAssembly="Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">
    <Property Name="QueryPromptString">This control is customized.....</Property>
    <Property Name="SearchBoxTableClass">search-box</Property>
    <Property Name="GoImageUrl">/_layouts/images/goviewfiles.png</Property>
    <Property Name="GoImageUrlRTL">/_layouts/images/goviewfiles.png</Property>
    <Property Name="GoImageActiveUrl">/_layouts/images/goviewfiles.png</Property>
    <Property Name="GoImageActiveUrlRTL">/_layouts/images/goviewfiles.png</Property>
    <Property Name="UseSiteDefaults">true</Property>
    <Property Name="FrameType">None</Property>
  </Control>
</Elements>
In the Element.xml file I have commented the Module section see figure 4
Figure 4 - Custom Delegate Control Element.xml file
Figure 4 - Custom Delegate Control Element.xml file
Now we are almost done, try to build, deploy and activate the feature which will result in change of SharePoint default search box with your customized control on fly without modifying the master page see figure 5
Figure 5 - SharePoint 2010 Custom Search Input Box
Figure 5 - SharePoint 2010 Custom Search Input Box
At run time, this control accepts the union of control elements declared at the server farm, Web application, site collection, and Web site levels. The control that has the lowest sequence number is added to the control tree by means of the DelegateControl. In the case of a sequence tie, the order of controls is arbitrary.
The sequence number of the DelegateControl can be used to integrate a portal search control in SharePoint Foundation. The default search control has a sequence number of 100, and a portal search, for example, could be activated at the site collection level with a sequence number of 50. In this way, SharePoint Foundation replaces the default search control with the portal search control in all places where the search control is invoked.

A delegate control is not inherently designable because it is ignorant of the actual control that gets instantiated inside it. The best it can do is render the design-time HTML of the chosen control for the particular instance. At best, the designer provides an option to "hardcode" the control, meaning replace the SharePoint:DelegateControl with the current control that is being returned via the Features infrastructure. The developer can then customize the control.

How to: Customize a Delegate Control

This example shows the basic process of creating and implementing a delegate control. The delegate control resides in the AdditionalPageHead control on the page. It registers some ECMAScript (JavaScript, JScript) on the page.

To build the delegate control

  1. Start SharePoint development tools in Microsoft Visual Studio 2010.
  2. On the File menu, point to New, and then click Project.
  3. In Project Types, under Visual Basic or C#, select Empty SharePoint Project.
  4. Type EcmaScriptDelegate as the project name. Click OK.
  5. In the SharePoint Customization Wizard, choose Deploy as a farm solution. Click Finish.
  6. In the Solution Explorer, right-click the EcmaScriptDelegate project. Select Add and then New Item.
  7. In the Add New Item dialog box, click the Code group and choose the Class template. Type EcmaScriptDelegateControl as the Name and then click Add.
  8. Next, you must add a reference to System.Web. In the Solution Explorer, right-click the References folder and select Add Reference. In the Add Reference dialog, click the .NET tab and find System.Web in the list. Click OK.
  9. In the EcmaScriptDelegateControl file that is displayed, add the following using statement.
    using System.Web.UI.WebControls;
    
  10. Change the base class of EcmaScriptDelegateControl to WebControl by modifying the following line.
    class EcmaScriptDelegateControl : WebControl
    
  11. Override the OnLoad method by adding the following code.
    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);
    }
    
    
  12. Inside the OnLoad method, add the following code to put JavaScript on the page.
      string helloAlert = "alert('Hello, world!');";
      this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "popup", helloAlert, true);
    
    
Now, you have built the delegate control for the project. Next, you will create the Feature to deploy the control.

To create a Feature to deploy the control

  1. In the Solution Explorer, right-click the EcmaScriptDelegate project and select Add and then New Item.
  2. In the Add New Item dialog box, choose the Empty Element template and type EcmaScriptDelegateFeature as the Name. Click Add.
  3. Insert the following XML inside the Elements element. The Id attribute identifies the delegate where the control is rendered. The ControlAssembly and ControlClass attributes are unique to your control. For more information about how to find the full assembly name, see How to: Create a Tool to Get the Full Name of an Assembly.
    <Control Id="AdditionalPageHead" ControlAssembly="EcmaScriptDelegate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=public key token" ControlClass="EcmaScriptDelegate.EcmaScriptDelegateControl">
    
    
You now have both the control and the Feature you need to deploy the control. Controls require a SafeControl entry in the web.config file in order to run on the page. The following procedure adds a SafeControl entry for your control.

To add a SafeControl entry

  1. In the Solution Explorer, click EcmaScriptDelegateFeature and click ... in the Safe Control Entries property.
  2. Click Add in the Safe Control Entries dialog.
  3. In the Properties box, ensure that the Namespace property is the correct value. This is the namespace of your control. Also, ensure that the Safe property is set to true. Click OK.
Now that the SafeControl entry is added, you can deploy the solution.

To deploy and test the delegate control

  1. Press F5 to run the solution.
  2. When the page loads, a dialog box appears that says Hello, world!. This is the script that the delegate control has added to the page.

 

Web Parts in SharePoint Foundation

Web Parts are server-side controls that run inside the context of site pages in Microsoft SharePoint Foundation. There are many Web Parts available by default, and you can also build your own custom Web Parts in SharePoint Foundation. They are editable and configurable by users. Web Parts let users add functionality to a site page by simply putting them on the page. SharePoint Foundation includes many default Web Parts. In addition, you can build your own Web Parts.

Types of webparts


There are two types of webparts available the first is Asp.net webparts and other is sharepoint web. the Asp.net inherited from system.web.UI.webcontrols.webparts and sharepoint webpart inherited from system.sharepoint.webparts.webpart. it uses Microsoft.SharePoint.dll and ASP.net uses System.Web.dll.

Asp.net webparts can be used to both enviroment .net as well as sharepoint. while sharepoint webparts can be used in sharepoint enviroment.

Custom Web parts

The term customization implies that changes are seen by all site members. Individual users can further personalize Web Parts page by adding, reconfiguring, and removing Web Parts. The term personalization implies that these changes are seen only by the user who made them. A site owner or a site member who has the appropriate permissions can customize Web Parts page by using a browser or by using Microsoft SharePoint Designer to add, reconfigure, or remove a Web Part.

Custom web parts used to provided the following facitlities..


Connectable Web Parts

Connectable web parts is the special type of webparts which provides the connection between two or more web parts, connectable web parts exchange the information to each other, there are some kind of prents child relationship. they provides the interface to consume and consumer interface to exchange the information.

Adding a web part property
after adding hte web part add a new property which is used to personalize the web part to the indiviudual user. It apears in the tools to edi


  • Create custom properties that you can display and modify in the user interface.
  • Improve performance and scalability. A compiled custom Web Part runs faster than a script.
  • Implement proprietary code without disclosing the source code.
  • Secure and control access to content within the Web Part. Built-in Web Parts enable any users who have the appropriate permissions to change content and alter Web Part functionality. With a custom Web Part, you can determine the content or properties to display to users, regardless of their permissions.
  • Make your Web Part connectable, allowing Web Parts to provide or access data from other connectable Web Parts.
  • Interact with object models that are exposed in SharePoint Foundation. For example, you can create a custom Web Part to save documents to a SharePoint Foundation document library.
  • Control the Web Part cache by using built-in cache tools. For example, you can use these tools to specify when to read, write, or invalidate the Web Part cache.
  • Benefit from a rich development environment with debugging features that are provided by tools such as Microsoft Visual Studio 2010.
  • Create a base class for other Web Parts to extend. For example, to create a collection of Web Parts that have similar features and functionality, create a custom base class from which multiple Web Parts can inherit. This reduces the overall cost of developing and testing subsequent Web Parts.
  • Control Web Part implementation. For example, you can write a custom server-side Web Part that connects to a back-end database, or you can create a Web Part that is compatible with a broader range of Web browsers.

Web Parts

1. To render web part Basically.. you pass the parmater in the override render method(System.web.ui.htmltextwriter writer)
then writer.write--used to render any static text
writer.renderbegintag--used to render < 
writer.renderendtag--used to render >
writer.write("<td><tr>") you can render whole html as well..

2. To render any control in your web part you basically override a create child method
    declare button
 Button btnAdd
btnAdd= new Button()
add properties on btnAdd if you want
this.controls.Add(btnAdd)--- to add button control in your form

To add event handler on the button
btnAdd.Click += new eventhandler(btnAdd_Click);

method would be genrated like this private void btnAdd_Click(object sender,eventargs e)

3. If you want manually rendering of your controls the override void render method and inside do the below code
this.EnsureChildControls();
btnAdd.RenderControls(writer);
do the br or whatever you want

4. Adding a new property and get that value into your code on web part.
[WebBrowsable(true),Category("Miscellaneous"),Personalizable(PersonalizationScope.Shared),WebDisplayName("Enter some text")]
public string CustomTextProp{get;set;}
 on the prerender
lbl_MySelection.Text = this.webpat.CustomTextProp.ToString();

5. Customize the content by query webpart
add a publishing dll in your reference
add using microsoft.Sharepoint.Publishing.Webcontrols
and inherit the class
public class ExtendCustomQueryWebPart : ContentByQueryWebPart

6. Loading User control :
create variable of control type and on the createdchildcontrols method write the below code
base.createchildcontrols();
this.controls.clear()
control = this.page.loadControl(@"/_controltemplates/usercontrol/simplecontrol.ascx");
this.controls.add(control);



Web Part Life Cycle
the life-cycle of a webpart is like this:
- OnInit
- OnLoad
- Applies personalization
- Web Part connections
- CreateChildControls
- OnPreRender
- SaveViewState
- Render

if it's a postback this is  the sequence, a bit different
- OnInit
- LoadViewState
- CreateChildControls
- OnLoad
- Applies personalization
- Postback events
- Web Part connections
- OnPreRender
- SaveViewState
- Render

1 comment:

  1. Những câu nói hay nhất về tình yêu và cuộc sống trên facebookBạn là một ngừoi lạc quan, vui vẽ, bạn yêu cuộc sống hiện tại. Tâm hồn bạn rất lãng mạng và bay bỏng, bạn đa cãm, bạn muốn chia sẽ thật nhiều những lời hay ý đẹp đến mọi người.
    Những câu stt buồn hay - độc nói về tình yêu và cuộc sốngMọi chuyện buồn cũng sẽ qua thôi vì có anh ở đây rồi
    Tư thế quan hệ vợ chồng 69 là gì?Trong cuộc sống vợ chồng, bạn cần có phương pháp để giữ lữa tình yêu, làm thế nào mà vợ chồng giống như lúc mới yêu. Lúc nào cũng yêu thương và luôn nghĩ về nhau.
    Nằm mơ thấy tai nạn giao thông là điềm báo gì?Trong những giấc mơ hàng ngày, chắc rằng bạn đã từng một lần nằm mơ thấy tai nạn giao thông.
    Những hình ảnh quan hệ tình dục nóng cận cảnhChuyện giới tính luôn là một vấn đề khiến cả hai giới tò mò thích thú. Bản năng tình dục của con người dường như là nhu cầu tất yếu, là một vấn đề hết sức bình thường
    Cây cỏ mực có công dụng chữa trị bệnh gì?Hầu hết mọi ngừoi dân việt nam từ xưa đến nay đều có niềm tin vào cây thuốc nam. Cách sử dụng rất đơn giản, dể làm nếu như bạn nắm được công dụng của chúng.
    Cách nhận biết phụ nữ mới vừa quan hệ tình dục xongBạn cảm thấy tò mò, thắc mắc mỗi khi gặp những ngừoi phụ nữ xung quanh mình. Rằng cô ấy đã từng quan hệ tình dục hay chưa?
    Cách nhận biết dấu hiệu khi phụ nữ lên đỉnhCó rất nhiều chàng trai khi quan hệ với ngừoi phụ nữ của mình nhưng không biết được khi nào họ lên đỉnh. Mình chiến như vậy liệu có được hay chưa, có làm nàng thoã mản hay chưa
    Dắm táo mật ong có tác dụng làm đẹp là gì?Đôi khi bạn có thể lo lắng về việc sử dụng các loại kem dưỡng da trên thị trường, tuy nhiên nếu sử dụng dấm táo thì có thể bạn sẽ không còn phải bận tâm nhiều nữa
    Làm sao để đẹp trai như tài tử hàn quốcAi xin ra trên đời này đều muốn mình có thể đẹp trai, đẹp gái, là một trong những trai xinh gái đẹp được nhiều ngừoi yêu thích
    Thuốc 7 màu có tác dụng trị gì - bán ở đâu?Một loại thuốc mà đi đâu cũng không thể thiếu là thuốc 7 màu, bạn bị nấm, bị ngứa, hay bị dị ứng thì thuốc 7 màu đều có công dụng chữa trị được hết

    ReplyDelete