How To: Address SharePoint 2010 people editor issue not clearing

One of the issues my team noticed on one of the recent projects is that SharePoint 2010 people editor control doesn’t get cleared on a post back when instructed to do so.

SharePoint People Editor in my case is defined in a visual web part using the following way:

<SharePoint:PeopleEditor id="PeopleSelector" MultiSelect="true"
  ValidatorEnabled="true" SelectionSet="User,SPGroup" runat="server"/>

To clear the people editor, you would invoke the following code in your event handler, in my case a button:

PeopleEditor picker = PeopleSelector;
picker.Accounts.Clear();
picker.Entities.Clear();
picker.ResolvedEntities.Clear();

If you run above code in the click event of a button and step through it, when you check the values for each of the properties (Accounts, Entities, ResolvedEntities), they’re all cleared, but as soon as the code has executed and the page posts-back – you will see the people editor containing the same values as before you cleared it. We started noticing this behavior after SP2010 SP1 has been applied and even when we applied October 2011 CU, the issue still persisted.

When you look at the page source of the page where the people editor is rendering, PeopleEditor reveals the following, pretty complex, structure:

There are number of hidden variables, one of which is called hiddenSpanData, and contains resolved entities. Also, the DIV highlighted in the image above, contains all of the resolved entities and corresponding HTML to render them. Effectively, if you remove the contents of that DIV, the resolved entities will disappear.

This is exactly what we’re going to do, plus we’ll clear the hidden variable (hiddenSpanData) value to make sure the values are cleared in a helper containers and peopl editor structure has nothing to repopulate the people from.
Naturally, this is a workaround and not a fix to a people editor issue; the hope is that the issue to the people editor control will be resolved soon so when the object properties are cleared, they propagate down and do not re-appear on the page.

For this workaround, we’ll add the following JavaScript code to the top of the page. This code will trigger every time the page refreshes; this means, if you need to trigger it on button click, ensure you call a clearPicker function from below on OnClientClick event of your button or means similar to this.

<script language="javascript" type="text/javascript">
    // this registers clearPicker to run every time the page reloads
    _spBodyOnLoadFunctionNames.push("clearPicker");

    // this is the function that clears the picker and helper variables
    function clearPicker() {

        var control;
        var arr = document.getElementsByTagName("div");
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id.indexOf("upLevelDiv") > 0)
            { control = arr[i]; }
        }
        control.innerHTML = '';

        arr = document.getElementsByTagName("input");
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].name.indexOf("hiddenSpanData") > 0)
            { control = arr[i]; }
        }
        control.value = '';
    }
</script>

That’s it; the upLevelDiv and hiddenSpanData now contains no resolved values and the people editor appears cleared.

Enjoy!

Posted in sharepoint, sharepoint 2010 | Tagged , , | Comments Off

How To: Configure default BCS Service application for SharePoint 2010 web app

In most scenarios, you create a SharePoint web application and then provision service applications. In some odd cases you might need to re-create your web application and now all service applications are not assigned to any default web application.

This is very prominent in case of working with SharePoint 2010 Business Connectivity Services, and when you try to create a site which instantiates external lists you will get an error similar to this:

There is no default Business Data Connectivity Service Proxy
  available for the site collection at URL http://[server name]

You will also get the same error when trying to deploy Visual Studio 2010 solution which provisions external lists.
This can be easily fixed by associating a BCS service application (or any other service applications for that matter) proxy to the SharePoint web application.

1. Navigate to the Central Administration
2. Under Application Management click Manage web applications
3. Select your desired web application and click Service Connections

4. Select service applications you would like to be associated as default to the web application, in our case it’s only BCS service application.

Save your changes and your next deployment should give you no problems at all!

Posted in sharepoint 2010 | Comments Off

How To: Configure SharePoint 2010 BCS connection information with PowerShell

If you worked with BCS in SharePoint 2010 you know that you can configure your BCS models and connection information right in the model configuration file, and that’s something developers will create for you. But once your model has been deployed to the server – all of the configuration information stays there. Some of the model details you can change using SharePoint Designer, some others you just can’t get to.

One of the most common things you’d want to change is connection information for your LOBSystem. There is not SharePoint out-of-the-box UI for it, but thankfully PowerShell can access and change BCS LOB System connection configuration.

Just so we’re on the same page, I assume you already have BCS model installed in your farm. Let’s assume your BCS system instance (LobSystemInstance) has the name of My.Project.BCSInstance; this is important to change in the commands below.

To get your LobSystemInstance value also used in the script below, navigate to Central Administration -> Manage Service Applications -> click Business Data Connectivity Service
-> switch the view to External Systems

In the same screen you will find your External System Name (in our case it’s My.Project.BCSSystem).
To find out External System Instance Name (in my case My.Project.BCSInstance), click on the BCS system name from the screen above and grab a value of External System Instance Name

