Ads

Sunday, 14 July 2013

Change master page as per logged in user group

we will discuss how you can change the master page for your site according to some logic like you can change the master page for a logged in user or simply can switch the application.master page to your custom master page for all applictaion pages.
I achive written a Step-by-step sample code to switch mater page according to logged in user's group.

The Steps to Create a Custom httpModule for Changing master page for a logged in user are :
1. Create a new Class Library project in Visual Studio name it as CustomhttpModule
2. Add the below code in your class file.
using System;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
namespace SwitchMasterPage{
public class CustomHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
{
// register handler for PreInit event
page.PreInit += new EventHandler(page_PreInit);
}
}
void page_PreInit(object sender, EventArgs e)
{
Page page = sender as Page;
if (page != null)
{
SPSite site = SPContext.Current.Site;
using (SPWeb web = site.OpenWeb())
{
if (web.CurrentUser != null)
{
SPGroupCollection userGroups = web.CurrentUser.Groups; // Check all the groups user belong to
foreach (SPGroup group in userGroups)
{
if (group.Name.Contains(“OurCustomgroupName”)
// Switch the master page.
page.MasterPageFile = “/_catalogs/masterpage/MyCustom.master”;
}}}
}}
public void Dispose() { /* empty implementation */ }
}
}
it’s important to remember that an HttpModule cannot be deployed in a WSS farm for an individual site collection. Instead, an HttpModule must be configured as an all-or-nothing proposition at the Web application level.
3. Now, sign the project and build it.
4. Drag and Drop the signed assembly in GAC.
5. Next, we need to register this CustomhttpModule in our SharePoint webconfig. To do this add the below under <httpModules> tag in your web app’s web.config fie.
<add name=”CustomHttpModule” type=”SwitchMasterPage.CustomHttpModule,  SwitchMasterPage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7ebdb1031dfc1e406?/>
And you are Done!

Monday, 8 July 2013

Developer Dashboard with powershell command to make it on/Off

One of the new feature in SharePoint 2010 is Developer dashboard. With help of Developer Dashboard we can get view of SharePoint enviroment and find out issues if occuring. This Provides us info about Call Stacks, Web Server, Critical Events, Database Queries, Service Calls, SP Requests, and Webpart Events. This even shows the time being taken to execute any code.

Under Database Calls this will even provide us the hyperlinks. We can click on the link and it will show us a dialog and we can see the SQL commands being Called.



Mode of developer dashboard:
On – creates everytime the output at the end of the page content
Off – switch off developer dashboard and nothing is rendered
OnDemand – creates a DeveloperDashboard icon to make dashboard output visible as needed

How to turn on Developer Dashboard?
Open Sharepoint 2010 Management Shell and type the following commands:

##Turn on
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService 
$dashboard = $contentService.DeveloperDashboardSettings
$dashboard.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::On
$dashboard.Update()

##Turn on Demand Mode
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$dashboard = $contentService.DeveloperDashboardSettings
$dashboard.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::OnDemand
$dashboard.Update()

##Turn Off
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$dashboard = $contentService.DeveloperDashboardSettings
$dashboard.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::Off
$dashboard.Update()

##Turn On demand using stsadm
stsadm -o setproperty -pn developer-dashboard -pv ondemand

SharePoint 2010 Feature Stapling

Feature Stapling allows you to create a feature and then associate it with any site definition without ever touching the site definition files themselves. Your feature will be activated when the site is provisioned.

Stapling basically consist of two features:
  1. Staplee Feature: The feature which will be stapled to an existing site definition
  2. Stapler Feature: The feature which will staple the staplee feature with site definition

Steps

  1. Create new Empty SharePoint Project.
  2. Create staplee feature which we want to get activated on site provisioning.
  3. Create Stapler feature with scope as Farm.
  4. Add new Empy Element "StaplerElementHelper" to the project.
  5. Edit Element.xml file
  6. Add follwing line<FeatureSiteTemplateAssociation Id="d3f566c2-b711-4ddb-808b-c4d0c00dac36" TemplateName="STS#0" />FeatureSiteTemplateAssociation is going to associate our steplee feature with site definition "STS#0"(team site).
    Note: Replace value of Id with your staplee feature ID. You can also specify your own TemplateName.

    your complete file will look like
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/"><FeatureSiteTemplateAssociation Id="d3f566c2-b711-4ddb-808b-c4d0c00dac36" TemplateName="STS#0" />
    </Elements>
  7. Double click your Stapler Feature and Include "StaplerElementHelper" in "Items in feature". Remember it should be included in Stapler feature and not in staplee feature.
  8. Deploy it.

