CodePlex project uploaded: SharePoint 2010 Conditional Lookup Control

I’ve created a custom control for SharePoint 2010. This control let you connect two lookup fields so that the second lookup field contains only a subset of all values depending on the selected value of the first lookup field.

The control can handle both rendering methods of SharePoint for lookup fields: If there are more then 20 items in a lookup dropdown it will be rendered alternatively as input text box and not as input dropdown…

But… It’s alpha!!!

See: http://spconditionallookup.codeplex.com

Some Screenshots…

This is the demo list where you start using the demo.

image

Add a new item. You see two input controls. Both are empty.

image

Now you open the dropdown list of the first field:

image

There are values in Winking smile – Leave it on “(none)” for now.

Open the dropdown of the second field:

image

Its empty Smile

Now select the value “List1-Value1” in the first dropdown.

image

Now open the second dropdown. Now there are values in there Smile :

image

The second dropdown was filled with values depending on the selected value of the first dropdown.

Lets have a look behind the scene.

Open the List “This list defines the value dependencies between the main list and the conditional list”:

image

This list defines the values for the second dropdown depending on the values of the first dropdown.

For value “List1-Value1” you’ll find there 4 values:

image

Lets have a look into the project:

image

The Test project has 4 SharePoint List definitions… “List 1” is the “main list” and “List 3” is the “conditional list”. “List 2” will contain the items you create. “RefList” contains the dependencies between “List 1” and “List 3”.

“List 2” contains to custom list forms:

image

“New2” is used to create new items, “Edit2” is used to edit items.

Lets have a look into “New2”. There are only a few customizations for using the Conditional Lookup control.

image

This references to the input fields “ff1” and “ff2”:

1:                             <tr> 
2:                                 <td> 
3:                                     <table  border="0"  cellspacing="0"  width="100%"> 
4:                                         <tr> 
5:                                             <td  width="190px"  valign="top"  class="ms-formlabel"> 
6:                                                 <h3  class="ms-standardheader"> 
7:                                                     <nobr> Reference (lookup) to the main list </nobr> 
8:                                                 </h3> 
9:                                             </td> 
10:                                             <td  width="400px"  valign="top"  class="ms-formbody"> 
11:                                                 <SharePoint:FormField  runat="server"  ID="ff1"  ControlMode="New"  FieldName="List2RefToList1FieldA"  /> 
12:                                                 <SharePoint:FieldDescription  runat="server"  ID="ff1description"  FieldName="List2RefToList1FieldA" 
13:                                                     ControlMode="New"  /> 
14:                                             </td> 
15:                                         </tr> 
16:                                         <tr> 
17:                                             <td  width="190px"  valign="top"  class="ms-formlabel"> 
18:                                                 <h3  class="ms-standardheader"> 
19:                                                     <nobr> Reference (lookup) to the conditional list</nobr> 
20:                                                 </h3> 
21:                                             </td> 
22:                                             <td  width="400px"  valign="top"  class="ms-formbody"> 
23:                                                 <SharePoint:FormField  runat="server"  ID="ff2"  ControlMode="New"  FieldName="List2RefToList3FieldA"/> 
24:                                                 <SharePoint:FieldDescription  runat="server"  ID="ff2description"  FieldName="List2RefToList3FieldA" 
25:                                                     ControlMode="New"  /> 
26:                                             </td> 
27:                                         </tr> 
28:                                         <tr  id="idAttachmentsRow"> 
29:                                             <td  nowrap="true"  valign="top"  class="ms-formlabel"  width="20%"> 
30:                                                 <SharePoint:FieldLabel  ControlMode="New"  FieldName="Attachments"  runat="server"  /> 
31:                                             </td> 
32:                                             <td  valign="top"  class="ms-formbody"  width="80%"> 
33:                                                 <SharePoint:FormField   runat="server"  ID="AttachmentsField"  ControlMode="New"  FieldName="Attachments"/> 
34:                                             </td> 
35:                                         </tr> 
36:                                     </table> 
37:                                 </td> 
38:                             </tr> 
39: 
40: 

Read and write User Profile Properties of SharePoint 2010 User Profile Service Application with PowerShell

