Ads

Showing posts with label Web Part. Show all posts
Showing posts with label Web Part. Show all posts

Thursday, 14 July 2016

Add web part zone in master page to add webpart


In master page, there is a content place holder:  
<asp:ContentPlaceHolder id="PlaceHolderLeftActions " runat="server">
</asp:ContentPlaceHolder>


So if you place the SAME ID for my web part zone in the Page layout/Page, at run time, The Master Page's content on PlaceHolderLeftActions will be replaced by the content page

In simple steps:
1. Create a Blank .Aspx page with SPD
2. Just insert the code as per the below screenshot

<asp:ContentPlaceHolder id="PlaceHolderLeftActions " runat="server"></asp:ContentPlaceHolder>



Note:
Same way, If you want to insert a webpart in Master page, you can use the same Technique, insert your own Tag in Master page and replace the content in your content page by assigning same tag.
<asp:ContentPlaceHolder id="MyTag" runat="server"></asp:ContentPlaceHolder>



Monday, 30 June 2014

Creating a Classic Webpart - VS 2010

Overview
Classic webparts can be created by deriving from the WebPart class. You must write the code from scratch, in the CreateChildControls method, to create the layout design of the Web Part, which can be time consuming. One of the challenges that you face when designing a Web Part that has a complex user interface (UI) is the lack of drag-and-drop support.

Creating a Classic Webpart
Following are the steps for creating a Classic Webpart.

1) Open Visual Studio and select "New Project->SharePoint->2010". The following window will open displaying all SharePoint project templates. Select "Empty SharePoint Project", give a suitable name and click "Finish".

2) The following window pops-up. Enter the suitable Site collection name for debugging purpose. You also have the option to select Farm Solution or Sandboxed Solution.  

3) Right click on Solution and select Add->New Item. 
4) Another window with SharePoint templates will open as shown in the below figure. Select "Web Part".

 5) When a webpart is added 2 main components are added. First one is the webpart "MyClassicWP" which contains all the files supporting the webpart. Second one is "Features" contains the features for deploying the webpart to the site.
(Note: We will take a closer look into features in the upcoming posts.)
6) Now we will some custom code to display a welcome text along with date and time. Add the following code in the CreateChildControls() method.
SPWeb currentWeb = SPControl.GetContextWeb(HttpContext.Current);
String currentUserName = currentWeb.CurrentUser.LoginName;
this.Controls.Add(new LiteralControl(String.Format(
"<h1>Welcome {0}!</h1>", currentUserName)));
this.Controls.Add(new LiteralControl(String.Format(
"<div>Current DateTime: {0}</div>", DateTime.Now)));

7) Select "Build-> Deploy MyVisualWebPart" to deploy the webpart to the site collection that we entered in the "SharePoint Customization Wizard" in the 2nd step.
(Note: For deploying the wepart solution to another site collection or subsite we must use the STSADM command line tool or SharePoint Management Shell. We will discuss deployment in detail in the upcoming sessions.)

8) Now open the Webpart page in "Edit mode" and click "Add a Web Part". The webpart "MyClassicWP" is now available in the webpart gallery under "Custom" group. Select the webpart and click "Add".

9) Our webpart has been created and displays the Welcome message along with date and time.

This is just small example of creating a Classic Webpart. In the next post we will create a sample visual webpart.

Monday, 8 July 2013

Using People Picker control in edit web part Properties

How to use People Picker control in edit web part Properties?

First Create a "Empty SharePoint Project". Add New "Web Part" named "TestWebpart". Create a new webpart property in this, as shown below.

private string _ImpersonateUser = null;

[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(false)]
[System.ComponentModel.Category("Custom Properties")]
[WebDisplayName("Impersonate User")]
[WebDescription("User for impersonation")]
        public string ImpersonateUser
        {
            get
            {
                return _ImpersonateUser;
            }
            set
            {
                _ImpersonateUser = value;
            }
        }


Leave this as it is, we will come back to this again.


Add new class named "PeoplePickerEditor.cs" to this project. Your class should look like:

namespace SP.Anmol.Customization
{
    public class PeoplePickerEditor: EditorPart
    {
        private PeopleEditor _peoplePicker;

        public PeoplePickerEditor(string webPartID)
        {
            this.ID = "PeoplePickerEditor" + webPartID;
            this.Title = "Impersonate User";
        }


        protected override void CreateChildControls()
        {
            _peoplePicker = new PeopleEditor();
            _peoplePicker.ID = "pe1";
            _peoplePicker.AllowTypeIn = true;
            _peoplePicker.AllowEmpty = false;
            _peoplePicker.MultiSelect = false;
            _peoplePicker.Width = Unit.Pixel(250);
            _peoplePicker.SelectionSet = PeopleEditor.AccountType.User.ToString();

            Controls.Add(_peoplePicker);
        }


