Microsoft Technology, .Net, BizTalk, Sharepoint & etc.

Liedong(Ken) Zheng, Senior SharePoint Developer at SIMPLOT

Archive for October, 2009

“The type or namespace ” does not exist in the class or namespace ” (are you missing an assembly reference?)” in SmartPart Sharepoint

Posted by ken zheng on October 29, 2009

Sometime you get this error when you deployed a web part which use references. To fix the problem, you need to open your aspx page and add references like , even you are not useing it in your UI

Posted in Sharepoint | Tagged: , , | Leave a Comment »

Install TFS 2010 Beta 2

Posted by ken zheng on October 27, 2009

Finally today, I managed to install TFS 2010 on my virtual pc which is server 2008 with SharePoint 2007. The erors I got is all aournd permission. So you need to make sure your SharePoint Service and Application Pool use domain account. There are 2 problems I had;
1. Ther error happens when configure the TFS.
TF255275: The following Web service for SQL Server Reporting Services could not be accessed: http:///ReportServer/ReportService2005.asmx.
To fix this error, you will need to remove the ReportServer and ReportServerTempDb database from the database server, see here for more details.
2. Grant TFS permission to SharePoint. This is a permission problem. I will need to change all my sharepopint service to run under domain account. See here

Posted in Sharepoint | Leave a Comment »

Visual Studio 2010, Fx 4 Beta 2 Training Kit

Posted by ken zheng on October 27, 2009

I believe you have notice vs 2010 beta 2 is available for download http://www.microsoft.com/australia/visualstudio/default.mspx.

There is a great set of training resources for Visual Studio 2010 & Fx 4 Beta 2 in the form of the Visual Studio 2010 and .NET Framework 4 Training Kit and check out http://channel9.msdn.com/learn/ for more great learning materials.

You’ll find material covering

1. What’s new for Common Language Runtime
2. ASP.NET 4
3. Windows
4. Windows Workflow
5. Windows Communication Foundation
6. Silverlight
7. Data Access
8. Parallel Computing
9. Extensibility Framework
10. Application Lifecycle Management

so check it out and get up to speed fast with the Visual Studio 2010 and Fx 4 Beta 2!!

Posted in vs2010 | Tagged: , | Leave a Comment »

Purging a SharePoint Document Library using Powershell!

Posted by ken zheng on October 22, 2009

The followong script is to recursively remove documents from a library only. A few examples for Announcement from here.