I needed to change some properties of user profiles of my SharePoint 2010 farm.

Of cource I wanted to do this with PowerShell!

Before you can execute the following script, be sure that your user account is “Admin” on your “User Profile Service Application” and has “Full Control” permissions on the same Service App! – You may get this error: New-Object : Exception calling ".ctor" with "1" argument(s): "No User Profile Application available to service the request. Contact your farm administrator." – You can verify or change this settings in the Central Administration –> Manage Service Applications –> (select User Profile Service Application) –> than:

  1. Click “Administrators” –> Add the user that will execute the PowerShell script –> Set “Full Control” for this user –> Click “OK”
  2. Click “Permissions” –> Add the user that will execute the PowerShell script –> Set “Full Control” for this user –> Click “OK”

So…

Here is the Script for reading properties from the profile system:

#region Check x64 host
if( [System.IntPtr]::Size -ne 8) {
  Write-Error "Please use a x64 PowerShell host!"
  return
}
#endregion

#region Load SharePoint SnapIn and DLL
  Remove-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  
  [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null    
  
  #Check available SharePoint Cmdlets
  if( (Get-Command -Noun SPWeb*) -eq $null ) {
    Write-Error "SharePoint SnapIn not loaded. SharePoint cmdlets missing!"
    return
  }
#endregion

#User must be set as Full Control *Admin* and with Full Control *Permission* on Central Admin->Manager Service Application->User Profiler Service App!!

$site=(Get-SPSite "http://sharepoint.local")
$sc = [Microsoft.Office.Server.ServerContext]::GetContext($site)

$upm = New-Object "Microsoft.Office.Server.UserProfiles.UserProfileManager" -ArgumentList ($sc)
$enumerator = $upm.GetEnumerator()
$enumerator.Reset()
while( $enumerator.MoveNext() -eq $true ) {
  $currentUserProfile = $enumerator.Current
  $propertiesCollection = $currentUserProfile.ProfileManager.PropertiesWithSection
  if( $currentUserProfile -ne $null -and $propertiesCollection -ne $null ) {
    foreach($p in $propertiesCollection) {
      Write-Output $p.Name $currentUserProfile[$p.Name].Value
    }
    
    #write to a property:
    #$currentUserProfile["FirstName"].Value="Test"
    #$currentUserProfile.Commit()
  }
}

If you need to write property values than uncomment the two lines on the bottom of the script and change them.

BE VERY CAREFULLY!!!!

You can damage your profile system if you do things wrong! – Be sure that your script will only change one property for one user. If you uncomment the script lines above this script would set the property “FirstName”  of every user  to value “Test”!!! – BE VERY, VERY CAREFULLY!!!

Walkthrough: Create Form with InfoPath and use it in a SharePoint 2010 Form Library

In this walkthrough I want to show you the steps for creating a InfoPath form and use it with InfoPath Forms Services of SharePoint 2010.

1. First I downloaded a downloadable InfoPath form from Microsoft: http://office.microsoft.com/en-us/templates/new-travel-client-preference-form-TC001201306.aspx – It’s called “New travel client preference form”.

2. I create a document library where I store my InfoPath template(s).

image

image

3. Open InfoPath Designer. Open the downloaded InfoPath form (see step 1).

image

4. Go to “File” menu.

=> Click “Publish your form”

=> On the first time you will be redirected to “Publish” sub menu.

=> On “Publish” menu: Click “Quick Publish” or “SharePoint Server”

image

A wizard starts…

On the first page enter the URL of the destination site.

image

On the second page I choose “Site Content Type”. => So you can use the form on multiple lists.

image

Create new Content Type.

image

Enter the name of the Content Type.

image

Specify the location where the form template will be saved. This URL will be used for the Content Type. You know: A Content Type can have a document template setting that is used to create new items (documents) based on this Content Type. The URL will be stored in the Content Type.

image

image

Add all form columns to the resulting Content Type. This columns will be available in the SharePoint list items that represent a saved form. (Here I choose some columns for this example…)

image

Now you are almost finished. – Click “Publish”…

image

That’s the result for that:

image

 

4. Go to the browser. Open your SharePoint site.

=> Click “Libraries” in the Quick Launch.

=> Create a new Form Library like this:

image

Click “Library Settings” in the Ribbon.

image

Edit the “Advanced Settings” of the library.

=> Select the option “Allow management of content types?” May be other options. Then save.

image

Now edit the Content Types of the library on the “Library Settings” page:

image

=> Press “Add from existing site content types”.

Now choose your previously created content type “TravelPreference”. Then press “OK”.

image

Optional: Remove the standard “Form” content type from the list.

Now it looks like this:

image

 

5. In InfoPath Designer

=> Open the “File” menu.

=> Open the “Info” sub menu.

=> Click “Submit Options”

Choose “To SharePoint Library”

image

In the wizard: Specify the location for saving the filled forms:

image

Go through the next wizard page… Click “Finish”

image

=> Open the “File” menu.

=> Open the “Info” sub menu.

=> Click “Form Options”

Open “Compatibility” tab. Choose Form Type “Web Browser Form” and enter the site URL:

image

Click OK.

The “Design Checker” will open. There are some problems in the form:

image

This results in setting the form type to “Web Browser Form”: Such a form does not have some features. – Now remove the fields from the form…

Click “Refresh” in the “Design Checker” pane.

Now there’s only a warning. You can ignore this.

image

=> Open the “File” menu.

=> Open the “Info” sub menu.

Click “Quick Publish”

image

That’s it:

image

 

6. Go to the browser. Open your SharePoint site. Open your “TravelPreferences” list.

=> Click “Add new document”

NOW YOU’LL GET YOUR BROWSER FORM!!!

Fill it out!

Click “Submit” (NOT: “Save” => You can disable the “Save” button in InfoPath Designer => “File” menu => “Info” pane => “Advanced form options” => “Web Browser” tab)

After clicking “Submit” you’ll get a document in your form library:

image

This can be used with Workflows and any other SharePoint functionality…

Error while enabling Session State Service on SharePoint 2010

There are some mysterios errors on my SharePoint farm. After reading tons of log files I found some hints to problems with the “Session State Service” of SharePoint 2010.

I found this Cmdlets in PowerShell for controlling this service:

Enable-SPSessionStateService 
Disable-SPSessionStateService
Get-SPSessionStateService
Set-SPSessionStateService

I tried to enable the service with the first Cmdlet. – This was the resulting error:

image

Error message: “Microsoft SharePoint Server session state could not find the Session State Service. Contact your farm administrator.”

There is no information about this error in the internet. (Till now Smile )

MY SOLUTION FOR MY PROBLEM (may be it does not help you in your special situation. It’s “experimental”!!!):

I created a PowerShell script for re-creating the Session State Service and its Service Application.

Before you go on: Make sure, the Windows service “ASP.NET State Service” is running. (I set it to start automatically during system startup.)

This is the resulting script:

#region Check x64 host
    if( [System.IntPtr]::Size -ne 8) {
      Write-Error "Please use a x64 PowerShell host!"
      return
    }
#endregion

#region Load SharePoint SnapIn and DLL
  Remove-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  
  #Check available SharePoint Cmdlets
  if( (Get-Command -Noun SPWeb*) -eq $null ) {
    Write-Error "SharePoint SnapIn not loaded. SharePoint cmdlets missing!"
    return
  }
#endregion

cls

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local

$services = $farm.get_Services() #get all SharePoint services
$sessionStateService = ($services | ? { $_.TypeName -like "*session state*" } ) #find the existing Session State Service -> it was "NULL" for me!

if( $sessionStateService -eq $null ) {
    #Recreate the Service
    $newSessionStateService = New-Object Microsoft.Office.Server.Administration.SessionStateService ("", $farm)
    $newSessionStateService.Id = [System.Guid]::NewGuid()
    $newSessionStateService.Name=[String]::Empty
    $newSessionStateService.Update()
    $farm.Update()
    $newSessionStateService.Provision()
    $newSessionStateService.Name=[String]::Empty
    $newSessionStateService.Update()
}

$services = $farm.get_Services() 
$sessionStateService = ($services | ? { $_.TypeName -like "*session state*" } ) 

$servers=(Get-SPServer)

#Create service instances on all application servers of the SharePoint farm
$servers | % {
    if( $_.Role -eq "Application" ) {
      $currentSessionStateSvcOnServer = ($_.ServiceInstances | ? { $_.TypeName -like "*session state*" } ) 
      if( $currentSessionStateSvcOnServer -eq $null ) {
        #write-host $_.Name $server.Role $_.gettype().fullname
        
        #To create a service instance you must use a "protected" constructor
        [type]$t = "Microsoft.SharePoint.Administration.SPServiceInstance" -as "Type"
        $p = @( ("string" -as [Type]), ("Microsoft.SharePoint.Administration.SPServer" -as [Type]), 
                ("Microsoft.SharePoint.Administration.SPService" -as [Type]) )
        $c = $t.GetConstructor([System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance,$null, $p, $null)
        #these are the parameters for creating a service instance by using the protected constructor
        [Object[]]$params = @([Object]"Session State Service Instance", 
                              [Object]([Microsoft.SharePoint.Administration.SPFarm]::Local.Servers[$_.Name]), 
                              [Object]([Microsoft.SharePoint.Administration.SPFarm]::Local.Services[$sessionStateService.Id]))
        $newSvcInstance = $c.Invoke($params)
        #update & provisioning
        $newSvcInstance.Update()
        $newSvcInstance.Provision()
      }
    }
}

if( (Get-SPSessionStateService -ErrorAction SilentlyContinue) -ne $null ) {
  Write-Host "Successfull :-)" -ForegroundColor Green
} else {
  Write-Host "Failed :-(" -ForegroundColor Red
}

After that, the “Enable-SPSessionStateService” works:

image

(Spend me 1 1/2 days.)


You can use this script to delete the Session State Service, e.g. if some script parts does not work as expected. ONCE MORE: USE IT CAREFULLY AND AT YOUR OWN RISK!!!

#region Check x64 host
    if( [System.IntPtr]::Size -ne 8) {
      Write-Error "Please use a x64 PowerShell host!"
      return
    }
#endregion

#region Load SharePoint SnapIn and DLL
  Remove-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  
  #Check available SharePoint Cmdlets
  if( (Get-Command -Noun SPWeb*) -eq $null ) {
    Write-Error "SharePoint SnapIn not loaded. SharePoint cmdlets missing!"
    return
  }
#endregion

cls

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local

Get-SPServiceApplication | ? {$_.GetType().FullName -eq "Microsoft.Office.Server.Administration.SessionStateServiceApplication"} | Remove-SPServiceApplication 

$farm.Services | ? { $_.TypeName -like "*session state*" } | % {
  $_.Instances | % {
    $_.Delete()
  }
  $_.Delete()
}

Enumerate Sharepoint 2010 database in PowerShell

“Is there a way to enumerate all SharePoint 2010 databases in PowerShell like the page /_admin/DatabaseStatus.aspx”>/_admin/DatabaseStatus.aspx”>http://<centra_administration>/_admin/DatabaseStatus.aspx does it??”

YES!

You can use this script:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") 

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local

$type = ('Microsoft.SharePoint.Administration.SPPersistedTypeCollection`1') -as "Type"
$type = $type.MakeGenericType( ("Microsoft.SharePoint.Administration.SPDatabase"as "Type") )
$o = [Activator]::CreateInstance($type, $farm)

$’

Now the variable “o” contains all Database-Objects of your farm!

How to create an instance of an generic class in PowerShell

Sometimes you may need to create instances of generic classes in PowerShell.

Like this (in C#):

 using  System;

 using  System.Text;
 
 namespace  tmp1
 {
     class  Program 
     {
         static  void  Main(string [] args)
         {
             System.Collections.Generic.List<string> t = new  System.Collections.Generic.List<string>();
         }
     }
 }

There is a generic class used in the code above: System.Collection.Generic.List.

If you want to create an instance of this class in PowerShell you can not use this:

New-Object "System.Collections.Generic.List<string>"

You’ll receive an error!

Here is the solution: You can use the System.Type that represents other .NET types.

Use this PowerShell code snipped to create an instance of System.Collections.Generic.List<string>

$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type = $type.MakeGenericType("system.string" -as "Type")
$o = [Activator]::CreateInstance($type)

“$o” will contain the created instance.

You can use this method for all other generic classes.

You may need to change the following details.

  1. In the first line of the snipped there is `+"1" This is the amount of parameters for the generic class.
  2. In the second line you have to specify the parameter types for the generic class. Separate them with “,” and cast them to System.Type by using -as “Type”.
  3. In the third line you may need to specify the constructor parameters for creating an instance of the generic class.

Here is another example:

$type = ("System.Collections.Generic.SortedList"+'`'+"2") -as "Type"
$type = $type.MakeGenericType( @( ("System.Int32" -as "Type"), ("system.string" -as "Type") ) )
$o = [Activator]::CreateInstance($type, 100)
$o.Add(1, "test")
$o

This creates an instance of System.Collections.Generic.SortedList<System.Int32, String> with a starting capacity of 10 (line 3: the second parameter of CreateInstance).

How to determine current PowerShell session is x86 or x64.

For the execution of SharePoint PowerShell scripts I need to check the execution environment of my PowerShell session to be sure that PowerShell runs as x64 application.

This was a problem because PowerShell does not provide this information itself.

BUT PowerShell is a .NET Application.

There you can check for x86 or x64 by using this static method (in C# or VB.NET):

System.IntPtr.Size

In PowerShell syntax:

[System.IntPtr]::Size

This results in “4” for x86 and “8” for x64. (Without question marks of cource. The result type is int.)

So you can use this in your PowerShell script.

Here I started 2 PowerShell sessions: one x86 and one x64. See the result of the command above:

image

(In the window title you see “Windows PowerShell (x86)” –> That’s the x86 session. The x64 session has no special window title.)

Here is a corresponding PowerShell code snipped:

#region Check x64 host
if( [System.IntPtr]::Size -ne 8) {
  Write-Error "Please use a x64 PowerShell host!"
  return
}
#endregion

Forefront Protection 2010 for SharePoint–Error “The SharePoint service is running but the Forefront VSAPI Library is not registered”

 

I got this error in the config tool of Forefront Protection 2010 for SharePoint:

“The SharePoint service is running but the Forefront VSAPI Library is not registered”

image

Here is what I did:

1. Stop running service “Microsoft Forefront Server Protection Controller”

2. Stop running service “Microsoft Forefront Server Protection Controller for SharePoint”

3. Go to your installation directory of Forefront Protection 2010 for SharePoint

4. Run from command prompt: “fsccontroller.exe /disable”

5. Run from command prompt: “fsccontroller.exe /enable”

6. Restart SharePoint Services:

    • SharePoint 2010 Administration
    • SharePoint 2010 Timer

7. Start service “Microsoft Forefront Server Protection Controller for SharePoint”

8. Start service “Microsoft Forefront Server Protection Controller”

9. That’s it. (Do a “Refresh” in the Forefront management console application.)

image

How to set the SharePoint 2010 Enterprise Search Service Application “Default Content Access Account” by using PowerShell

If you want to set the SharePoint 2010 Enterprise Search Service Application "Default Content Access Account" by using PowerShell you can use this script:

$searchapp = Get-SPEnterpriseSearchServiceApplication "Search Service Application"
$c= New-Object Microsoft.Office.Server.Search.Administration.Content($searchapp)
$c.SetDefaultGatheringAccount($crawlUser, (ConvertTo-SecureString $crawlPwd -AsPlainText -force))

($crawlUser is – of cause – the login of the account and $crawlPwd is the password in plain text)

How to set the identity of a SharePoint Windows Service, e.g. “SharePoint Server Search”

I have had the problem to set the SharePoint Sevice Account of "SharePoint Server Search" to a special user account during a automatic setup.

In other words: I want to automate this step:

Central Administration -> Security -> Configure Service Accounts

blog-201011030017

There is no PowerShell command as far as I can see.

You can use this script for this job:

  

$farm =(Get-SPFarm)

$farm.get_Services() | ? { $_.typename -ieq "SharePoint Server Search" } | % {

  $searchservice=$_

  $i = $searchservice.get_ProcessIdentity()

  $i.set_CurrentIdentityType(3)

  $i.set_Username($searchUser)

  $i.Update()

  $i.Deploy()

}