Now whenever you create a new site using site definition specified in FeatureSiteTemplateAssociation staplee feature will automatically get activated.

Sample Project

refer click 

Client Object Model Access Large Lists

If you want retrieve large list using Client Object Model. You can use the ListItemCollectionPosition class to implement paging list item retrieval according to the position of items relative to their collection. Use the RowLimit element to specify the number of items to return per page.

Download Working Example


 static void Main(string[] args)
        {
            ClientContext clientContext = new ClientContext("URL Here");

            List list = clientContext.Web.Lists.GetByTitle("Tasks");

            ListItemCollectionPosition itemPosition = null;
            while (true)
            {
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ListItemCollectionPosition = itemPosition;
                camlQuery.ViewXml = @"<View>
                                        <ViewFields>
                                          <FieldRef Name='Title'/>
                                        </ViewFields>
                                        <RowLimit>1</RowLimit>
                                      </View>";

                ListItemCollection listItems = list.GetItems(camlQuery);
                clientContext.Load(listItems);
                clientContext.ExecuteQuery();
                
                itemPosition = listItems.ListItemCollectionPosition;
                
                foreach (ListItem listItem in listItems)
                    Console.WriteLine("Item Title: {0}", listItem["Title"]);
                
                if (itemPosition == null)
                    break;
                
                Console.WriteLine(itemPosition.PagingInfo);
                Console.WriteLine();
            }

            Console.ReadLine();
        }

C# code to create Terms and Term Set programmatically (using code)?

Add reference of "Microsoft.SharePoint.Taxonomy" assembly to your project. Include namespace "Microsoft.SharePoint.Taxonomy". And use the code as listed below.


 using (SPSite site = new SPSite("Site URL"))
            {
                TaxonomySession _TaxonomySession = new TaxonomySession(site);

                //Get instance of the Term Store 
                TermStore _TermStore = _TaxonomySession.TermStores["My Term Store"];

                //Now create a new Term Group
                Group _Group = _TermStore.CreateGroup("My New Group");

                //Create a new Term Set in the new Group
                TermSet _TermSet = _Group.CreateTermSet("My New Termset");

                //Add terms to the term set
                Term _term1 = _TermSet.CreateTerm("First Term", 1033);
                Term _term2 = _TermSet.CreateTerm("Second Term", 1033);
                Term _term3 = _TermSet.CreateTerm("Third Term", 1033);
                Term _term4 = _TermSet.CreateTerm("Last Term", 1033);

                //commit changes
                _TermStore.CommitAll();

            }

C# code to create SharePoint Views (SPView) Programmatically

SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["My List"];

SPViewCollection allListViews = list.Views;
string viewName = "My New View";

StringCollection newviewFields = new StringCollection();
viewAllContactFields.Add("Edit");
viewAllContactFields.Add("LinkTitleNoMenu");
viewAllContactFields.Add("Field1");
viewAllContactFields.Add("Field2");
viewAllContactFields.Add("Field3");


string myquery = "<OrderBy><FieldRef Name='LinkTitle' Ascending='TRUE' /><FieldRef Name='EffectiveDate' Ascending='TRUE' /></OrderBy>";

allListViews.Add(viewName, newviewFields, myquery, 30, true, false);

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; }
        }


    }
}

Client Object Model Exception Handling Scope

When we perform the operations on client side, we need to make a require to execute some operations that depend on the presence of an exception or not. We all have used try and catch blocks so far.
Lets take an example to understand: if you want to access a specific list in the SharePoint 2010 site in order to modify its property to allow Folder creation and versioning.

