Creating Visual Web Part Properties

Before reading this article I assume you already know how to create your own web parts in Sharepoint and is looking for some ways to create a property for that webpart that you can easily Set and Get from your application like this one on the image below.

but if not please read this post regarding Developing Web Parts first to avoid confusion.  But if you already know what to do then continue on.

First on your Web Part Class (yellow highlight) and not the User Control Class (green highlight) define your properties

For this example I will show you how to define a text, boolean, integer, date time and enummeration property

[ToolboxItemAttribute(false)]
public class Sample_Web_Part : WebPart
{
    // Visual Studio might automatically update this path when you change the Visual Web Part project item.
    private const string _ascxPath = @"~/_CONTROLTEMPLATES/Sample_Project/Sample Web Part/Sample Web PartUserControl.ascx";

    protected override void CreateChildControls()
    {
        Control control = Page.LoadControl(_ascxPath);
        Controls.Add(control);
    }

    public static Boolean SampleBoolean;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Boolean"),
    WebDescription("Please Choose a Sample Boolean")]
    public Boolean _SampleBoolean
    {
        get { return SampleBoolean; }
        set { SampleBoolean = value; }
    }

    public static string SampleText;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Text"),
    WebDescription("Please Enter a Sample Text")]
    public string _SampleText
    {
        get { return SampleText; }
        set
        {
            // Sample Validation
            Regex oRegEx = new Regex("[a-zA-Z]+");
            if (!oRegEx.IsMatch(value))
                throw new Microsoft.SharePoint.WebPartPages.WebPartPageUserException("Please enter alphabeth characters only");
            SampleText = value;
        }
    }

    public static int SampleNumber;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Number"),
    WebDescription("Please Enter a Sample Number")]
    public int _SampleNumber
    {
        get { return SampleNumber; }
        set { SampleNumber = value; }
    }

    public static DateTime SampleDate;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Date"),
    WebDescription("Please Enter a Sample Date")]
    public DateTime _SampleDate
    {
        get { return SampleDate; }
        set { SampleDate = value; }
    }

    public enum CityEnum { Manila, Berlin, Auckland, Zurich };
    public static CityEnum SampleDropDown;
    [Category("Extended Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable(true),
    WebDisplayName("Sample Drop Down"),
    WebDescription("Please Choose a Sample DropDown")]
    public CityEnum _SampleDropDown
    {
        get { return SampleDropDown; }
        set { SampleDropDown = value; }
    }
}

If you noticed each property you created have attributes and here is what it means

  • Category – This will group your property according to category, If not declared “Miscellaneous” will be used as a default.
  • Personalizable – How the web part is configured which can be per-user (PersonalizationScope.User) basis or for all everyone (PersonalizationScope.Shared). For this example, we have chosen all users.
  • WebBrowsable – This will hide or show the property on the tool pane.
  • WebDisplayName – Label for the property.
  • WebDescription – Description for the property.

You might also notice that we have validation on the codes.  You can add your own like the one on the SampleText property where we implemented a Regular Expression or even in SampleNumber it is by default validated by its type so you cannot save once it has an illegal values

So the final step is conusming that property in your WebPart, you can do it easily by doing like such.

Developing Web Parts for Sharepoint 2010

Developing Web Parts for Sharepoint have never been easier with Visual Studio 2010, by installing the Sharepoint 2010 SDK you will have templates ready for you in your Visual Studio 2010 environment.

But before you start you should have installed Sharepoint 2010 on your Development Workstation and if you are having some difficulties on how to achieve that here is a quick guide on how to install Sharepoint in a non server environment.

Now lets start!

1. Open Visual Studio 2010 as an Administrator then create a new Visual Web Part project, give it a name. In this sample we call it SampleWebPart.

If you did not run as an Administrator then it will prompt you to restart using a different credential

2. Specify the local Sharepoint Server, and note that you cannot use a Sharepoint instance outside your workstation.

3. All the necessary files have been created you can now start developing

You will be using VisualWebPart1UserControl.ascx.cs and VisualWebPart1UserControl.ascx, these are the controls that will be rendered on your Sharepoint instance.

4. Now start developing, if you are familiar with web development in Visual Studio it will be similar, you can drag and drop controls and add events to it.

For this sample we will put 2 controls, 1 button and 1 label. Then put an event on the button to change the text on Label1 to “Hello World!”

protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = "Hello World!";
}

5. Now build and run your project.

