SharePointConsole

SharePointConsole

I wrote a Console application, which will allow you do some common tasks for your SharePoint environment. stsadm lacks some functionality like recyling all list items from a list…

Just copy the exe to your SharePoint Server, and execute it with an account which has the appropriate rights on your farm.

Usage:
SharePointConsole http://siteurl[/weburl] Command [Parameter1 Parameter2]

The SharePointConsole has the following parameters:

  • EnumContentTypes
  • CreateContentType
  • RenameContentType
  • DeleteContentType
  • DeleteAllListItems
  • ShowInNewForm
  • ShowInEditForm
  • ShowInDisplayForm
  • DeleteAllVersions
  • RecycleAllVersions
  • SetTitleWithFilename
  • SetSearchCenterUrl
  • SystemUpdate
  • FeatureManager
  • EmptyRecycleBin

EnumContentType:
Returns all content types from the specified sitecollection.

CreateContentType newName [Parent ContentType]:
Creates a new content type and inherrits from an exiting one, if a parent content type is specified.

RenameContentType contentType newName:
Renames a content type

DeleteContentType Name:
Deletes a content type

DeleteAllListItems ListName:
Deletes all listItems from the specified list (use the displayname)

RecycleAllListItems ListName:
Recycles (moves to Recycle Bin) all listItems from the specified list (use the d
isplayname)

ShowInNewForm ListName FieldName bool:
Changes the visibility of a field in the NewForm

ShowInEditForm ListName FieldName bool:
Changes the visibility of a field in the EditForm

ShowInDisplayForm ListName FieldName bool:
Changes the visibility of a field in the DisplayForm

DeleteAllVersions ListName:
Deletes all version except the current one

RecycleAllVersions ListName:
Recycles all version except the current one

SetTitleWithFilename ListName:
Sets the Title of all Documents with its filename without extension

SetSearchCenterUrl SearchCenterUrl:
Sets the SearchCenterUrl for an entire WebApplication

SystemUpdate ListName SleepTime itemID:
Hit each ListItem and do a SystemUpdate(false) to call attached EventHandlers. With SleepTime you define how many seconds to wait, before working on the next ListItem. If the itemID is != 0, only that item will be updated

FeatureManager featureID Enable/Disable [AllSites|AllWebs|Farm] :
Enable or Disable a feature by its ID. The optional paramter AllSites enables the feature on all sitecollections AND webs, AllWebs only in all webs of the sitecollection and Farm in the whole farm

EmptyRecycleBin
Empties the Recylce Bin for the site collection (from all stages and all webs!)

Update 28. May 2009
New commands added.

Download Download the SharePointConsole

HowTo create an object if you only have its type as string

Sometimes you have only the type of an object, which you want to create. Meaning you want to create an object dynamically. This is how you would achieve your goal:

In my case I wanted to create a SPField from its typename.

   1:  string typename = "Microsoft.SharePoint.SPFieldText, Microsoft.SharePoint, "+
   2:      "Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c";
   3:  Type t = Type.GetType(typename, true, true);
   4:  object newObject = System.Activator.CreateInstance(t, 
   5:      BindingFlags.SetProperty, new object[] { fields, "Title" });

I know one constructor for a SPField is to create a new object with the SPFieldCollection and its name.

The problem was that the constructor could be found.

You can view all available constructors with:

   1:  ConstructorInfo[] constructors = t.BaseType.GetConstructors();

After looking back into the SDK, I noticed that SharePoint can be so easy. You can create a SPField like this:

   1:  SPField newField = new SPField(fields, "SPFieldText", "new Field Name");

Next time I will remember 🙂

Keywords: Create SPField from typename, Erstellen eines spfield von seinem typ namen

Create an audience which contains an Active Directory Group

In the SDK are examples on how to create an audience which adds a rule like:

 

But how do you create a rule which takes the membership of an Active Directory Group? Well, look at this:

To get the ‘distinguishedName’ from a group, you can use ADSI Edit (open up a MMC and add the ADSI Edit Snap-In).

Keywords: Audience, AD, Gruppe, Active Directory, group, SharePoint, Member of

Another place, another proxy

Do you connect to different networks regularly? Well, I do. Switching the proxy each time is annoying. Here is the solution:

Marco wrote a great tool, which will switch your IE proxy based on the Gateway IP or the DNS Suffix 🙂

Have a look at it: http://blog.mwiedemeyer.de/2007/08/16/ProxySwitcherV102.aspx

Quote:

Proxy Switcher is a little helper tool for switching between different proxy settings.

