Why PowerShell ? Why Now ?
PowerShell was designed to do for Windows what the UNIX shells do for UNIX: provide a powerful, well-integrated command-line experience for the operation
system. Unfortunately since Windows is mostly managed through objects (WMI, COM and .NET) this required creating a new kind
of shell. So why create it now? As Windows moves off the desktop
and into server farms or application servers like print, DNS
and LDAP services, command-line automation becomes a
fundamental requirement.
PowerShell is freely available through the Microsoft Windows Update Service packaged as an optional update for Windows XP SP2, Windows Vista and Windows Server 2003. It is also included with Windows Server 2008 as an optional component.
In Sharepoint 2007,Farm Administrators used STSADM.EXE to do the administrative tasks. SharePoint Foundation still installs STSADM.EXE but it is primarily included to support backwards compatibility with scripts migrating from earlier versions.
PowerShell is something i was always love to have in the production farm.In MOSS 2007,there were many things which can be done through object model easily,can’t done through STSADM.EXE.Sharepoint 2010 is the first version to directly support PowerShell.In PowerShell, You can directly access Sharepoint object model through the codes in the console window. Nice …isn’t it ?
I started exploring PowerShell long back. In next couple of posts, i will try to provide comprehensive list of operations you need to know to get your hands dirty on PowerShell.
http://msdn.microsoft.com/en-us/library/ee554869(office.14).aspx
Only thing missing is installing Visual studio 2010. Install visual studio 2010 first and then proceed towards installation of sharepoint 2010.
http://andreasglaser.net/post/2009/11/17/Installing-SharePoint-Server-2010-on-Windows-Server-2008-R2-and-SQL-Server-2008-R2-Part-1-Overview.aspx
There will be two errors most likely to come while configuration wizard is running.
Failed to register SharePoint services.
An exception of type System.TypeLoadException was thrown. Additional exception information: Could not load type 'Microsoft.Office.Server.Search.Administration.SearchWebServiceManagerService' from assembly 'Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C'.
System.TypeLoadException: Could not load type 'Microsoft.Office.Server.Search.Administration.SearchWebServiceManagerService' from assembly 'Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C'.
at System.RuntimeTypeHandle._GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, Boolean loadTypeFromPartialName)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.RuntimeType.PrivateGetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase)
at Microsoft.SharePoint.PostSetupConfiguration.ReflectionHelper.InvokeConstructor(String assemblyQualifiedName, Type[] constructorSignature, Object[] constructorParameters)
at Microsoft.SharePoint.PostSetupConfiguration.TaskCommon.ReflectionHelperInvokeConstructor(String assemblyQualifiedName, Type[] constructorSignature, Object[] constructorParameters, TaskBase task)
at Microsoft.SharePoint.PostSetupConfiguration.ServicesTask.InvokeServiceConstructor(String serviceRegistryKeyName, String solutionIdRegistryName, String serviceNameRegistryName, Type[] constructorSignature, Object[] constructorParameters)
at Microsoft.SharePoint.PostSetupConfiguration.ServicesTask.InstallServiceInConfigDB(Boolean provisionTheServiceToo, String serviceRegistryKeyName)
at Microsoft.SharePoint.PostSetupConfiguration.ServicesTask.InstallServices(Boolean provisionTheServicesToo)
at Microsoft.SharePoint.PostSetupConfiguration.ServicesTask.Run()
at Microsoft.SharePoint.PostSetupConfiguration.TaskThread.ExecuteTask()
----------------------------------------------------------------------------------------------------------------------------------------------
This error can be removed by removing the following registry keys
Removing the following registry keys fixed the problem:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\WSS\Services\Microsoft.Office.Server.Search.Administration.SearchWebServiceManagerService]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\WSS\ServiceProxies\Microsoft.Office.Server.Search.Administration.SearchWebServiceManagerServiceProxy]
2. Error in step 8
Failed to create sample data.
An exception of type Microsoft.Office.Server.UserProfiles.UserProfileException was thrown. Additional exception information: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (application/soap+msbin1). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: ....
This error can be removed by installing the following hotfix
http://go.microsoft.com/fwlink/?LinkID=166231
In Sharepoint point sites, if are storing data in a sharepoint list, then you can use inbuilt “Custom list” webpart to display data in the sharepoint pages .But, What if the Data is stored other than sharepoint lists and you want to display the data in sharepoint list style ? In my scenario, I have the requirement that, I have to show data from sql server database in sharepoint list style .Here is something I found interesting.
Sharepoint uses Microsoft.SharePoint.WebControls.SPGridView control to display its own list. Here goes the webpart
It contains almost everything; you can do with a SPGridView.To start with let’s add a GridView to the Webpart and assign data source
using System;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Drawing;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
#region Method : CreateChildControls
///
/// Method Name : CreateChildControls
/// Description : Method for creating the child controls.
///
protected override void CreateChildControls()
{
//Defining the grid view
SPGridView customGridView = new SPGridView();
//Here GetCustomData() function returns a dataset.
customGridView.DataSource = GetCustomData();
this.Controls.Add(customGridView);
}
In this case, the columns are auto generated based on the data columns in the dataset.
Let’s include List items menu’s to the individual row of the grid view. Let’s include the following code for service grid view inside create child controls.
serviceGridView.AutoGenerateColumns = false;
SPBoundField titleBoundField = new SPBoundField();
//Assigning the Columnname which is coming from the dataset
titleBoundField.DataField = “TITLE”;
titleBoundField.HeaderText = " Service Title";
titleBoundField.HeaderStyle.CssClas=ConstantVariables.GetMSFormBobyCSS;
SPBoundField serviceIDBoundField = new SPBoundField();
serviceIDBoundField.DataField = SERVICEID;
serviceIDBoundField.HeaderText = "ServiceID";
serviceIDBoundField.Visible = false;
serviceIDBoundField.HeaderStyle.CssClass= “myCustomClass”; customGridView.Columns.Add(titleBoundField);
customGridView.Columns.Add(serviceIDBoundField);
titleBoundField.Visible = false;
//Defining Menu Field for the Title
titleMenuField = new SPMenuField();
titleMenuField.HeaderText = "Service Title";
titleMenuField.TextFields = TITLE;
titleMenuField.HeaderStyle.CssClass = “myCustomClass”;
titleMenuField.MenuTemplateId = "ServicesMenu";
titleMenuField.TokenNameAndValueFields = "CustomID=ServiceID";
titleMenuField.SortExpression = TITLE;
MenuTemplate servicesListMenuTemplate = new MenuTemplate();
servicesListMenuTemplate.ID = "ServicesMenu";
//Defining Menu Templates for the menu
MenuItemTemplate viewMenuItemTemplate = new MenuItemTemplate("View Details");
StringBuilder viewDetailsUrl = new StringBuilder();
viewDetailsUrl.Append(“http://google.com”);
//Adding event on menu item click
viewMenuItemTemplate.ClientOnClickNavigateUrl=viewDetailsUrl.ToString();
servicesListMenuTemplate.Controls.Add(viewMenuItemTemplate);
MenuItemTemplate editMenuItemTemplate = new MenuItemTemplate("Edit Details");
StringBuilder editDetailsUrl = new StringBuilder();
editDetailsUrl.Append(“http://www.msdn.com”);
//Adding event on menu item click
editMenuItemTemplate.ClientOnClickNavigateUrl=editDetailsUrl.ToString();
servicesListMenuTemplate.Controls.Add(editMenuItemTemplate);
deleteMenuItemTemplate = new MenuItemTemplate("Delete");
deleteMenuItemTemplate.ClientOnClickScript = "javascript:do_confirmService('" + this.UniqueID + "','%CustomID%');";
servicesListMenuTemplate.Controls.Add(deleteMenuItemTemplate);
//Adding seperator template
MenuSeparatorTemplate sepMenuTemplate = new MenuSeparatorTemplate();
servicesListMenuTemplate.Controls.Add(sepMenuTemplate);
this.Controls.Add(servicesListMenuTemplate);
customGridView.Columns.Add(titleMenuField);
//Defining Description Column
SPBoundField statusBoundField = new SPBoundField();
statusBoundField.DataField = "Status";
statusBoundField.HeaderText = "Status";
statusBoundField.HeaderStyle.CssClass = ConstantVariables.GetMSFormBobyCSS;
customGridView.Columns.Add(statusBoundField);
SPBoundField languageBoundField = new SPBoundField();
languageBoundField.DataField = " Language ";
languageBoundField.HeaderText = "Language";
languageBoundField.HeaderStyle.CssClass = ConstantVariables.GetMSFormBobyCSS;
customGridView.Columns.Add(languageBoundField);
The most important thing above are the click event of each menu item.
1. If you want to redirect to some URL on menu item click, then you can use ClientOnClickNavigateUrl property of MenuItemTemplate
This is done here for “View Details” and “Edit Details” menu Item.
Eg : viewMenuItemTemplate.ClientOnClickNavigateUrl=viewDetailsUrl.ToString();
Here Clicking View Detail page will redirect to http://www.google.com/.
On Click of “Edit Detail” page will redirect to “http://www.msdn.com
2. What if you want some server side functionality on the client click.
You need to do four things over here.
2.1. Implement IPostBackEventHandler. Your class goes like this
using System.Web.UI;
public class Services : Microsoft.SharePoint.WebPartPages.WebPart, IPostBackEventHandler
{
}
2.2. Register your javascript file OnPreRender() method.
2.3. Call the javascript method on ClientOnClickScript event of MenuItemTemplate
Eg :
deleteMenuItemTemplate.ClientOnClickScript = "javascript:do_confirmService('" + this.UniqueID + "','% CustomID %');";
Here ‘%Name%’ is assigned to the datafield defined the Token
TokenNameAndValueFields of the MenuField
Eg : titleMenuField.TokenNameAndValueFields = " CustomID=ServiceID";
Here DataSet has a column ServiceID. So on click of delete Menu item of a particular row, serviceID of that row is passed as a parameter to the javascript.
The Javascript File goes here
File : CustomJavaScript.js
-----------------------------------------------------------------------
function do_confirmService(ID,Name)
{
if (confirm('Are you sure you want to delete the service?'))
{__doPostBack(ID,Name)
}
;
-----------------------------------------------------------------------
On click of “delete” menu item it will ask for the conformation .If you click ok, then it will do a PostBack.
2.4. Implement RaisePostBackEvent as part of IPostBackEventHandler Interface
#region Event : RaisePostBackEvent
///
/// Method Name : RaisePostBackEvent
/// Description : This method is the implementation of IPostBackEventHandler Interface and is used to Delete A Service Record while Postback event.
///
/// string
public void RaisePostBackEvent(string eventArgument)
{
//Check for the ServiceID which is passed as parameter
//here in eventArgument gives the ServiceID which is passed to javascript
}
#endregion
Enabling Paging in SPGridview
Add the follwing lines
customGridView.AllowPaging = true;
customGridView.PageSize = 15;
customGridView.PagerSettings.Mode = PagerButtons.NumericFirstLast;
serviceGridView.PageIndexChanging += new GridViewPageEventHandler(customGridView _PageIndexChanging);
//Creating Event Handler for Page index changing
#region Event : customGridView _PageIndexChanging
//
/// Method Name : serviceGridView_PageIndexChanging
/// Description : This method handles Page Indexing Event of gridview
///
/// GridViewPageEventArgs
/// object
private void customGridView _PageIndexChanging(object sender, GridViewPageEventArgs e)
{
customGridView.PageIndex = e.NewPageIndex;
customGridView.DataBind();
}
#endregion
Add following lines after adding SPGridview to the control collection.
Eg : this.Controls.Add(customGridView);
customGridView.PagerTemplate = null;
customGridView.DataBind();
Don’t DataBind the gridview before adding the control to the control collection in case of paging.
Enabling Grouping in SPGridview
customGridView.AllowGrouping = true; customGridView.AllowGroupCollapse = true; customGridView.GroupField = "TITLE"; customGridView.GroupDescriptionField = "TITLE"; customGridView.GroupFieldDisplayName = "TITLE ";
Scenario –1
Let’s consider, you have a javascript file with some javascript functions. You want to call one of the client side functions inside the webpart code. Here goes the solution
Java script File
----------------------------------------------------------------------
function do_confirmService(ID)
{
var textbox = document.GetElementByID(ID);
alert(textbox.value);
}
------------------------------------------------------------------------------
Code
Place the javascript file in Layouts folder and register it on PreRender function. Code in the webpart file goes here
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
Complete Path of the Layout folder is %Program Files%/Common Files/web server extensions/12/Template/Layouts
2.Call the javascript function in Client event. Code goes here
----------------------------------------------------------------------------------------
protected override void CreateChildControls()
{
TextBox sample = new TextBox();
sample.ID = "sampletextbox";
Button testButton = new Button();
testButton.Text = "click me";
testButton.Attributes.Add("OnClick", "javascript:doConfirmService(" + this.ClientID + "_sampletextbox");
this.Controls.Add(sample);
this.Controls.Add(testButton);
}
--------------------------------------------------------------------------------------
Now deploy the webpart.Enter some text in the textbox and click the button.It will alert the textbox value you entered.
Scenario –2
Suppose you don’t want to go for the javascript file and want to place the javascript in the code itself ,then here is the solution
///
/// Method Name : OnPreRender
/// Description : This method is for registering JavaScript file
///
/// EventArgs
protected override void OnPreRender(EventArgs e)
{
string script= @" function do_confirmService(ID)
{
var textbox = document.GetElementByID(ID);
alert(textbox.value);
}”
//regestering the Javascript
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Javascriptkey", script);
base.OnPreRender(e);
}
Then call this javascript function on the button click as discussed in step 2 above.
http://msdn.microsoft.com/en-us/library/ms469765.aspx
But If you have less number of parameters to pass, then I suggest you go for Query strings. In this article, I am describing how to work with query strings.
1.Redirecting the user from the donor webpart page to the Page having Acceptor webpart
string desiredURL = "http://www.moss2k:8080/ITServices";
//Replace desired Url with your page url of the acceptor webpart
string business= “Health”;
this.Page.Response.Redirect(WebUrl + "?mode=f&b=" + business);
Here I have passed two query strings,one is “mode” whose value is “f” and “b” whose value is assigned to a variable “business”
2.Getting the Values of query String in Acceptor webpart
this.Page.Request.QueryString[“mode”].ToString();
this.Page.Request.QueryString[“b”].ToString();
this will give you value “f” and “health” respectively