Sunday, 14 October 2012

create webpart custom properties in SharePoint 2010


Steps Involved(Webpart and not Visual webpart):

These custom properties will be displayed in the property pane 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


  • 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.

Managing SharePoint Designer 2010


SharePoint Designer 2010 is a powerful application used to build custom sites and solutions on the SharePoint platform. It’s a great way to create and customize pages, views, forms, data sources, workflows, and more.
But there are some tasks in SharePoint Designer that give SharePoint administrators real heartburn because of the potential problems it creates for them.
Here are the big 3:
  1. Detaching pages from their site definition – When you do this, intentionally or not, the page overrides the site definition and therefore won’t be recognized the next time the site definition is updated. This means you’ll be talking to your SharePoint administrator the next time the server is upgraded.
  2. Customize master pages and page layouts – While this may improve the look and feel of your site, there’s a risk that you’ll remove the corporate brand that was intended for all sites in your organization. Even worse, you could potentially break your site and other sites if you change or delete a required content region.
  3. Editing files directly in the site URL structure – This might be a quick and easy way to modify any file on your site, but in doing so, you could mistakenly delete a support file or template file required by SharePoint.
So on one hand, SharePoint Designer 2010 gives you a lot of power and flexibility in how you change the appearance or functionality of a SharePoint site. But on the other, if it’s used incorrectly, it can create issues for you, your site, and of course, your administrator.

The SharePoint Designer Settings page
In SharePoint 2010, you and your administrator will be happy to learn about the SharePoint Designer Settings page, which looks like this.


The SharePoint Designer Settings page helps you manage how SharePoint Designer 2010 is used in your organization by giving you control of these settings:
  1. Enable SharePoint Designer: Enables or disables SharePoint Designer for an entire application or site collection. When checked, SharePoint Designer can open and edit SharePoint sites. When unchecked, it cannot be used to open or edit sites.
  2. Enable Detaching Pages from the Site Definition: Enables or disables the ability to detach pages from the site definition. When checked, SharePoint Designer allows users to edit pages in Advanced Mode, giving them access to every part of the page and consequently when they save, the page is detached from its site definition. When unchecked, SharePoint Designer disables the Advanced Mode, forcing users to edit only the parts of the page in a Web Part Zone. The page, as a result, is never detached from the site definition.
  3. Enable Customizing Master Pages and Layout Pages – Enables or disables master pages and page layouts in SharePoint Designer. When checked, SharePoint Designer displays master pages and page layouts in the Navigation pane. When unchecked, these pages don’t appear in the Navigation pane of SharePoint Designer.
  4. Enable Managing of the Web Site URL Structure – Enables or disables the site URL structure and its contents. When checked, SharePoint Designer displays the All Files options in the Navigation pane allowing users to view and edit any file on the site. When unchecked, the All Files option doesn’t appear in the Navigation pane.
In Central Admin and Site Collection Admin
There are not one but two SharePoint Designer Settings pages that you can use to manage how SharePoint Designer 2010 is used in your organization:
  • Central Administration – The SharePoint Designer Settings page in Central Administration applies the settings at the web application-level for all site collection administrators on down. That’d be everyone.
  • Site Collection Administration – The SharePoint Designer Settings page in Site Collection Administration (you know, the Site Settings page for your top-level site) applies the settings at the site collection level to all designers and owners.
Use one or both pages to manage how SharePoint Designer 2010 is used in your organization without fear of it detaching pages, removing corporate brands, or breaking sites. You may even choose to temporarily enable and disable certain SharePoint Designer features depending on where you’re at with your SharePoint deployment.

Friday, 12 October 2012

Deploying WSP using Powershell


What is a Solution Package?

A solution is a deployable, reusable package that can contain a set of Features, site definitions, and assemblies that apply to sites, and that you can enable or disable individually. You can use the solution file to deploy the contents of a Web Part package, including assemblies, class resources, .dwp files, and other package components. A solution file has a .wsp file extension.
How to add the solution to the sharepoint farm and then deploy it to a particular web application is discussed below.