Also, I assume you’re connecting to a SQLServer machine with the machine name of MySqlserver, you can also change that in the script below.

Open SharePoint 2010 Management Shell and execute the following script, substituting variables with your own.

$lob = Get-SPBusinessDataCatalogMetadataObject
  -BdcObjectType "LobSystem"
  -Name "My.Project.BCSSystem"
  -ServiceContext "http://[site URL]"

$instance = $lob.LobSystemInstances | Where-Object {$_.Name -eq "My.Project.BCSInstance"}

Set-SPBusinessDataCatalogMetadataObject –Identity $instance
  –PropertyName "AuthenticationMode" –PropertyValue "PassThrough"

Set-SPBusinessDataCatalogMetadataObject –Identity $instance
  –PropertyName "RdbConnection Data Source" –PropertyValue "MySqlserver"

Set-SPBusinessDataCatalogMetadataObject –Identity $instance
  –PropertyName "RdbConnection User ID" –PropertyValue "My.Sql.User"

Set-SPBusinessDataCatalogMetadataObject –Identity $instance
  –PropertyName "RdbConnection Password" –PropertyValue "MyPassword#!"

Set-SPBusinessDataCatalogMetadataObject –Identity $instance
  –PropertyName "RdbConnection Integrated Security" –PropertyValue " "

$instance.Update()
$lob.Update()

That’s it – the script above will connect to the BCS system instance and change any provisioned variables with the ones in the script.
Essentially, we’ve updated the connection information to our SQL Server backed BCS connection to use new username and password.

Loooot’s more on BCS configurations with PowerShell you can find in my newly published book!

Enjoy!

Posted in sharepoint 2010 | Tagged , , | Comments Off

Making structural customizations to SharePoint 2010 system pages

In my last post we’ve looked at how you can make changes to your SharePoint 2010 system pages by manipulating CSS for Site and System masterpages.

This approach works as long as you don’t have to introduce new controls to your system pages and manipulate existing controls such as a left nav etc.

If you do need to introduce new .NET controls, you will need to create a new system masterpage for your system pages, which is quite simple. In here we’ll look how to accomplish this with SharePoint Designer 2010.

Open your site in SharePoint Designer 2010; on the left hand side Site Objects menu, click Master Pages.
When presented with a list of available masterpages select v4.master and copy/paste it to the same place. Give it a meaningful name. Navigate back to your site using SharePoint UI, Site Actions -> Site Settings -> Master pages (assuming this is a publishing site).
There you should see your new masterpage under System Masterpages drop down, as shown below

Once applied using the UI above, this masterpage will be used on all system pages and modal dialogs.
At first you won’t notice any differences on your pages until you start modifying the masterpage.

In your SharePoint Designer masterpage view, it’s important to copy v4.master as opposed to some other masterpage available there:

Even though you might be tempted to apply your Site Masterpage for your system sites, you should avoid that since site masterpages may not have all of the required placeholders that system pages require. When a system page tries accessing the placeholder name which is not present on the masterpage it will crash the page with a big error and you don’t want your users to see that.
For system pages, this means that important system function may be broken and users won’t be able to manage certain features on the site.
Therefore, it’s best to get a copy of the existing system masterpage and transfer your customizations to there.

You can use SharePoint Designer 2010 to modify your masterpage; the split view is pretty handy where you can see the code associated to most elements in the preview panel:

Before removing placeholders and elements from the system masterpage, make sure you have tested how all (at least most) system pages look like with those elements removed. If you’re not sure about a meaning of a particular control and how it affects other pages, it’s best to leave it alone or hide it rather than remove it altogether. Adding new controls and markup is easy, just make sure you account for a fact that system masterpages are used in modal dialogs so be sure to test your UI in modals too. If you ‘d like to see how to style modals, check out my previous post here.

Oh, did I mention you can find a lot of handy tips on the subject in my branding book? :)

Enjoy!

Posted in cloud, sharepoint, sharepoint 2010 | Tagged , | 1 Comment

Customizing user interface of SharePoint 2010 system pages

Since SharePoint 2010 system pages are often used by end-users and not just administrators, you might need to customize the user interface of those to match your company’s theme.
As you know SharePoint 2010 has 2 sets of masterpages: System and Site masterpage.
Assuming you’re running a publishing portal, click Site Actions -> Site Settings -> Master page to see where you can set both of the masterpages.
Here, you are likely to have a site masterpage which is custom and a system masterpage which is by default v4.master.
In this article we’re not going to be discussing how to modify your site masterpage, for that you can check out my branding book, instead I’m going to focus on how and when to customize system page maasterpage.
Depending on the type of customization you require for your system pages you may just get away with still using v4.master and applying custom CSS.