Now if you notice in the output screen you will also see that a package was created on your bin folder, this is what you will be using later to deploy on your server. You can also package your solution anytime by right clicking the project and choose package.

6. When the project is running your default browser will run opening your local Sharepoint instance, your control cannot be seen yet at this point and you have to add it you your page as a web part to do that, go to a page that you can edit and add your Sample Web Part, once added you can now test if the events are firing.

7. Once you stopped the project, it will deactivate, retract and delete the solution that was imported to the local Sharepoint instance so don’t try to find it on your local Sharepoint installation afterwards as you will not find it.

8. Now if all is working fine you are ready to deploy. Go to your bin folder and copy the package to your servers file system.

9. Once copied you can run powershell scripts to install your package to your Sharepoint Server. To do that go to SharePoint 2010 Management Shell

To Add the Solution in Sharepoint

Add-SPSolution C:\YourFolder\SampleWebPart.wsp

To Install the Solution to your Sharepoint

Install-SPSolution -identity SampleWebPart.wsp -WebApplication http://yoursharepointserver -GACDeployment

To Update your Solution in Sharepoint
you will need this if you want to update the Webpart that is already installed

Update-SPSolution –Identity SampleWebPart.wsp –LiteralPath C:\YourFolder\SampleWebPart.wsp –GACDeployment

Now if something went horribly wrong or you just want to uninstall it you have to run this two commands

To Uninstall a Solution in Sharepoint

Uninstall-SPSolution –Identity SampleWebPart.wsp –WebApplication http://yoursharepointserver

then

Remove a solution from Sharepoint

Remove-SPSolution –Identity SampleWebPart.wsp

10. At this point your webparts in now available for usage, all you have to do is to Import it into your Sharepoint Server gallery.

Go to Site settings (of the topmost site) then under Galleries you will see “Webparts” click on it.

Then import your new Web Part to the Gallery, click New Document

Then you will be presented with Web Parts available for import

Choose the webpart you just installed the click populate gallery, at this point your web part now is available on the Sharepoint Ribbon’s Editing Tool.

Developing Web Parts for MOSS is easy!

In this post I will show you how easy it is to develop webparts in MOSS (Sharepoint), If you know how to develop in .Net then it will be a breeze.  It will be as easy as 13 steps so here we go.

Step 1

Create a new Class Library Project and name it any way you want I named mine as MyWebPart

Class Library Project


Step 2

You now add a reference to System.Web as you are using the following namespaces

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

You can do that by right clicking on the project and choose add a reference, choose the .Net tab

Add Reference

Do you coding now.  Here is a sample code on how to render controls on the webpart

namespace MyWebPart
{
    public class NewWebPart : WebPart
    {
        protected override void CreateChildControls()
        {
            TextBox myTextBox = new TextBox();
            myTextBox.Text = "This is easy";
            Controls.Add(myTextBox);
        }
        public override void RenderControl(HtmlTextWriter writer)
        {
            RenderChildren(writer);
        }
    }
}

On this sample its just a simple rendering of a TextBox called myTextBox and assigning a value to the textbox.  Once done you are ready to publish the code to your MOSS


Step 3

Determine the bin folder of your MOSS site, you can find it in IIS. Usually its in C:\Inetpub\wwwroot\wss\VirtualDirectories\{your MOSS instance name}\bin

MOSS bin folder


Step 4

Once found, copy and put that in your output path in the build properties of your project, also choose All configurations on the Configuration Section, so when you debug it publishes on your MOSS bin folder (not a best practice but we just doing it for simplicity if this walkthrough)

Output Path build properties


Step 5

Build the project and you will now see the dll on the MOSS bin folder

MOSS Bin Folder


Step 6

Add a SafeControl Assembly on the web.config of your MOSS instance.  That would be one directory above the bin folder.

Safe Control Assembly


Step 7

Now that your webpart is on the server you need MOSS to import the library you created for you, you can do that by going to Site Settings and Modify Site Settings

Site Actions


Step 8

Now go to Galleries and choose Web Parts

Web Part Galleries


Step 9

Add the WebPart by clicking New

New Web Part


Step 10

Choose the webpart you just developed by ticking the checkbox beside it and click Populate Gallery

Populate Gallery


Step 11

Now your new webpart is available for use in any of you pages and it is now included in the library

New WebPart


Step 12

Now you can use it in any pages, if you add a new webpart it will be on the list

Web Part List


Step 13

Now you can use it. its that simple!’

Finshed Product

Follow

Get every new post delivered to your Inbox.

Join 773 other followers