1. Adding solution package to the server

stsadm.exe -o addsolution -filename myEventCalendarList.wsp
OR
Use the complete location of the file, for example:
stsadm.exe -o addsolution -filename “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN\Solution\myEventCalendarList.wsp”

Deploy solution package command

2. Deploying the Solution

Deploy the solution using the following command:
stsadm -o deploysolution -name myEventCalendarList.wsp  -url http://sp-dev/ -local  -force
Here( -url) means the web application where to deploy the solution.
OR
Goto, Central Administration > System Settings >Manage farm solutions
Now click your solution from the list (for example, myEventCalendarList.wsp).

Manage farm solutions
a)  Now click Deploy Solution and select the web application where you want to deploy the solution (example, http://sp-dev here), Click OK when you are done.

Click Deploy Solution

Select web application where you want to deploy
b)  And finally you will have your solution deployed status like the following.

solution deployment status
You are done with deployment.

OPTIONAL STEP (You can do it when necessary):

Now you have to enable this feature at the website to use it. To do it follow these steps:
3.  Enable the features at the website>>
Go to your Site settings> Site Collection Administration > Site collection features
And activate the feature (myEventCalendarList ,for example)  that you have installed. And add that webpart  to your site to test.
Hope it helps.

Solution Package

A solution package is a distribution package that delivers your custom SharePoint Server 2010 development work to the Web servers or the application servers in your server farm. Use solutions to package and deploy custom Features, site definitions, templates, layout pages, Web Parts, cascading style sheets, and assemblies.

A solution package is a CAB file with a .wsp file name extension and a manifest file. It is recommended that you use Visual Studio 2010 Tools for SharePoint 2010 to develop and package SharePoint solutions. You can also create solution packages manually by using a tool such as Makecab.exe.

Components that can be packaged in a solution include:
  • .NET Framework assemblies, typically Web part assemblies and event receiver assemblies.
  • Deployment files such as resource files, pages, or other helper files.
  • Features, which allow you to activate and deactivate code in a Web site and provide functionality that include elements such as custom lists, libraries, fields, and content types.
  • New templates and site definitions.
  • Configurations that must be performed at the Web-server level — for example, deploying customizations to the Web.config files for the registration of Web Parts. You can also modify these configurations with a Feature that is distributed with a Feature.
  • Web content such as Web pages and images that are called by Web pages. If you must deploy Web content in a disconnected environment, you should use a content deployment package.

What problems WSP solves?Suppose you developed a custom solution for sharepoint and now is the time to deploy that to production. Your solution included set of Features, site definitions, assemblies, Web Part packages, class resources etc etc. Now the production has 3 Web Front Ends, an Application server and a SQL backend.
In an ideal world, the infrastructure (i.e. the farm) is under the control of Administrators and you handed over your solution to them for deployment. Now the Administrator has no idea what your solution does, what are these resources, where to put them and what configuration is necessary to make them work. He is simply baffled at what you just handed over to him, coz he knows that he has to do that for all the 3 Web Front Ends and the Application server one by one. This is problem no. 1.
In a real world, ofcourse it will be you yourself who will be deploying the solution to production (yeah, we all know that). So, even if you know exactly how the solution works and where should you put what, it is going to be tedious and error prone to get everything right for all the Front Ends and Application Servers. You miss one file or one configuration setting at one place and you could be fired :) . Why, coz when you deployed everything, you tested and you were hitting Web Front End1 all the time and it was sublime, however, when your Boss tested, he managed to hit Web Front End2 because of load balancing among the 3 Web Front Ends, which was exactly the server where you messed up a configuration setting or was missing a file and the application failed. This is problem no. 2
So, to resolve these two problems we use solution files (.wsp). Read on.