public void AllowFolderAndVersionCreation(string listName)
        {
            ClientContext context = new ClientContext("
http://anmol-pc");
            using (context)
            {
                List myList = null;
                try
                {
                    myList = context.Web.Lists.GetByTitle(listName);
                    context.Load(myList);
                    context.ExecuteQuery();

                }
                catch
                {
                    ListCreationInformation info = new ListCreationInformation();
                    info.Title = listName;
                    info.TemplateType = (int)ListTemplateType.GenericList;

                    myList = context.Web.Lists.Add(info);
                    context.ExecuteQuery();
                }
                finally
                {
                    myList.EnableVersioning = true;
                    myList.EnableFolderCreation = true;
                    myList.Update();
                    context.ExecuteQuery();
                }

            }
        }



Issue with Try and Catch Block
If you see the above i am first trying to get a list by Title in try block, and if list not found in catch block i tried to create a new list and Then in finally block i updated "EnableFolderCreation", "EnableVersioning" properties of list. To acheive this I require to send three commands to the server. So in SharePoint 2010 Client Object Model it is not convenient to use the try and catch blocks in the operations. The reason why is very easy to understand: we are in a client-side context and we have to pay attention to the number of queries to the server in order to execute our operations.

How ExceptionHandlingScope comes to rescue?
SharePoint 2010 Client object Model provides a class ExceptionHandlingScope for exception management. It exposes basic four methods StartScope(), StartTry(), StartCatch() and StartFinally().
Exception Handling scope begins with Startscope() and other three as three difrent sections inside

 public void AllowFolderAndVersionCreation(string listName)
        {
            var context = new ClientContext("
http://anmol-pc");
            var _ExceptionHandlingScope = new ExceptionHandlingScope(context);

            using (_ExceptionHandlingScope.StartScope())
            {
                using (_ExceptionHandlingScope.StartTry())
                {
                    // the code you want to try
                }
                using (_ExceptionHandlingScope.StartCatch())
                {
                    //code to run on error
                }
                using (_ExceptionHandlingScope.StartFinally())
                {
                    // the code that will execute finally
                }

           }
    }

lets place our example code inside this structure


public static void AllowFolderAndVersionCreation(string listName)
        {
            var context = new ClientContext("
http://anmol-pc");
            var _ExceptionHandlingScope = new ExceptionHandlingScope(context);
            List myList = null;

            using (_ExceptionHandlingScope.StartScope())
            {
                using (_ExceptionHandlingScope.StartTry())
                {
                    myList = context.Web.Lists.GetByTitle(listName);
                    context.Load(myList);
                    // context.ExecuteQuery() not required here
                }
                using (_ExceptionHandlingScope.StartCatch())
                {
                    ListCreationInformation info = new ListCreationInformation();
                    info.Title = listName;
                    info.TemplateType = (int)ListTemplateType.GenericList;
                    myList = context.Web.Lists.Add(info);
                    // context.ExecuteQuery() not required here
                }
                using (_ExceptionHandlingScope.StartFinally())
                {
                    myList.EnableVersioning = true;
                    myList.EnableFolderCreation = true;
                    myList.Update();
                    // context.ExecuteQuery() not required here
                }
            }
            context.ExecuteQuery();
        }


So you can notice that same thing can be acheived using ExceptionHandlingScope using less calls to the server.

Use of the "Try and catch" block:
  • Definetly more than 1 call
  • The debug operations are more complicated.
  • Easily understandable code as we are known to this type of code.
Use of the "ExceptionHandlingScope" class:
  • With one call to server we can acheive our goal.
  • The debug operations are much easier.
  • The code may not look that clear.

Way of Safe Control Entries in Web Config File from code

There may come a situation where we want to add a custom new safe control entry in web.config file. 

Create New Empty SharePoint Project.

Add new "Empty Element" in project.

Select the newly created element and press F4 to open properties window.

Click ellipse button against the "Safe Control Entries" property as shown in below image.


The safe control entry dialog opens as shown below.

Click "Add" This will add a new safe control entry. Set properties 
Name: name of safe control entry
Assembly: A strong assembly name, such as: MyFirstProject.MyFirstAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=11e9bce111e9418c.
NameSpace: The fully-qualified namespace for the class/control
Safe: True

Add as many entries as you like.

Thursday, 4 July 2013

Default Sharepoint Notifications setting from UI



1.JPG

Assuming that your 'Notifications' list has the following items in it.

2.JPG

Creating New Notifications

Power users or site collection admins can use this simple custom application page to create new notifications and assign to users or SP groups.

6.JPG
3.JPG

Mark As Read functionality

Also, when your users read a message and close them by clicking little 'x', that message is 'marked as read' and won't be displayed next time user visits the page.

4.JPG

5.JPG

How to use Notifications in SharePoint 2010

In SharePoint 2010, Notifications is another way to display information/warnings without distracting user. It'll be shown in top right below Topbar and Ribbon. Just like Status bar, No Server side code or manual setup required to use Notifications. The required functions are bundled in SP.UI.Notify class that defined in SP.Js/SP.Debug.Js and it's included in SharePoint master page. So no manual include of Js is required.

Well, Status bar is used to display content and to hide developer has to invoke RemoveStatus or RemoveStatusAll Method, whereas Notifications by default getting hide after few seconds. It's possible to make notifications Sticky(stay until closed by code).

SP.UI.Status Notify
The SP.UI.Notify class has 2 functions. They are
  1. SP.UI.Notify.addNotification(strHTMLContent, boolIsSticky) This function used to display specified content in Notification area. The parameters are self explanatory. boolIsSticky parameter specifies whether this content should be shown as sticky(true) or hide after few seconds(false). It's possible to show multiple Notifications at a time and they getting aligned themselves.
  2. SP.UI.Notify.removeNotification(strNotifyID) This function hides the Notification that passed as parameter.
Sample Code
<
Script type="text/javascript">
var
strNotificationID, strStickyNotificationID;

function showNofication()
{
  strNotificationID = SP.UI.Notify.addNotification(
"Quick Info : <font color='#AA0000'>Registration in Progress..</font> <img src='/_Layouts/Images/kpiprogressbar.gif' align='absmiddle'> ", false);
  

strStickyNotificationID = SP.UI.Notify.addNotification("Sticky Notes : <font color='#AA0000'>Welcome to My World.</font> <img src='/_Layouts/Images/lg_ICPINNED.gif' align='absmiddle'> ", true);
}

function removeNofication()
{
 
if (strStickyNotificationID != null)
    SP.UI.Notify.removeNotification(strStickyNotificationID);
}
</Script>

<
div class="ms-toolpanefooter">
  <
input type="button" onclick="Javascript:showNofication();" value="Show Nofitication" class="UserButton" />
 
<input type="button" onclick="Javascript:removeNofication()" value="Remove Nofitication" class="UserButton" />
</div>
Notifications

Step by Step SharePoint Server 2010 Installation Guide

Introduction

This article provides a step by step Installation and Prerequisites Software requirement for SharePoint server 2010 beta installation.
Finally! My long awaited SharePoint Server 2010 beta is ready for download… (http://technet.microsoft.com/en-us/evalcenter/ee391660.aspx) I installed it successfully on VMWARE Workstation, alternatively you can use VirtualBox.
Given below is a step by step Installation guide.

List of Prerequisites Software

  1. Windows server 2008 with SP 2 / Windows 7 / Vista (All OS must be 64bit)
  2. Windows 2008 R2 and Windows Server 2008 KB971831
  3. WCF Fix article for Windows 2008 R2 and Windows 7 KB976462
  4. Microsoft SQL Server 2008 Native Client
  5. Microsoft "Geneva" Framework Runtime
  6. Microsoft Sync Framework Runtime v1.0 (x64)
  7. Microsoft Chart Controls for Microsoft .NET Framework 3.5
  8. Microsoft SQL Server 2008 Analysis Services ADOMD.NET
  9. PowerShell V2 RTM
  10. SQL Server 2008 SP1
  11. .NET Framework 3.5 Service Pack 1 (Full Package) KB959209 KB967190

Installing OS on VMWARE Workstation 7.0

Installing Windows Server 2008 with SP2 on VMWARE Workstation 7.0 may prompt the following error:
“You have configured this virtual machine as a 64-bit guest operating system…”
image
By default, Lenovo T61 laptop’s ship with virtualization technology and set VT is disabled.
In order to enable VT on laptop, please shut down your laptop and go to BIOS setup > CPU > Virtualization technology > Enable and Press F10 to Save and Exit.
Install Windows server 2008 with SP 2.
Windows 2008 x64 Install
Download prerequisites software (if you need to share your PC folder to access from VMWARE) enable Share folder option:
image
Go to VM > Setting > Options > Shared Folder > Enable and Select your Pre-request software download folder.
image
Run > SharePoint Server 2010 Application file, system will extract files and show the above screen, under Install > click Install Software prerequisites…
image
image
System will run for few minutes and display the following error message:
image
Install your prerequisites software that you downloaded one by one (if possible, follow the above order as shown in the error message).
Note: If you try to install Hotfixes from your Share Folder system may prompt “error code 0x80070003” please copy your hotfix files to Windows server and click Install.
image
Once you get the above screen “Installation Complete”, click "Install SharePoint Server” link:
image
SharePoint 2010 Installation screen prompts for Product Key get beta key from here
image
Read your License terms and click I accept and start Installation:
image
Select Standalone option, if you are installing with SQL Express 2008 server. If you are installing SQL Server 2008 and SharePoint 2010 farm servers, then select Server Farm option. Since I am using VMWARE installation, I select Standalone option.
image
System will start the Installation progress…
image
System would take several minutes to complete installation and prompt for Configuration Wizard.
image
Run your Configuration wizard and click next >
image
Step 2 on Configuration wizard click “Yes” to start IIS and SharePoint Admin, Timer service.
image
Configuration wizard continue 2 of 10 tasks and if everything is ok, the system will display the following screen. (Please note that it will take several minutes to complete. It's not as fast as SharePoint 2007 configuration wizard)
image (
Congratulations… you successfully Installed SharePoint 2010.
System will launch SharePoint 2010 Central Administration screen…
SharePoint CA
Enjoy… and provide me your feedback…

Ads