Navigation

Saturday, 17 January 2015

Enable PowerShell ISE for Windows Server 2008 R2

PowerShell ISE (Integrated Scripting Environment) gets installed by default with Windows 7  or Windows Server 2008 R2 but doesn't show in the start menu. There are two ways to enable PowerShell ISE.

Windows PowerShell ISE (Integrated Scripting Environment) is a host application for Windows PowerShell.In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphical user interface. Its features include multiline editing, tab completion, syntax coloring, selective execution, context-sensitive Help, and support for right-to-left languages.

  Using PowerShell
  1. Open Powershell Window
  2. Execute following cmdlets.
 Import-Module ServerManager 
 Add-WindowsFeature PowerShell-ISE
 





















Using Server Explorer
  1. Open the Server Explorer
  2. Navigate to the Features Node
  3. Right-click on Features node, select “Add Features
  4. You will get Add Features wizard with list of features provided with checkboxes.
  5. Check the “Windows PowerShell Integrated Scripting Environment (ISE)”
  6. Click on Next button
  7. Click on Install button.

Wednesday, 14 January 2015

Difference between application Pages and Site Pages

Application Pages:
1.These are the normal .aspx pages deployed within SharePoint. Most common of them are the admin pages found in _layouts folder.
2.These are deployed either at the farm level or at application level. If they are deployed within _layouts folder or global SharePoint Virtual Directory, then they can be used by any SharePoint application (available at farm level), otherwise they can be deployed at application level only by creating a virtual directory.
3.These are typical ASP.Net aspx pages and can utilize all of the functionalities available within ASP.Net including code-behind, code-beside, inline coding etc.
4.These are compiled by .Net runtime like normal pages.
5.They can only use master pages available on file-system not within SharePoint Content Databases and for the same reason, you will notice that _layouts pages can only use Application master page deployed within _layouts folder and cannot use any of your custom master page deployed within SharePoint masterpage library.
6.If you deploy your custom ASPX pages within _layouts folder or within SharePoint application using a virtual directory, you will not be able to use SharePoint master pages and have to deploy your master page within the virtual directory or _layouts folder.
7.Application Pages cannot use contents as this concept is associated with SharePoint Page Layouts not with ASP.Net.
8.Since application pages are compiled once, they are much faster
9.Normally application pages are not web part pages, hence can only contain server controls or user controls and cannot be personalized by users.
10.Easiest way to deploy your existing ASP.Net web site within SharePoint is to deploy its pages as Application Pages within SharePoint. In this way you can convert any ASP.Net web solution as SharePoint application with minimal efforts.
11.SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages not against application pages.
12.Application pages can be globalized using Resource files only.
Site Pages
1.Site Pages is a concept where complete or partial page is stored within content database and then actual page is parsed at runtime and delivered to end-users.
2.Pages stored in Pages libraries or document libraries or at root level within SharePoint (Wiki pages) are Site Pages
3.You must be thinking why we should use such pages? There are many reasons for this. One of the biggest catch of the SharePoint is the page layouts, where you can modify page once for a specific content type and then you can create multiple pages using the same page layout with different contents. In this case, contents are stored within database for better manageability of data with all the advantages of a data driven system like searching, indexing, compression, etc and page layouts are stored on file system and final page is created by merging both of them and then the outcome is pared by SharePoint not compiled.
4.Site Pages can contain web parts as well as contents placeholders, and all of them are stored per page-instance level within database and then retrieved at run time, parsed and rendered.
5.Another advantage is they are at user-level not at web-application or farm level and can be customized per site level.
6.Since their definition is retrieved from database, they can utilize master pages stored within SharePoint masterpages library and merged with them at run time for rendering.
7.They are slower as compared to Application pages as they are parsed everytime they are accessed.
8.SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages not against application pages.
9.Since they are rendered not compiled hence it is not easy to add any inline code, code behind or code beside. Best way of adding code to these pages is through web-parts, server controls in master pages, user controls stored in “Control Templates” folder or through smart parts. If you want to add any inline code to master page, first you need to add following configuration within web.config:
PageParserPaths
PageParserPath VirtualPath=”/_catalogs/masterpage/*” CompilationMode=”Always” AllowServerSideScript=”true” IncludeSubFolders=”true” /
PageParserPaths
10.To add code behind to SharePoint master pages or page layouts, refer to this MSDN article
11.Since Site pages are content pages, hence all SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages.
12.Variations can only be applied against Site pages for creating multilingual sites.
13.”SPVirtualPathProvider” is the virtual path provider responsible for handling all site pages requests. It handles both ghosted and unghosted pages requests as shown below

Difference between Site Definition and Site Template in SharePoint

Site Definitions
  • A site definition is the core definition of what a site is in SharePoint.
  • A site definition is installed on file system of web front ends, located at ..\12\Template\SiteTemplates. This directory is language-neutral.
  • A site definition consists of .aspx pages and .xml files with Collaborative Application Mark-up Language (CAML).
  • A major benefit is that the Page and List definition is read locally from the file system, not from Content Database.
Site Template
  • A site template (*.stp file) is created through the user interface or through implementation of the object model.
  • The site template package is a package containing a set of differences and changes from a base site definition.
  • The site template package is stored as a CAB-based file that can be downloaded or uploaded to site collections by users with the appropriate rights.
When choosing whether to create a site template or a site definition, first consider the following issues:
Are the changes you need to make simple or complex? If, for example, you need to make only minor changes in the look of certain pages and add a few fields in particular lists, you should create a custom site template.
However, if you need to create new content types, add new Web Part definitions, and significantly restructure sites, you should create a custom site definition.
Can you deploy changes to the front-end Web server? If you do not have access to the file system of the computers running Windows SharePoint Services, you have no choice but to create a custom site template.
Site definition (Advantages):
  • Data is stored directly on the Web servers, so performance is typically better.
  • A higher level of list customization is possible through direct editing of a Schema.xml file.
  • Certain kinds of customization to sites or lists require use of site definitions, such as introducing new file types, defining view styles, or modifying the Edit menu.
Site definition (Disadvantages):
  • Customization of site definition requires more effort than creating custom templates.
  • Editing a site definition after it has been deployed is difficult.
  • Doing anything other than adding code can break existing sites.
  • Users cannot apply a SharePoint theme through a site definition.
  • Users cannot create two lists of the same type with different default content.
  • Customizing site definitions requires access to the file system of the front-end Web server.
Site Templates (Advantages):
  • Custom templates are easy to create.
  • Almost anything that can be done in the user interface can be preserved in the template.
  • Custom templates can be modified without affecting existing sites that have been created from the templates.
  • Custom templates are easy to deploy.
Site Templates (Disadvantages):
  • Custom templates are not created in a development environment.
  • Custom templates are less efficient in large-scale environments.
  • If the site definition on which the custom template is based does not exist on the front-end server or servers, the custom template does not work.
Now to the fun part, the comparison :
Site Definitions
Site Templates
Files are on disk, better performance.Files are in database, less efficient.
Highly customizable and extensible (XML  and .NET code is much more flexible than UI)Not easily extensible  (You are limited by what UI offers)
Can provision multiple webs *Can only provision one web
Complex to createEasier to create
Requires admin access to server for deploying.Installable from a Web UI by site owners.
Modifying the site definition after provisioning at least one site from it is not supported and might break existing sites.Custom templates can be modified without affecting existing sites that have been created from the templates(**).

SharePoint WebPart Page Life Cycle

OnInit – Configuration values set using WebBrowsable properties and those in web part task pane are loaded into the web part.
LoadViewState – The view state of the web part is populated over here.
CreateChildControls – All the controls specified are created and added to controls collection. When the page is being rendered for the first time the method generally occurs after the OnLoad() event. In case of postback, it is called before the OnLoad() event. We can make use of EnsureChildControls() – It checks to see if the CreateChildControls method has yet been called, and if it has not, calls it.
OnLoad User Generated Event – for e.g. button click on the web part.
OnPreRender – Here we can change any of the web part properties before the control output is drawn.
RenderContents – Html Output is generated.
SaveViewState – View state of the web part is serialized and saved.
Dispose -UnLoad.

Ghosting and Unghosting in SharePoint

Ghosted pages are pages whose content doesn’t reside in the content database (save as a row with a null value for Content); they reside on the actual file system disk. When site pages are customized, the page is unghosted and their content is then stored in the content database. The issue with unghosted pages is that site maintenance and performance can be affected (e.g. updating server or solution may be impacted or site caching may be affected).
[ In SharePoint Designer 2010, though, you have the option to have more control over how site pages are customized—thus disabling the ghosting process from occurring. To find this functionality, go to SharePoint 2010 Central Administration, and click General Settings, and then under the SharePoint Designer category click Configure SharePoint Designer settings
Under the Configure SharePoint Designer settings, you can check/uncheck a number of settings—one of which is the Allow Site Collection Administrators to Detach Pages from the Site Template option. If you uncheck this option, you are disabling the detachment of pages from the site definition—thus disabling ghosting from occurring.
What happens is that site collection administrators can now edit the site is Normal mode from SharePoint Designer; not the Advanced mode, which supports the ghosting/unghosting process. ]
Ghosted means that the Site Definition pages have not been customized and the pages in your Site Definitions run directly from the file system (cached of course).
SharePoint provide users with an easily customizable platform to do work. It leverages both files on the file system and data in a database to virtually create many sites most of which share the same files on the file system. The net effect is that SharePoint gives the appearance that it’s many files when in reality it’s a relatively small number.
This is accomplished by a technique that used to be called Ghosting. SharePoint contains database entries for each site and each page in the site. By default these entries refer back to a file on the file system. The result of this is that there’s good performance and the ability to impact changes on a massive scale just by changing one file. Since every site refers back to that one set of files making a change there has a global impact.
These files reside in physical ~\TEMPLATE\LAYOUTS\ path of 12 hives.
For example, the default home page is a ghosted page.  Any web part pages created via New Web Part Page user interface also ghosted.
You can also check this out by going to a page like the default.aspx page in the STS Site Definition and typing “Hello” in the body somewhere. Run IIISRESET to clear the cache, and you’ll see that “Hello” shows up immediately on all sites that were created using that Site Definition.
Unghosted means that the site has been customized.  When you customize a v2.0 site in FrontPage or a v3.0 site in SharePoint Designer, or you add custom fields to a Document Library, or create sites using that template; then the changes that you made are stored in the database as a diff and that is referred to as Unghosted.
A request for a Customized (Un-Ghosted) page returns a response which is a combination of data from both the file system and the database. In v2 this was a performance hit, and you wanted to avoid having a large number of sites that were Un-Ghosted. In v3 – caching etc. has been improved.
Ghosted = Un-Customized, The asp.net parser renders the page.
Unghosted = Customized, Controlled by the SafeMode parser.

Is it possible to “reset” an unghosted page to its original ghosted state? No.
This ties into the previous answer. Straight out of the box, there is no way to return a page to its originalghosted state.
Can a page transition from a ghosted state to unghosted? Yes.
Ghosted pages become unghosted once a file has been modified. If a page is updated using FrontPage 2003, web folders, or the modification of custom document library fields, the Content column of the given document row is populated with the page contents. All uploaded .aspx files are automatically unghosted

Ghosted Page in SharePoint
A ghosted page is a page in SharePoint website which is not stored in the database instead it reference to a file which exists in the server’s file system. These reference files are common for all the website/site collection within that SharePoint server, i.e., if you modify a reference file then that change will reflect in all the websites/site collections within that SharePoint server automatically. So we can say these reference files are used as template.
The default master page of SharePoint “default.master” is a well known example of ghosted page. “default.master” page is located in the directory “C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\Global”. If you do some changes in the “default.master” then this change will automatically reflect in all the websites within that SharePoint server.
To create a new site in SharePoint, a site template is used. Site template contains description of all the pages, webparts within the pages, master page used, custom lists, etc. for the web site to be created. You can define a page ghostable in the “onet.xml” file of the site template.
Unghosted Page in SharePoint
All the pages in a SharePoint website which are stored in the content database are referred as unghosted pages. All the unghosted pages are specific to that SharePoint website only, i.e., changes done in an unghosted pages will not reflect in other websites within that SharePoint server.
If a new website is created with a site template which contains a page defined as “unghostable” in the “onet.xml”, then that page will be stored in the content database of new website created and will not reference to the page available in the site template folder.
If a ghosted page is modified in the SharePoint designer, it will become unghosted. For example if a master page is customized in SharePoint Designer, SharePoint stores a modified version of the master page in the content database and also it breaks the reference to the “default.master” file on the “C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\Global“.

Monday, 12 January 2015

DisableEventFiring is obsolete in SharePoint 2010

You can check this in msdn. However DisableEventFiring()/EnableEventFiring() still works as per Reflector.
Recommended way now is to use new property EventFiringEnabled. This gives us an option to check current status and save it. I found a great post from Adrian Henke and modified his code using this new feature.

public class DisabledItemEventsScope : SPItemEventReceiver, IDisposable
{
private bool eventFiringEnabledStatus;
public DisabledItemEventsScope()
{
eventFiringEnabledStatus = base.EventFiringEnabled;
base.EventFiringEnabled = false;
}
#region IDisposable Members
public void Dispose()
{
base.EventFiringEnabled = eventFiringEnabledStatus;
}
#endregion
}
The class DisabledItemEventsScope disable/enable event firing for the current thread 
and could be used in that manner at any place  
including code behind for the page or web part   
item["Title"]="New Title";
using (new DisabledItemEventsScope())
{
item.Update(); // will NOT fire events
}

 BTW: There are couple useful SPList extensions to manage SPListItemEventReceiver collection

public static void AddEventReceivers(this SPList list,Type erClassType,params SPEventReceiverType[] erTypes)
{
foreach (SPEventReceiverType erType in erTypes)
{
list.EventReceivers.Add(erType, erClassType.Assembly.FullName, erClassType.FullName);
}
} 
// Sample:
// list.RemoveEventReceivers(typeof(TestProject.ListItemEventReceivers.TestReceiver));
public static void RemoveEventReceivers(this SPList list, Type erClassType, params SPEventReceiverType[] erTypes)
{
List<SPEventReceiverDefinition> receivers = new List<SPEventReceiverDefinition>();
for (int i = 0; i < list.EventReceivers.Count; ++i)
{
SPEventReceiverDefinition r = list.EventReceivers[i];
if (r.Class.Equals(erClassType.FullName) && (erTypes.Length==0 || erTypes.Contains(r.Type)))
receivers.Add(r);
}
foreach (SPEventReceiverDefinition r in receivers)
{
r.Delete();
}
}

Attach event receiver in a particular list by Feature receiver

const string _listName = Constants.ListName;

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb oWeb = (SPWeb)properties.Feature.Parent;
                SPList oList = oWeb.Lists[_listName];
                DeleteReceiver(oList);
                oWeb.Lists[_listName].EventReceivers.Add(SPEventReceiverType.ItemAdded, Assembly.GetExecutingAssembly().FullName, "Class Name_Reviewers.SetReviewers.SetReviewers");
                oWeb.Lists[_listName].EventReceivers.Add(SPEventReceiverType.ItemUpdated, Assembly.GetExecutingAssembly().FullName, "ClassName_Reviewers.SetReviewers.SetReviewers");
            }
            catch (Exception ex)
            {
                Constants.LogToUls(Constants.LogCategory, string.Format("Exception occured on featureactivation: Message {0} - Stacktrace {1} ", ex.Message, ex.StackTrace));
            }
        }

------------
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb oWeb = (SPWeb)properties.Feature.Parent;
                SPList oList = oWeb.Lists[_listName];
                DeleteReceiver(oList);
            }
            catch (Exception ex)
            {
                Constants.LogToUls(Constants.LogCategory, string.Format("Exception occured on FeatureDeactivating: Message {0} - Stacktrace {1} ", ex.Message, ex.StackTrace));
            }
        }
-------------------
private void DeleteReceiver(SPList oList)
        {
            try
            {
                for (int i = oList.EventReceivers.Count - 1; i >= 0; i--)
                {
                    if (oList.EventReceivers[i].Type.Equals(SPEventReceiverType.ItemAdded) || oList.EventReceivers[i].Type.Equals(SPEventReceiverType.ItemUpdated))
                    {
                        oList.EventReceivers[i].Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                Constants.LogToUls(Constants.LogCategory, string.Format("Exception occured on delete receiver: Message {0} - Stacktrace {1} ", ex.Message, ex.StackTrace));
                throw;
            }
        }

Event Receivers BeforeProperties or AfterProperties



These are the values of the properties in List events:


ListBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo ValueNo ValueNull
ItemAddedNo ValueNo ValueNew Value
ItemUpdatingOriginal ValueChanged ValueOriginal Value
ItemUpdatedOriginal ValueChanged ValueChanged Value
ItemDeletingNo ValueNo ValueOriginal Value
ItemDeletedNo ValueNo ValueNull

And here are the properties available in Library events:


LibraryBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo ValueNo ValueNull
ItemAddedNo ValueNo ValueNew Value
ItemUpdatingOriginal ValueChanged ValueOriginal Value
ItemUpdatedOriginal ValueChanged ValueChanged Value
ItemDeletingNo ValueNo ValueOriginal Value
ItemDeletedNo ValueNo ValueNull
-------------------------------------------
ListBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo valueNew valueNull
ItemAddedNo valueNew valueNew value
ItemUpdatingNo valueChanged valueOriginal value
ItemUpdatedNo valueChanged valueChanged value
ItemDeletingNo valueNo valueOriginal value
ItemDeletedNo valueNo valueNull

No value means that column value in the hash table was not available.
New value means that the correct value for the column was available.
Changed value means that the correct updated value was available.
Original value means that the correct original value was available.



Here is the same test against a document library:
LibraryBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo valueNo valueNull
ItemAddedNo valueNo valueNew value
ItemUpdatingOriginal valueChanged valueOriginal value
ItemUpdatedOriginal valueChanged valueChanged value
ItemDeletingNo valueNo valueOriginal value
ItemDeletedNo valueNo valueNull