Definition and Benefits: 
Wsp is a single file that contains all your resources including Features, site definitions, assemblies, Web Part packages, class resources etc etc. This file is used to deploy your solution to the entire farm in one go. You do not need to go to separate servers one by one for deployment. Timer Jobs will be created on each Web Front End in the farm. When the timer service on each server will run, it will execute the timer jobs and completes the deployment.
Now the farm Admin is happy coz he needs not know whats inside the wsp. He simply has to take the .wsp file and deploy once and for all, no need to go to each and every Web Front End or Application Server (solves problem no.1). And, you are happy coz you dont need to worry that all the files are gonig to all the places, and i.e. all the right places, making sure all configuration settings are OK, and last but not the least, your Boss tested successfully (solves problem no.2).
Deployment is a process of Distributing, Unpacking and Installing solutions to a SharePoint server farm.
Solution File is an Easy, Safe, Consistent and Reusable way of Deployment.
Sounds great, isn’t it.
Now let’s see how to build wsp files.

Building Solution Packages (.wsp files):
There could be three ways to build a solution package (.wsp file).
  1. Manually
  2. DDF File
  3. WSPBuilder
Manually, you dont want it.
DDF stands for Diamond Definition File, Diamond Directive File…………whatever you may want to call it. Using DDF is tedious. It’s the ancient way of building WSPs. You have to write a Manifest.xml manually (this file tells what to put on the server farm and where to put it), then you have to write a .ddf file manually (its an instruction file that tells the compiler what to put in the wsp package i.e. in .wsp file), and then compile using makecab.exe which will read your .ddf file and give you a .wsp file. So, this is the old way of doing things, what’s new then.
It is WSPBuilder. What WSPBuilder does:
  1. Generates the solution package (.wsp file) for you automatically with a click, Period.
So, you save all the hassle of writing Manifest.xml. WSPBuilder will automatically generate it for you and put that in the .wsp file. No need for DDF file. No need for makecab.exe.
Newer versions of WSPBuilder will even Deploy, Upgrade, Uninstall solution packages along with many other features. I am trying to stick myself only to building and deploying solution packages and their schema.

Real World Example:
Now, I want to do a real world example of a WSPBuilder and talk about some of the elementsin Manifest.xml file and how to manipulate them for our custom needs.
Why Manifest.xml, coz we said that “what to put and where to put” is specified in Manifest.xml. So, if this is automatically generated by WSPBuilder, it can know about “what to put” as we will be using WSPBuilder from within Visual Studio where our custom solution is, but how will it know “where to put”. Here is the reason why we want to discuss elementswithin Manifest.xml.
Download and Install WSPBuilder Extensions from here (latest version as of today is 1.0.6):
http://wspbuilder.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30858
Open any of your sharepoint projects in Visual Studio. I wrote a sharepoint event handlerpost here and will be using the same project for this example. So, I will create a solution package using “WSPBuilder Extensions for Visual Studio” to deploy my “Event Handler Feature” to a sharepoint farm.
Installation is very simple and I assume you did that successfully. In visual studio right click your project and you will see the following:

 You can now see lots of features available with this tool. Click Build WSP. Output screen will display something like this:
 

 If you received an error message about cablib.dll, look here.
Now go to your project directory on the file system. You will see that two new files are added there:

 Solutionid.txt contains just a GUID that is used in Manifest.xml. So, where is Manifest.xml. Lets find out. Rename your .wsp file and change the extension to .cab:

 Double click the .cab file and open. This is what you see:

Note the Path tab in the figure above. WSP will not show you folder structures but it will keep track of folders using this path value. 
So the wsp contains my ”Event Handler’s DLL”, “Feature.xml” and “Elements.xml” (remember that I am implementing my event handler as feature). Three of these files are part of my custom solution and not generated by WSPBuilder. The only thing WSPBuilder generated is the Manifest.xml. Lets see whats inside it and what it means (and ofcourse how to manipulate it):