To remove the items just uncomment the $items | % { $_.Delete() }

    #Start-Transcript ‘c:\powershell\logs\transcript.txt’
    [System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
	$weburl = "http://winsvr2008/kenny"
	$contenttype = "Document"
    $site = new-object Microsoft.SharePoint.SPSite($weburl)
    $web = $site.OpenWeb()
    $list = $web.Lists["Test Doc"]

	# $list | foreach { $_.Items | select Name, ContentType }

    $caml='<Where><Eq><FieldRef Name="ContentType" /><Value Type="Text">'+ $contenttype + '</Value></Eq></Where>'

    $query=new-object Microsoft.SharePoint.SPQuery
    $query.ViewAttributes = "Scope='Recursive'"
    $query.Query=$caml 

    $items=$list.GetItems($query)

    # Pipe results to a loop and delete each element

    #$items | % { $_.Delete() }
	$items.Count
	$items |  select Name 

    $web.Dispose()
    $site.Dispose()
    #Stop-Transcript

Posted in PowerShell, Sharepoint | Tagged: , | Leave a Comment »

SharePoint Powershell Script Examples

Posted by ken zheng on October 22, 2009

PowerGUI is a great tool to write scripts. I just play around the PowerShell script and add here for furture reference:

The first step in connecting to SharePoint is to load the necessary .Net library. This can be done with the following command:

[system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint")
$site = New-Object Microsoft.SharePoint.SPSite("http://adbmoss")

# Connect to the site collection http://adbmoss and store the object in the $site variable

$site | get-member

# Display all the properties and methods for the object in $site

$site.set_readonly($True)

# Set the site collection to read only. No updates are allowed

$site.set_readonly($False)

# Set the site collection back to read-write

$root = $site.rootweb

# Connect to the root site in the site collection and store the object in $root

$root | get-member

# Display all the properties and methods for the object in $root

$root.lists | format-table -property title, author

# Display title and authors for all the lists in the root site

$root.lists | ?{$_.iscatalog -eq $null} | format-table -property title, author

# Filter the lists to show only the user lists. The $_ symbol refers to the object in the piple line. The ? symbol is an alias for the where-object commandlet.

$root.listtemplates | format-table -property name

# Show all the available list templates for the root web

$TempCal=$root.listtemplates["Calendar"]

# Store the Calendar template in a variable $TempCal

$root.lists.add("Events","Company Events", $tempCal)

# Create a list called “Events” with Description “Company Events” on the calendar template

import-csv dept.csv | %{$root.lists.add($_.Dept, $_.Descr,$root.listtemplates[$_.Temp])}

# Create a new list for ever line in a CSV file where the name for the list is saved in the Dept column of the file, the description is in the Descr column, and the type of list to create is in the Temp column. First check that the lists are correctly created before you continue. The % symbol is an alias for the foreach-object commandlet and places each instance of the collection in the pipeline one after the other.

import-csv dept.csv | %{$root.lists[$_.Dept].delete()}

# Use the CSV file again to delete all the create lists again.

You can user PowerShell to provision additional columns in a custom list as well. The following commands show how to accomplish that.

[system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint")

# Load SharePoint library

$site = New-Object Microsoft.SharePoint.SPSite("http://adbmoss")

# Connect to the site collection http://adbmoss and store the object in the $site variable

$root = $site.rootweb

# Connect to the root site in the site collection and store the object in $root

$root.lists.add("CTest","Custom Test",$root.listtemplates["Custom List"])

# Create a new list called “CTest” from the template “Custom List”

$list = $root.lists["CTest"]

# Set a variable $list to the custom list that was just created.

$list.fields.add("T1","Text",0)

# Create a new field of type Single Line Text with the name of “T1”. The field is not required (last parameter)

The scenario below was that the documents were already in the library and they had a spreadsheet with the id number of the document and some additional meta-information. This can also be done in PowerShell. The first step is to save the spreadsheet in CSV format or any other format that PowerShell can easily import. The following code shows how to go about importing the metadata.

[system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint")

# Load SharePoint library

$site = New-Object Microsoft.SharePoint.SPSite("http://adbmoss")

# Connect to the site collection http://adbmoss and store the object in the $site variable

$root = $site.rootweb

# Connect to the root site in the site collection and store the object in $root

$docs = $root.lists["Shared Documents"]

# Store the Shared Documents document library in a variable $Docs

import-csv DocProps.CSV | %{$item = $Docs.items[$_.id]; $item["Title"] = $_.Title; $Item["Group"] = $_.group; $Item.Update()}

# Loop through the csv file and update the properties

The last line of the code is quite complex, so what it means are:

import-csv DocProps.CSV # Import the data from the DocProps CSV file

    | # Pipe the results to the group

         %{ # For each (%) line in the csv file do begin ({)

                $item = $Docs.items[$_.id]; # set the variable $item to the entry in the list where the id corresponds to the id column in the file. The semicolon (;) indicates the separate command is to follow

                $item["Title"] = $_.Title; # set the title of $item to Title in the file

                $Item["Group"] = $_.group; # set the Group metadata property to the group Column in the file

                $Item.Update() # update the entry $item in the list

              } # End (}) the loop

Posted in PowerShell, Sharepoint | Tagged: , | Leave a Comment »

please wait while the installer determines …

Posted by ken zheng on October 21, 2009

Windows Installer doesn’t finish determining disk space requirements, you can run the following command for installation.

msiexec /package /qr

Posted in Handy Tips | Tagged: | Leave a Comment »

“The security validation for this page is invalid” or “Access Denied” in SharePoint

Posted by ken zheng on October 21, 2009

Every time I executed the code, some error came up. Most of the time, it was either “Access Denied” or “The security validation for this page is invalid”.

I ran the code using RunWithElevatedPrivileges, but that didn’t help much. Neither did the SPWeb.AllowUnsafeUpdates property.
Now the below code to rescue me:

SPSite.WebApplication.FormDigestSettings.Enabled = false

But you will have to use it in RunWithElevatedPrivileges scope:

public void EditSecurity()

{

    SPSecurity.RunWithElevatedPrivileges(delegate()

    {

        using (SPSite site = new SPSite(url))

        {

            using (SPWeb web = site.OpenWeb())

            {

                SPWebApplication webApp = web.Site.WebApplication;

                webApp.FormDigestSettings.Enabled = false;

                web.AllowUnsafeUpdates = true;

                SPGroup group = web.SiteGroups["groupname"];

                SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);

                SPRoleDefinition roleDefinition;

                roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor); // Gets a predefined role definition

                roleDefinition = web.RoleDefinitions["customRole"]; // Gets a custom defined role definition

                roleAssignment.RoleDefinitionBindings.Add(roleDefinition);

                web.RoleAssignments.Add(roleAssignment);

                web.Update();

                web.AllowUnsafeUpdates = false;

                webApp.FormDigestSettings.Enabled = true;

            }

        }

    });

}

Posted in Sharepoint | Tagged: , | Leave a Comment »

Using SPWeb.EnsureUser(loginName) to add a new SPUser to a web

Posted by ken zheng on October 21, 2009

To add new user to the web is very common process but fails most time. See http://sharepointsearch.com/cs/blogs/sharepointblogs/archive/2007/12/20/using-spweb-ensureuser-loginname-to-add-a-new-spuser-to-a-web.aspx for more details.
The way to solve this problem is to user SPWeb.EnsureUser(loginName).The description in the SDK for EnsureUser is:
“Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.” Which happens to be exactly what we want!
Now we can finish our code:

   SPUser newUser = newWeb.EnsureUser(@"domain\username");
   newWeb.AllowUnsafeUpdates = true;

   // Create the new roleassignment that we want to add to the collection of roleassignments of the new web
   SPRoleAssignment roleAssignment = new SPRoleAssignment(newUser);
   SPRoleDefinitionBindingCollection roleDefBindings = roleAssignment.RoleDefinitionBindings;
   // Add the binding to the correct roledefinition to the roleassignment
   // This can also be Contribute for contributor rights.
   // Keep in mind that in sites in other languages this needs to be translated
   roleDefBindings.Add(roleDefinitions["Read"]);
   roleAssignments.Add(roleAssignment);

   newWeb.AllowUnsafeUpdates = false;

   newWeb.Dispose();
   portalSite.Dispose();

Posted in Sharepoint | Tagged: , | Leave a Comment »

Infopath cannot find access the specified web service descript

Posted by ken zheng on October 20, 2009

I saw this error when my infopath form trying to access web service in the SharePoint “_vti_bin/xxx/”. To solve the problem, open your iis and go to your sharepoint web -> _vti_bin then make sure xxx is a application not a folder,.

Posted in Sharepoint | Tagged: , | Leave a Comment »

Code to create a SharePoint list with predefined permission

Posted by ken zheng on October 19, 2009

This is just a sample code for me to create a list with a predefined permission

private void SetPermissionsForTheList(SPList selectedList)
{
          // breaks the inheritance from the parent
         selectedList.BreakRoleInheritance(true);

		 //removes all the permissions from the list, except for 'site - admins'

         while (selectedList.RoleAssignments.Count > 0)
                selectedList.RoleAssignments.Remove(0);

         if (selectedList.RoleAssignments.Count == 0)
         {
            // get the defined site admins group
               SPGroupCollection groupCollection = selectedList.ParentWeb.SiteGroups;
              SPGroup group = groupCollection["Site - Admins"];

            // get the full access role definition
              SPRoleDefinitionCollection roleDefCollection = selectedList.ParentWeb.RoleDefinitions;
              SPRoleDefinition roleDefinition = roleDefCollection [0];

			// create a role assignment based on the site admin group
            // and bind to the full access role definition
            SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);
            roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
            selectedList.RoleAssignments.Add(roleAssignment);
         }
}

Posted in Sharepoint | Tagged: , | Leave a Comment »