If you don’t require any structural changes to system pages to make them appear different than out-of-the-box UI, you can get away with attaching a custom CSS to existing system masterpage.
To do that, you need to create a new CSS file and place it somewhere on the site where it’s accessible to all users. In my case, I’m going to place my CSS file into the Style Library of the root site.

Next, I’m going to Site Actions -> Site Settings -> Master page and connect to my custom CSS as show below:

Any changes applied to this file will take effect on both site and system masterpages.
Here is what I have in my custom CSS fle

.menu-item-text {
 color: red;
}

Resulting in the menu color to change as below:

If you don’t need to make any structural changes to the page such as adding custom controls or removing the menu etc, this approach will work well for you.
Again, any changes made here will apply to all pages that use system and site masterpages. This means that before you release any of your CSS customizations to production, ensure you tested majority of the pages to ensure elements of the page are not distorted or invisible. Take a special care when trying to hide elements on the site.

For example, you might think that hiding left hand side navigation bar is not a big deal; the problem is that some pages, such as People and Groups page (Site Actions -> Site Settings -> People and Groups) uses left hand navigation to ensure you’re adding people to the proper group. If this navugation menu was hidden – this system interface would be pretty much unusable.

So take a special care when hiding elements on the page.
In my next post, I discuss how you can make a bit more significant changes to the look of your pages by using custom system masterpage and it’s own dedicated file.

Posted in sharepoint, sharepoint 2010 | Tagged , | 1 Comment

How To: Set security timeouts in SharePoint 2010 using PowerShell

SharePoint 2010 allows you to set timeout of the user session so that your users are logged out after certain time of inactivity. Also, SharePoint allows you to configure the timeout for the current page state to expire. This is handy for forms which have to be filled within a certain period of time before they expire.

Alternatively, if you want to extend the timeout – you can do that too.

First, let’s take a look at how you can expire page content after a given time using PowerShell:

Open SharePoint 2010 Management Shell as administrator and execute the following:

$SPSite = Get-SPSite("[your site collection]")
$webApp = $SPSite.WebApplication
$webApp.FormDigestSettings.Enabled = $true
$webApp.FormDigestSettings.Expires = $true
$webApp.FormDigestSettings.Timeout = New-TimeSpan -Hours 2 -Minutes 30
$webApp.Update()

This will effectively enable expiration and set page content to expire after users leave it hanging for over 2 hours and 30 minutes.

Also, if you’re using claims authentication and would like for your provider to expire sessions after certain period of inactivity, here is how to do that with PowerShell:

$sts = Get-SPSecurityTokenServiceConfig
$sts.UseSessionCookies = $true
$sts.LogonTokenCacheExpirationWindow = New-TimeSpan -Minutes 5
$sts.Update()

This will set our logon expiration to 5 minutes.

By the way, for more PowerShell goodies be sure to check out my new book

Enjoy!

Posted in sharepoint, sharepoint 2010 | Tagged , , | 1 Comment

How To: Programmatically create new site collections in SharePoint 2010

Provisioning site collections programmatically is a common task implemented in site provisioning workflows and subscription environments.
There are few ways to create new site collection. Naturally, since SPSite object is a child of SPWebApplication you would expect to be able to create new site collection in your code just by adding new item to the SPSite instance. However, in order to be able to add new site collections you are required to have writer rights on the content database.

If you don’t have sufficient right, you will get the following exception in your code:

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

As an alternative to start giving away rights you’re not too sure about you can enable self service site creation on a web application. Self-Service Site Creation allows users with the “Use Self-Service Site Creation” permission to create sites in defined URL namespaces.

First you need to enable this setting in Central Administration otherwise your code will fail.

1. Navigate to Central Administration

2. Under Application Management click Manage web applications
3. Select your desired web application and click the Self service site creation ribbon button.

4. On the modal dialog turn the setting on and save changes.

The you can use the following code in your application to create new site collections:

SPWebApplication webApp = site.WebApplication;
if (webApp.SelfServiceSiteCreationEnabled)
{
    string siteName = "[new site URL]";

    SPWeb web = site.OpenWeb();
    web.AllowUnsafeUpdates = true;
    SPSiteCollection spSites = webApp.Sites;
    SPSite newSite = spSites[0].SelfServiceCreateSite(
    "/sites/" + siteName,
    "[Site Title]",
    string.Empty,
    1033,
    "STS#0",
    site.Owner.LoginName,
    site.Owner.Name,
    site.Owner.Email,
    site.Owner.LoginName,
    site.Owner.Name,
    site.Owner.Email);
}

In here we’re creating a team site STS#0, but you can supply any template, custom or out-of-the-box.

Enjoy!

Posted in sharepoint 2010 | Tagged , | Comments Off