What’s this Manifest.xml:
<?xml version="1.0"?>
<!-- Solution created by WSPBuilder. 2/12/2009 4:31:46 PM  -->
<Solution SolutionId="f33a01ff-84d9-481f-8c60-8f3e661c734b" xmlns="http://schemas.microsoft.com/sharepoint/">
  <Assemblies>
    <Assembly Location="EventHandler.SharePoint.SendEmail.Feature.dll" DeploymentTarget="GlobalAssemblyCache" />
  </Assemblies>
  <FeatureManifests>
    <FeatureManifest Location="EventHandler.SharePoint.SendEmail.Feature\feature.xml" />
  </FeatureManifests>
</Solution>



First element of a Manifest.xml is always a <Solution>. You can see the GUID from solutionid.txt being used in SoutionId attribute.
Other elements in Manifest.xml specify three things:
  1. What is in the WSP
  2. Where is it placed in the WSP
  3. Where should it be placed in the server farm
Note these questions as I’ll refer to these below. Anwers to these questions will vary with theelement type. Every element has an associated default location with it that answers question no. 3 i.e. Where should it be placed in the server farm.


<Assembly>******************************************************
Lets examine these elements and their attributes one by one. Lets first take the element <Assembly>.

<Assemblies>
    <Assembly Location="EventHandler.SharePoint.SendEmail.Feature.dll" DeploymentTarget="GlobalAssemblyCache" />
</Assemblies>
  • Assembly element is telling the installer that this is going to be an assembly. Answers question no. 1. 
  • Location attribute is telling the installer to look for the “EventHandler.SharePoint.SendEmail.Feature.dll” at the root of the WSP file. Answers question no. 2.
  • DeploymentTarget is telling the installer to deploy it to GlobalAssemblyCache (GAC). Answers question no. 3. 
So, the Manifest is telling the installer to get EventHandler.SharePoint.SendEmail.Feature.dll from the root directory from within the wsp and deploy it to Global Assembly Cache (GAC).
Other option would have been DeploymentTarget = “WebApplication”, in that case the dll would have been deployed to the bin folder of the web application.
********************************************************


<FeatureManifest>********************************************************
In the case above, DeploymentTarget was mentioned separately, however, this is not the case with <FeatureManifest> element. Let’s have a look:

<FeatureManifests>
    <FeatureManifest Location="EventHandler.SharePoint.SendEmail.Feature\feature.xml" />
</FeatureManifests>
  • FeatureManifest is telling the installer that this is a feature. Answers question no. 1.

  • Location is telling the installer to look for feature.xml file in EventHandler.SharePoint.SendEmail.Feature directory within wsp file. So, once again, you wont see “EventHandler.SharePoint.SendEmail.Feature” folder inside the .wsp file, it is calculated based on the path value as shown above. Answers question no. 2.

  • Now how does the installer find out where to deploy this feature.xml. That is hidden in the element type as mentioned before. FeatureManifest element is used to specify features, so this element type has a location associated with it. That location is root of all the Features in sharepoint. Can you guess it now, yeah it is 12\TEMPLATE\FEATURES, where all sharepoint Features reside. Answers question no. 3.
So, the Manifest is telling the installer to get feature.xml from EventHandler.SharePoint.SendEmail.Feature directory from within the wsp and deploy it to
12\TEMPLATE\FEATURES\EventHandler.SharePoint.SendEmail.Feature\feature.xml.
*******************************************************

<TemplateFile>*******************************************************
Similarly, there could have been a TemplateFile element in the Manifest.xml had my solution contained a user control:

<TemplateFiles>
    <TemplateFile Location="ControlTemplates\SendEmailForm.ascx"/>