If you are at many locations, e.g. at work, home, hotel, etc. you may be tired of setting (and rember) proxy settings for the different locations.

So, Proxy Switcher will assist you in remeber and easily switch between proxy settings. The major feature which is different from many other tools is, that Proxy Switcher can switch settings automatically depending on network connections.

To make this work, define a new proxy configuration and set a condition for activating it. Possible conditions (in this version) are depending on the DNS suffix (e.g. yourcompany.com) or on the gateway IP address. If you now connect you notebook to a network, the settings will activated automatically.

Display all my alerts

The "old" SharePoint Server 2003 offered the ability to display all alerts from a user on his/her MySite. MOSS and SharePoint 2010 lacks this functionality. So I wrote a Webpart, which will display all my alerts. Of course is multilingual. Currently there is English, German and Spanish language support included. And it will work on Windows SharePoint Services V3 as well ass SharePoint Foundation. You don’t need the Office Server / SharePoint Server 2010 for it 🙂

You can configure which columns shall be displayed, and if you want to see all alerts from all websites within your SharePoint farm.

The Webpart will iterate through all websites, and look if there are alerts for the current user. You can then modify the alerts, or navigate to the corresponding website and list by clicking on the appropriate entry in the context menu of the alert.

To install this Webpart, install and deploy the solution via stsadm:

  1. stsadm -o addsolution -filename RH.MyAlerts.wsp
  2. stsadm -o deploysolution -name RH.MyAlerts.wsp -immediate -url http://yoururl

Instead of deploying the solution using stsadm, you can deploy it in the central administration of your farm.

Creating the solution wsp file is very easy, if you use the WSPBuilder.

Download the solution.

Download the source code for the Webpart.

(Please set the trust level of your web.config to ‘Full’!)

Keywords: SharePoint, alert, all my alerts, benachrichtigung, alle meine benachrichtigungen anzeigen

Update 16.12.07
I fixed an error and the Multilanguage support is back

Update 12.05.08
Another small update. Handling search alerts is improved and the assembly will not install in the GAC (Global Assembly Cache) to get rid of the FullTrust setting in the web.config.

Update 11.06.08
This update deals with the problem that SPContext.Current.Web.CurrentUser is sometimes null.

Update 31.08.08
The Webpart does now include an update check in the Webpart properties.

Update 01.10.08
A small bug fix update.

Update 26.10.08
I have implemented Spanish localization.

Update 08.11.08
A small update to 1.0.4.0 with bugfixes

Update 22.07.09
HtmlDecoding for the GroupBy field value (the title for webs)

 

Update 1.9.09 – Version 1.0.6.0
Fix to prevent Access Denied e.g. for SSP Sites.

Update 20.12.2011 – Version 1.1.0.0
Small update to improve SharePoint 2010

HowTo use the resource files from SharePoint

How about using the available resources from SharePoint to translate some basic words and sentences? Well, it is quite easy to use the available resources. You need the Microsoft.SharePoint.Intl.dll and some lines of code to use the already translated resources:

But how do you know how the resource name for your translated text might be? Your friend and helper is the Reflector. Open up the ‘Microsoft.SharePoint.Intl.dll’ from the ‘C:\WINDOWS\assembly\GAC_MSIL\Microsoft.SharePoint.intl\12.0.0.0__71e9bce111e9429__71e9bce111e9429c’ folder (navigate to that path with cmd.exe and copy the dll to some safe place like c:\temp).

A big thanks goes to Janne Mattila for the information in the comment for this blog entry.

Custom assemblies for the Reporting Services 2005

Even if the Reporting Services are very powerfull, you might get to the point where you have to extend the building functionality. So why not write your own custom assembly with some additional code?

Create your assembly like this:

   1:  using System;