        public override bool ApplyChanges()
        {
            EnsureChildControls();
            TestWebpart.TestWebpart webPart = WebPartToEdit as TestWebpart.TestWebpart;
            if (webPart != null)
            {

                //set value of web part property
                webPart.ImpersonateUser = _peoplePicker.CommaSeparatedAccounts;
            }
            return true;
        }


        public override void SyncChanges()
        {
            EnsureChildControls();
            TestWebpart.TestWebpart webPart = WebPartToEdit as TestWebpart.TestWebpart;
            if (webPart != null)
            {

                //set value back to people picker control
                _peoplePicker.CommaSeparatedAccounts = webPart.ImpersonateUser;
            }
        }


    }
}

Now get back to web part code file. Implement the interface IWebEditable. Your web part code looks like:

namespace SP.Anmol.TestWebpart
{


    [Guid("84B6AF3B-9BA4-440A-AA4A-9657A5D67798")]
    public class TestWebpart : Microsoft.SharePoint.WebPartPages.WebPart, IWebEditable
    {
        public AnonymousUpload()
        {
            this.ExportMode = WebPartExportMode.All;
        }

      
        private string _ImpersonateUser = null;

      
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(false)]
        [System.ComponentModel.Category("Custom Properties")]
        [WebDisplayName("Impersonate User")]
        [WebDescription("User for impersonation")]
        public string ImpersonateUser
        {
            get
            {
                return _ImpersonateUser;
            }
            set
            {
                _ImpersonateUser = value;
            }
        }

      
        protected override void CreateChildControls()
        {
                 //Place your logic here
        }


 

        //Methods to be implement for interface IWebEditable        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();
            editors.Add(new PeoplePickerEditor(this.ID));

            return new EditorPartCollection(editors); 
        }

        object IWebEditable.WebBrowsableObject
        {
            get { return this; }
        }


    }
}

Wednesday, 15 May 2013

How to Deploy SharePoint WebParts

There are several ways to skin the Webparts deployment cat, each with a few pluses and minuses. 
Method 1 - manual
  • Copy assembly DLL to either
    - /bin directory for a given IIS virtual server (e.g., c:\inetpub\wwwroot\bin)
    - Global Assembly Cache (e.g., c:\windows\assembly)
  • Copy DWP file to C:\Inetpub\wwwroot\wpcatalog
  • Copy resources to
    - For GAC-registered parts, C:\Program Files\Common Files\Microsoft Shared\web server extensions\wpresources
    - For Web Parts in the /bin directory, C:\Inetpub\wwwroot\wpresources
  • Adjust web.config
    - Register as SafeControl
    - Select Code Access Security settings

Method 2: CAB File
  • CAB file should contain
    -Assembly DLL
    -DWP file(s)
    -Manifest.XML
    -Resource files (if needed)
  • CAB won't contain
    - Code Access Security settings
  • Server-side object model has methods for deploying such a CAB file
  • Deploy with STSADM.EXE
    Located in C:\Program Files\Common Files\Microsoft Shared\web server extensions\60\BIN
    Add it to your path
    Stsadm -o addwppack -filename filename [-globalinstall] [-force]

Method 3: MSI File via WPPackager
  • All of the features of CAB file deployment, but with
    - Code Access Security support
    - Ability to uninstall via Control Panel
  • Add additional files to project for use by WPPackager
  • Run WPPackager after project is built

Thursday, 4 April 2013

Understanding and working with the Web Part Verbs

Here we will discuss about understanding and working with webpart verbs. First question comes to the mind is what this web part verb actually is. Right, so here is the answer to this.
You have already seen Web part verb if you have worked with web parts. They appear when you press the down arrow button key available in every web part at right hand side corner. Each item in that menu is called verb. Look in to below image.



As you can also see in the image that we have created our own custom web part verb as well and added to the web part.

So let us start with explaining the method how we can achieve this functionality. First you need to know that there are two kinds of event you can bind it to a verb. Either it can be client side event or it can be server side event. As you can see in the image, to show you I have created two verbs and bound events respectively. You need to overrides WebPartVerbCollection. First you need to create your web part verb and then finally we will add them to the default web part verb collections for the web part.

Let us see it in action.
First web part verb will be handling the server side event and the other web part verb will be handling the client side event.

public override WebPartVerbCollection Verbs
{
get
{
List <webpartverb> objVerbs = new List <webpartverb>();

WebPartVerb verb = new WebPartVerb(this.ID, new WebPartEventHandler(ServerSideHandler));
verb.Text = "Click to execute server side code";
verb.Visible = true;
verb.Description = "This click will execute server side code";
objVerbs.Add(verb);

WebPartVerb verb1 = new WebPartVerb(this.ID + "newone","alert('hi you clicked me!!!');");
verb1.Text = "Click to execute client side code";
verb1.Visible = true;
verb1.Description = "This click will execute client side code";
objVerbs.Add(verb1);

WebPartVerbCollection allverbs = new WebPartVerbCollection(base.Verbs,objVerbs);

return allverbs;

}
}