How To: Make your SharePoint 2010 site collection read-only, restrict delete

SharePoint 2010 allows administrators to set certain site collection read only or restrict delete. This is done on a centralized site collection level and has nothing to do with permission assignments on your lists and libraries.

Here is a scenario:
a project represented by a site collection in SharePoint has completed and all of the deliverables must be read only, or new content must not be added only existing one modified.

Let`s take a look how you can implement such lock using PowerShell. Also, for more PowerShell hands on scenarios check out my new book.

From within SharePoint 2010 Management Shell execute the following command to prevent users from adding, updating, or deleting content, basically read-only site collection:

Set-SPSite -Identity "http://myserver/sites/site1" -LockState "ReadOnly"

Now, when you access list item for example and try to edit it – the controls will be greyed out, same goes for when you try adding new item – you’ll get an error right on the new item form.

To make the site collection accessible again call:

Set-SPSite -Identity "http://myserver/sites/site1" -LockState "Unlock"

For the scenario where no new content can be added but existing content modified and deleted, here is the command:

Set-SPSite -Identity "http://myserver/sites/site1" -LockState "NoAdditions"

When users try to add new content, the form will still show but the following error will occur when saving the new item:

0x81020066
Additions to this Web site have been blocked.
Please contact the administrator to resolve this problem.

Lastly, to prevent access to the site use the following command:

Set-SPSite -Identity "http://myserver/sites/site1" -LockState "NoAccess"

Resulting in the following error when site collection accessed:

0x81020071
Access to this Web site has been blocked.
Please contact the administrator to resolve this problem.

To unlock any of the above locks, user the Unlock command above.

Enjoy!

Posted in sharepoint 2010 | Tagged , | Comments Off

How To: Create SharePoint 2010 custom visual webpart properties

If you’ve created SharePoint 2010 classic web parts before, you know that you can easily define custom web part properties which your web part code-behind can consume.

With the popularity of SharePoint 2010 Visual Webpart, you’re probably interested in having custom properties defined there too.
There are few things different about exposing your custom properties in a Visual Web part.

Let’s see the steps involved:

1. Add new or use existing Visual Web Part to your project, in our case called Webpart1

2. Open Webpart1.cs file which will look something like this:

[ToolboxItemAttribute(false)]
    public class Webpart1: WebPart
    {
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/[your ASCX].ascx";
        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);
        }
    }

and add your custom property definition right below the CreateChildControls method, in our case the property will look something like this:

 [WebBrowsable(true),
        Category("Configuration"),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("Friendly Display Name"),
        WebDescription("Values: Whatever value you need)]
        public string PropertyValue { get; set; }

In here, the PropertyValue is the actual variable which will be later consumed by your web part user control.

3. Update your CreateChildControls logic to look like this:

 protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            if (control!= null)
            {
                ((Webpart1UserControl)control).WebPart = this;
            }
            Controls.Add(control);
        }

This piece here will pass in the properties every time the control is reloaded. In here, the only change you’ll need to make is rename Webpart1UserControl to the [name of your webpart]UserControl. This will reference the ASCX used for Visual Webpart.

4. Switch to your user control … Webpart1UserControl.ascx.cs
and define public variable right below the class declaration:

public Webpart1 WebPart { get; set; }

In here the Webpart1 is referencing the actual web part class file (not ASCX).
That’s all, in your code you can get a hold of the web part property value by using this: this.WebPart.PropertyValue, where the PropertyValue is the name of the variable we’ve chosen earlier.

Enjoy!

Posted in sharepoint, sharepoint 2010 | Tagged , | Comments Off

New Book is out: Microsoft SharePoint 2010 and Windows PowerShell 2.0: Expert Cookbook

Today my new book is out on amazon and directly from the publisher! Yes, Kindle too!

This new book continues on from my series of developer focused books; this time I focus on all the gotchas related to automating your deployments and configuration with SharePoint 2010 solution/service administration using PowerShell.

What you will learn from this book?

1. Automate your SharePoint 2010 custom solution deployment by using a robust PowerShell script

2. Master the management of SharePoint lists and list settings with PowerShell

3. Simplify SharePoint server management by using PowerShell for tasks like web application settings, configuration and monitoring, sandbox features and more

4. Get to the bottom of administering Business Connectivity Services (BCS) in SharePoint

5. Configure SharePoint FAST Search using PowerShell including audience targeting and improving search results

6. Get the most out of document and records management in SharePoint 2010 by automating configuration

7. Go further with PowerShell to create your own PowerShell commands (CMDLETs) and snap-ins and share them with your team

And there you have it … now you’ve got access to all I know about automating your SharePoint 2010 solutions with PowerShell!

Posted in About, sharepoint 2010 | Tagged , , | Comments Off