2: using System.Security.Permissions;
3: using Microsoft.SharePoint;
4:  
5: public class MyNamespace
6: {
7: public class ReportingExtension
8: {
9: public ReportingExtension()
10: {
11: }
12:  
13: public static string HelloWorld()
14: {
15: return "Hello World.";
16: }
17:  
18: [EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
19: [Microsoft.SharePoint.Security.SharePointPermission(SecurityAction.Assert, Unrestricted = true)]
20: public static string getSomeListItem(string url, int itemID)
21: {
22: string returnvalue = string.Empty;
23: try
24: {
25: using (SPSite site = new SPSite(url))
26: using (SPWeb web = site.OpenWeb())
27: {
28: // do something
29: returnvalue = "";
30: }
31: }
32: catch (Exception ex)
33: {
34: return ex.ToString();
35: }
36:  
37: return returnvalue;
38: }
39: }
40: }

 

Put this line into your AssemblyInfo.cs:
[assembly: AllowPartiallyTrustedCallers]

and sign your assembly with a strong name (see here for details).

Next you have to reference your assembly in your Reporting project in the Report Properties:

You can then use your code like this:

=MyNamespace.ReportingExtension.getSomeListItem("http://site/web", 5)

Before you can use your custom assembly, you have to deploy it to the following paths:

  • Report Designer C:\Program Files\Microsoft SQL Server\80\Tools\Report Designer
  • Reporting Server C:\Program Files\Microsoft SQL Server\MSSQL.1\Reporting Services\ReportServer\bin

And register it in the rssrvpolicy.config file:

<CodeGroup
class="UnionCodeGroup"
version="1"
PermissionSetName="FullTrust"
Name="MyNamespace.ReportingExtension"
Description="Code for SSRS">
<IMembershipCondition
class="UrlMembershipCondition"
version="1"
Url="c:\Program Files\Microsoft SQL Server\MSSQL.1\Reporting
Services\ReportServer\bin\MyNamespace.ReportingExtension.dll"
/>

 

Now you are good to go J

Index a remote SharePoint Site

Did you ever want to crawl a remote SharePoint site and were unsuccessfull doing so? Well I did.

The only solution I found, was not to crawl the remote site with the default crawler credentials, but with an account from the remote site.

You can do so by creating a crawl rule in your SharedServices Provider, which only includes the remote site.

Target Audiences

You can specify a Target Audience in a Webpart, for it to only be visible to e.g. members of a certain AD group.

 

Have you ever wonderd yourself why on earth the new group does not appear in the list and is not valid? Well, I did 🙁

The reason is quite simle. Shortly after the userimport from your AD or another LDAP source there is another import started. This one imports groups and memberships. Only after this step the groups will show up in the "Target Audiences" field in your Webpart!

But remember. This Target Audience is only for displaying a Webpart to certain users. It has nothing to do with access rights to items!

You can start the import in your SharedServices Provider http://urltossp/ssp/admin/_layouts/ProfMain.aspx

Updated Wiki Webpart

Please use my custom field type. It is more flexible –> http://www.hezser.de

 

I updated my Wiki Webpart. For all of you who don’t know what it does:

The normal Wiki Edit Form misses the ability to upload pictures. My Webpart, which has to be included to the EditForm.aspx, allows you to upload a picture. It also creates a link in your Wiki post, which displays the uploaded image.

This release of the Webpart is multi lingual. Meaning it will present text to the user in english and german. If you would like this Webpart in your language, drop me a note 🙂

Installation steps:
(If you need help: look here)

  1. copy the dll to the bin folder of your SharePoint virtual server
  2. create an entry in the safecontrol section of your web.config
    <SafeControl Assembly="WikiWebpart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b17a955c3eada4c1" Namespace="WikiWebpart" TypeName="*" Safe="True" />
  3. change the TrustLevel in the web.config to either "WSS_Medium" or "Full"
  4. add the Webpart to the Webpart gallery of your sitecollection
  5. modify the EditForm.aspx of your Wiki Page with SharePoint Designer, and add the WikiWebpart beneath the standard EditForm Webpart
  6. you are ready to use it 😉

  Download the Webpart

Update 23. Apr 2008:

I have released a new version. Bugfixing only.

Create an eventlog entry

For exception handling it is good practice to write errors to the eventlog.

EventLog.WriteEntry("SharePoint.Error", errorText, EventLogEntryType.Error);

Since SP1 for Windows Server 2003 "the normal user" is not allowed to write to the eventlog. James Kovacs wrote a great article about the problem.

(Remember to create your eventlog source, if you have your own!)

   1:  if(!EventLog.SourceExists("SharePoint.Error", ".")) {
   2:      EventLog.CreateEventSource("SharePoint.Error", "Application", ".");
   3:  }

„File not found“ error

If somehow the path to your masterpage is broken, you will get an error message like "file not found" when you access a website. This could happen if you create a new site from a template, which comes from another server. You can open your site in SharePoint Designer, though.

The KB article A subsite that you create in SharePoint Server 2007 does not inherit master page settings from its parent site, and you receive error messages on the Site Master Page Settings page describes this problem. You can solve it by enabling and disabling the Publishing feature in your sitesettings.

Open Office 2007 files from WSS V2/SPS 2003

You all know, that you can open a document via the context menu in SharePoint in editmode in an Office Application. This does not work, if you save e.g. a .docx.

But help is on the way: Icons that represent 2007 Office files are incorrect, and the "Edit in Microsoft Office <ProgramName>" option does not appear in a document library in SharePoint Portal Server 2003 or in Windows SharePoint Services 2.0

RESOLUTION

Modify the Docicon.xml file and the Htmltransinfo.xml file to include the file name extensions of the 2007 Office file types that you want. Perform this procedure on each front-end Web server on the server farm. To modify the Docicon.xml file and the Htmltransinfo.xml file to include the file name extensions of 2007 Office file types, follow these steps.
Note The following procedure shows you how to add support for Microsoft Office Word 2007 documents (.docx). Use the same procedure to add support for Microsoft Office Excel 2007 files (.xlsx) and for Microsoft Office PowerPoint 2007 files (.pptx).

1. Start Windows Explorer, and then locate the following folder:
Drive:\Program Files\Common Files\Microsoft Shared\Web server extensions\60\Template\Xml

2. Modify the Docicon.xml file. To do this, follow these steps:

a. Open the Docicon.xml file.

b. Locate, and then copy the following line:
<Mapping Key="doc" Value="icdoc.gif" EditText="Microsoft Office Word" OpenControl="SharePoint.OpenDocuments"/>

c. Paste the line under the line that you copied, and then modify it so that it reads as follows:
<Mapping Key="docx" Value="icdoc.gif" EditText="Microsoft Office Word" OpenControl="SharePoint.OpenDocuments"/>

3. Modify the Htmltransinfo.xml file. To do this, follow these steps:

a. Locate, and then copy the following line:
<Mapping Extension="doc" AcceptHeader="application/msword" HandlerUrl="Htmltranslate.aspx" ProgId="SharePoint.OpenDocuments.2"/>

b. Paste the line under the line that you copied, and then modify it so that it reads as follows:
<Mapping Extension="docx" AcceptHeader="application/msword" HandlerUrl="" ProgId="SharePoint.OpenDocuments.2"/>

4. Repeat step 2 and step 3 for each 2007 Office file type that you want. Make sure that you use the appropriate file name extension. For example, do one or both of the following:

• To add support for .pptx files, modify the line that you add to the Docicon.xml file and the Htmltransinfo.xml file to include Mapping Key="pptx" parameter.

• To add support for .xlsx files, modify the line that you add to the Docicon.xml file and the Htmltransinfo.xml file to include Mapping Key="xlsx" parameter.

5. Restart Internet Information Services (IIS). To do this, click Start, click Run, type iisreset, and then click OK.

How to get LookupField Information from a listItem

If you want the ID or the value form a LookupField, you can get it easily with this code snippet:

SPListItem item = getitsomewhare...
SPFieldLookupValue lf =
    (SPFieldLookupValue)
     item.ParentList.Fields.GetField(_FieldName).GetFieldValue(
     item.GetFormattedValue(_FieldName));

if you got the field, fetch its properties via

if (lf == null)
{
    int itemID = lf.LookupId;
    string itemValue = lf.LookupValue;
}
Have fun ;-)