As you can see, client side event, we have declared it in the constructor of webpart verb itself. There you can also write something like window.open or any other client side code that you want.

If we talk about the server side code, then it is handling one webpart event ahndler which is ServerSideHandler. To show you how it works, I have created a textbox in that event and added to the controls collection of web part. So by clicking on that verb, a new textbox will generated and added to the webpart.

public void ServerSideHandler(object sender, WebPartEventArgs e)
{
TextBox txtName = new TextBox();
txtName.TextMode = TextBoxMode.MultiLine;
txtName.ID = "txtname";
txtName.Text = "Hey you clicked server side code and see i got generated here";
this.Controls.Add(txtName);

}
Above are the steps that you need to implement. That will complete your functionality of achieving custom web part verb and adding them to your web part.

See the figure below when I click on client side verb, what happens!!




And see when I clicked on server side web part verb, what happenes!!





Wednesday, 3 April 2013

Hide Content Place Holder Programmatically

Lets assume the case where we want to replace a control from the master page by a custom web part. Initially we commented everything inside the content place holder and added my web part.

Later on i moved the web part reference out of the content place holder and made the visible attribute of the content place holder to false.

But now the requirement is to dynamically turn it ON and OFF (i.e through code)
Lets follow the steps given below to achieve this:

1. Go to the page_load method of the web part.
2. Write the following lines of code.

if (!Page.IsPostBack)
{
ContentPlaceHolder contPlcHolder = (ContentPlaceHolder)Page.Master.FindControl("PlaceHolderGlobalNavigation");
contPlcHolder.Visible = false;

//Rest of the code

}

If there is any nested content place holder then append that number of FindControl("ControlName") to the above code where we are finding the control.

Create webpart custom properties using visual studio


Steps Involved(Webpart and not Visual webpart):
These custom properties will be displayed in the property pane/tool pane view as different controls according to the type of the property.
bool -> Check box
enum  -> Dropdown list
int -> Text box
string -> Text box
DateTime -> Text box
Steps to follow:
  • Open Visual Studio 2010.
  • Create an "Empty SharePoint Project".
  • Right click on the solution and click on Add => New Item.
  • Select "Webpart" template from SharePoint 2010 installed templates.
  • Entire solution looks like the following


     
  • Replace CustomProperties.cs file with the following code.
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;
namespace CustomProperties.CustomPropertiesWP
{
    [ToolboxItemAttribute(false)]
    public class CustomPropertiesWP : WebPart    {
           
private string _Name;
        private string _cmd;
        private int _Width = 0;
        public enum ControlModes
        {
            Simple,
            Standard,
            Advanced
        }
          Label lblResult;
          Button btnClick;

 /*Just represnt a label */

       [WebBrowsable(true), WebDisplayName("Name"), WebDescription("Enter Name"),
       Personalizable(PersonalizationScope.Shared), Category("Custom Properties"),
       System.ComponentModel.DefaultValue("Please Enter")]
  /*This actually represents the Field  - Textbox(String)*/
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }

        }

                               //Another way of adding controls to Properties pane
       [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
        System.Web.UI.WebControls.WebParts.WebDisplayName("Enter Comment"),
        System.Web.UI.WebControls.WebParts.WebDescription("Comment"),
        System.Web.UI.WebControls.WebParts.Personalizable(
        System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
        System.ComponentModel.Category("Custom Properties"),
        System.ComponentModel.DefaultValue("")]
        public string Cmd
        {
            get { return _cmd; }
            set { _cmd = value; }
        }
                
        [Personalizable(PersonalizationScope.User),WebBrowsable(true),
       WebDisplayName("Set Width"),WebDescription("Set width"),Category("Custom Properties")]
 /*This actually represents the Field  - Textbox (Integer)*/
        public int setWidth
        {
            get{return _Width;} 
            set{_Width = value;}
        }
       
        protected override void CreateChildControls()
        {
            lblResult = new Label();
            btnClick = new Button();
            btnClick.Text = "Click";
            btnClick.Click += new EventHandler(btnClick_Click);
            this.Controls.Add(lblResult);
            this.Controls.Add(btnClick);
        }
        protected void btnClick_Click(object sender, EventArgs e)
        {
           
lblResult.Text = "Welcome" + " " + _Name.ToString() + "<br /> Your Valuable Comment: " + Cmd.ToString()+"<br/>You have set the width as :"+setWidth+"<br/><br/>";
            if(setWidth!=0)
            btnClick.Width = setWidth;
            else
            btnClick.Width = 500;
        }       
        }       
    }
}
  • Build and deploy the solution.

  • Go to the SharePoint Site =>Site Actions =>Edit Page =>Editing Tools => Insert =>Web Part =>Categories => Custom =>CustomPropertiesWP.

     
  • Click on Add.
  • The web part looks like the following with a button.

     
  • Edit the webpart you could see a new custom category in the webpart properties.
  • Enter the value and click on Ok.

     
  • In the CustomPropertiesWP click on the button.

Ads