</TemplateFiles>
  • TemplateFile is telling the installer that this is a Template File. (Answers question no. 1).

  • Location is telling the installer to look for the control SendEmailForm.ascx file in ControlTemplates directory within the wsp file. Answers question no. 2.

  • Now how does the installer find out where to deploy SendEmailForm.ascx control. That is hidden in the element typeTemplateFile element is used to specify template files, so this element type has a location associated with it. That location is the root of all the templates in sharepoint. Ofcourse you guessed it this time i.e. 12\TEMPLATE, where all sharepoint templates reside. Answers question no. 3.
Now, if you examine the TEMPLATE folder under 12 hive, you will notice that there is a CONTROLTEMPLATES directory with lots of user controls already in there.
So, the Manifest is telling the installer to get SendEmailForm.ascx from ControlTemplates directory from within the wsp and deploy it to 12\TEMPLATE\CONTROLTEMPLATES\SendEmailForm.ascx.
******************************************************


Conclusion (sort of :) )
In the case of FeatureManifest, “EventHandler.SharePoint.SendEmail.Feature” folder was not available in FEATURES directory but mentioned in Manifest.xml, so the installer will create a new folder with that name and put “feature.xml” in it. In the case of TemplateFile, ”CONTROLTEMPLATES” directory was already available under “TEMPLATE” folder, but “CONTROLTEMPLATES” was also mentioned in Manifest.xml, even then the installer will not create a new directory and use the existing “CONTROLTEMPLATES” directory and put “SendEmailForm.ascx” in it.
So, if its an existing directory, use the same one, otherwise create new.
I hope by now you have got a good idea of how this works. Here is a list of Elements and the associated root locations:


Manifest ElementRoot Location
WebTempFile12\Template
AssemblyWeb Application bin or GAC
FeatureManifest12\TEMPLATE\FEATURES
RootFileResourceFile12
ResourceFile12\TEMPLATE\FEATURE
SiteDefinitionManifest12\TEMPLATE\SiteTemplates
TemplateFile12\TEMPLATE
ApplicationResourceFile12\Resources




Manipulating Manifest.xml:Now, you may be thinking that directory structures could be specified as of our likinng in Manifest.xml. That’s not always true. Some may actually fail. For instance, if you specify “Location = MyFeature\EventHandler.SharePoint.SendEmail.Feature\feature.xml” for a <FeatureManifest> element, this will not work and you may actually receive an error message. Its coz Features can only locate directly under FEATURES directory. The immediate directory under FEATURES directory should have feature.xml in it. If you try to create ”MyFeature” directory, then “EventHandler.SharePoint.SendEmail.Feature” directory and this has feature.xml in it, this will not work.
However, if you want a different directory for your controls to separate them from sharepoint controls then you may specify the following directory structure without any problems:



<TemplateFiles>
    <TemplateFile Location="ControlTemplates\MyCustomControls\SendEmailForm.ascx"/>
</TemplateFiles>
This will create “MyCustomControls” directory in “CONTROLTEMPLATES” and put “SendEmailForm.ascx” in it.

Deploying using solution packages (.wsp files):Oh, I forgot, we still have to deploy the solution. So, first we add it to the Solution Store and then deploy it. Here are the commands to do so:



stsadm.exe -o addsolution -filename "c:\EventHandler.SharePoint.SendEmail.Feature.wsp"

Adding always involves STSADM command. You can deploy either by STSADM or Central Administration. If you wish you can deploy using the following STSADM command, but I am going to do it using Central Administration:

stsadm.exe -o deploysolution -name "c:\EventHandler.SharePoint.SendEmail.Feature.wsp" -immediate -allowGacDeployment -allowCasPolicies -force


Go to Central Administration -> Operations -> click Solution Management (under Global Configuration)
You will see your solution as “Not Deployed”, though added to the solution store:

Click the wsp file and click “Deploy Solution on the following screen:


Select “Now” and click OK:

Wait for sometime and (if everything goes fine), you should see the following screen with status as “Deployed”:

Now you can go and see your feature created under FEATURES directory in 12 hive (only if your custom solution created a Feature):

Your feature will also appear in “Site Features”:

That’s it.