Install Windows Service Pack on a VM

On a newly installed Virtual Machine you don’t need any uninstall information from a servicepack, which consumes lots of diskspace. You can install the SP2 for Windows Server 2003 (R2) with the /nobackup parameter.


RESTART OPTIONS

/NORESTART:
No restart will take place. You will have to perform a manual restart yourself before the service pack installation can be considered complete.

/FORCERESTART:
A restart will automatically take place at the end of the installation.This will be handy if you automate the execution of UPDATE.EXE.

/WARNRESTART:<SECONDS>:
You can pop up a dialog to let people know that a restart will take place in X seconds.

/PROMPTRESTART: A request to initiate a restart will be displayed for the interactive user/administrator to acknowledge.

SPECIAL OPTIONS

/OVERWRITEOEM:
Microsoft includes updated versions of some drivers in the service pack. If the installation finds a driver on your system that it wants to update, it will usually ask if you want to go ahead with this upgrade. Using this flag will force the installer to automatically do this for you. Personally, and I think others agree, if HP, IBM, Dell, etc, have provided me with a driver then I’m going to suspect that there’s something special about it. In fact, these manufacturers often do provide customised or

tweaked versions of drivers from mass manufactures such as Intel or Broadcom. I wouldn’t want to go messing with those drivers, especially if I’m using an OEM version control system for them or an SMS Inventory Tool from the likes of HP or Dell.

/NOBACKUP:
Normally, the service pack will create the familiar uninstall folder in the Windows folder. Along with this, a new item is added to the Add/Remove Programs applet in Control Panel. This enables an administrator to roll back the service pack installation if something breaks. Unfortunately, I’ve come across several sites where for some unknown reason, administrators choose to make the C: drive for fresh Windows 2003 installations as small as possible, often less than 5GB. The partition quickly fills up once the OS is installed; quickly followed by anti-virus, backup agents, page file, etc. In this case it may be prudent not to create a backup folder. This means that the service pack can never be uninstalled … so testing and application certification become even more critical.

/d:<PATH>:
We’ve just seen how we can choose not to backup files into the Windows folder because C: is nearly full. If you have space elsewhere, you can use the /d flag to point to that path to backup the

Get a listitem by ID

Fetching a listitem by ID will generate an error, if the a listitem with the ID does not exist. To avoid this exception, you can get a listitem by id by searching for it:

private SPListItem GetListItem(SPList List, int ListItemID)
{
    try
    {
        string defaultView = List.DefaultView.Title;
        SPQuery query = new SPQuery(List.Views[defaultView]);

        string caml =
String.Format("<Where><Eq><FieldRef Name='ID'/><Value Type='Counter'>{0}</Value></Eq></Where>",
ListItemID); query.Query = caml; SPListItemCollection results = List.GetItems(query); if (results.Count == 1) { return results[0]; } } catch (Exception ex) { _ErrorMessage +=
String.Format("List \"{0}\" does not contain an item with the id \"{1}\".<br/>{2}",
List.Title, ListItemID, ex.Message); } return null; }

If there is no listitem with the specified ListItemID, you will get a null instead of an exception.

Display a single listitem

You can display multiple list items with SharePoint and SharePoint Designer quite easy. But how do you display a single listitem? I worte a Webpart, which does this. If there are more than one listitem, you can page through them. And if you like, you can pass an itemid via a Webpart connection.

In the Webpart properties you can select the list/library. If you like, you can specify a view other than the default view.

SafeControl Entry for your web.config:
<SafeControl  Assembly="RH.DisplayListItem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7850e867f7381714"  Namespace="RH"  TypeName="*"  Safe="True" />

 Download Webpart
 
Download Webpart Source

Create/Rename/Modify content types

Some content types are hidden. This makes it hard to create a new content type, which inherrits from e.g. the "event". Via the object model it is very easy to create a content type, which uses e.g. "event" as parent.

SPSite site = new SPSite(http://serverurl);
SPContentType parentContentType = site.RootWeb.ContentTypes["Event"];
SPContentType newType = new SPContentType(parentContentType, site.RootWeb.ContentTypes, "newName");
site.RootWeb.ContentTypes.Add(newType);

Because creating a new content type is just not enough, I wrote a little console application, which lets you create, rename and delete content types for a sitecollection:

Usage:
SharePointConsole http://siteurl Command [Parameter1 Parameter2]
Commands:
– EnumContentTypes
– CreateContentType
– RenameContentType
– DeleteContentType

EnumContentType siteurl:
Returns all content types from the specified sitecollection.

CreateContentType newName [ContentType]:
Creates a new content type and inherrits from an exiting one, if a parent content type is specified.

RenameContentType contentType newName:
Renames a content type

DeleteContentType siteurl Name:
Deletes a content type

You can download this tool here, and the Visual Studio Project with sourcecode here.

How to make Content Type Searchable in a search scope

Content Types are great to identify your different types of documents and list items. But how can you search for them?

In this article I want to show you how to search for your content type via a search scope.

  1. First lets create a new content type "contracts". Go to the rootweb of your sitecollection, and create a new content type:

  1. Next, add the new content type to a (new) documentlibrary.
  2. Add some documents with the content type "contract"
  3. In order to be able to search von content types, we have to change the managed property "Content Type" in the Shared Services Provider Search Settings. With default settings, this property is not usable in search areas.
  • To change this setting, go to your Shared Services Provider, Search settings, managed Properties.

  1. Now we can go to the settings of our sitecollection, and create a new search scope. If you check the checkbox for Searchdropdown, "Contracts" will show up in the normal search dropdown on every site.

  2. The new and empty search scope has to be configured to return the results, we would like to see. In our case, this would be documents with the content type "contracts". So we have to add a rule the newly created search scope.

If you do not want to wait until the search scope will be created automatically, you can go to the search settings of your Shared Services Provider and manually compile your search scopes.