Saturday, August 1, 2009

Operation is not valid due to the current state of the object

I writed a post about this error (http://mosswat.blogspot.com/2009/02/operation-is-not-valid-due-to-current.html)

There is another cause to this error: using the "update" method in the "RunWithElevatePrivilege" scope, like this:

SPSecurity.RunWithElevatedPrivileges(delegate{
using (SPSite site = new SPSite("http://mySiteUrl"))
{
using (SPWeb web = site.OpenWeb())
{
SPListItem listItem = web.GetListItem("http://myItemUrl");
//do item modifications....
listItem.Update();
}
}

});

To resolve this issue, call the "update" method out of the "RunWithElevatedPrivileges" scope, like this;

SPSite site = null;
SPWeb web = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate{
site = new SPSite("http://mySiteUrl");
web = site.OpenWeb();
});
SPListItem listItem = web.GetListItem("http://myItemUrl");
//do item modifications....
listItem.Update();
}
finally
{
if (site != null)
site.Dispose();
if (web != null)
web.Dispose();
}

Wednesday, July 22, 2009

Active Directory: How to get all related groups by user

Hi

I know this is not a Moss post and i know that in Moss we trust, but it is a nice code to have.

Recently i needed to get all related AD groups per user, so if a user A is in group B and group B is in group C, i will get a collection like so { B,C } for A.

To do so i used the following code:


/// ldapPath - Ldap://...
/// distinguishedName - The user location (CN=AAA, OU=BBB,OU=CCC,DC=DDD )
///resultField - The property field value (DisplyName, Mail)
public static void GetAllRelatedGroupsByEntry(string ldapPath, string distinguishedName,
ref List<string> groups, string resultField)
{
SearchResultCollection results = null;

using (DirectoryEntry entry = new DirectoryEntry(ldapPath))
{

using (DirectorySearcher search = new DirectorySearcher(entry))
{

search.Filter = "(&(objectClass=Group)(objectCategory=Group)(member=" + distinguishedName + "))";

results = search.FindAll();

if (results != null)
{
foreach (SearchResult result in results)
{
for (int i = 0; i <>
{
groups.Add(result.Properties[resultField][i].ToString());
GetAllRelatedGroupsByEntry(ldapPath,
result.Properties["DistinguishedName"][i].ToString(),
ref groups, resultField);
}
}
}
}
}
}

Sunday, July 12, 2009

How to add Sharepoint Workflow Activities to Toolbox

Hi

There are more workflow activities that you can use beside the one that are already in, for example "Create Task".

To add them to the toolbox you need to open visual studio and on the Toolbox section:

1. Create new tab by right click and select "Add Tab".

2. Under the new tab press right click and select "Choose Items…" (It will take a while to open).

3. Then select microsoft.sharepoint.WorkflowActions.dll, it is usually under C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

4. Press OK.

5. Now you will have the following activities:


Monday, July 6, 2009

SPWeb.RoleDefinitions.GetByType(SPRoleType.None)

Hi all

Recently i tried to copy permission from one item to another (see How To Copy Permissions Between Site Collections) , and had a problem with role definition types that were None.
The problem occured when i tried to copy
Restricted Read role agginment.

So to solve it I used this code:

if (roleDefinition.Type != SPRoleType.None)
{
definition = web.RoleDefinitions.GetByType(roleDefinition.Type);
roleAssignment.RoleDefinitionBindings.Add(definition);
}
else
{
definition = web.RoleDefinitions.GetById(roleDefinition.Id);
roleAssignment.RoleDefinitionBindings.Add(definition);
}

Instead of geting the code by role definition type i got it by it's Id.

Wednesday, May 6, 2009

How to create your own local path

Hi

In lots of MOSS development we are using custom aspx/html or just office templates and we need to save them in the local server file system. We can use the layouts folder (/_layouts/...) or create our own path.

To do so create a feature.xml and element.xml, in the element file add the Module tab, in the SetupPath attribute write the file system folder path (like FEATRUES\mosswat), and in the Url attribute write the new url (like _mosswat/templates).



Run the stsadm segment.

Now enter in the explorer the following: http://WebApp/sites/SiteCollection/_mosswat/templates/filename.docx


Tuesday, May 5, 2009

MOSS & AJAX (Framework 3.5)

Hi,

More and more sites are using AJAX and it is not only "nice to have" feature but a mandatory one.

We can also use AJAX in MOSS and there is a lot of example how to on the Internet, but before we start we have to add some elements in MOSS web.config.

A few posts ago Michael wrote on how to update web config, so i added the XML file in here so u can copy it to C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\config and run the stsadm commend

Warnings:
  1. Before u run it backup your web.config and your DB and do not delete the element by your self only with the remove file.
  2. Don't copy the remove and the add together to the Config directory only the one you want to run.
  3. Very important don't change the guid before you are doing remove!!! 

Wednesday, March 11, 2009

MOSS Search PDF 64-bit using IFilter 9


Install the PDF Ifilter 9 for 64-bit

  1. Download and extract the contents of "PDFiFilter64installer.zip" to your local drive.
  2. Double click "PDFFilter64installer.msi" to launch the installer.
  3. Follow the instructions in the installer wizard to complete the installation.
  4. After installing the PDF iFilter, it is recommended that you set your system PATH environment variable to the "bin" folder of the "Ifilter" installation. For example, from the "Control Panel\System\Advanced\Environment Variables" tab, append to PATH "C:\Program Files\Adobe\Adobe PDF iFilter 9 for 64-bit platforms\bin\" and then restart the computer.
  5. Follow the Sharepoint IFilter Configuration Guide

Add the PDF extension to Search File Types

  1. SharePoint Server Search Administration page by adding ‘pdf’ to list of File Types in Search Administration->File Types

Add the PDF File Icon to MOSS

  1. Download the icon for pdf file from http://www.adobe.com/images/pdficon_small.gif , save it to \TEMPLATE\IMAGES directory and name it pdficon_small.gif.
  2. Open the docicon.xml file from .\template\xml .
  3. Add a new Mapping element to the ByExtension element.
  4. Save the docicon.xml file.
  5. Restart IIS using iisreset command line.


Restart all SharePoint services as well as IIS.

  1. Run these command-lines:
    “net stop osearch”. Wait for success message.
    “net start osearch”. Wait for success message.
  2. Restart IIS using iisreset command line and wait for success message.

Re-Crawl

Make sure that you Full Crawl !!!

*** Troubleshooting ***

Important step that will solve this error message "The filtering process could not process this item. This might be because you do not have the latest file filter for this type of item. Install the corresponding filter and retry your crawl."

Make sure to change the \\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\12.0\Search\Setup\ContentIndexCommon\Filters\Extension\.pdf to the GUID {E8978DA6-047F-4E3D-9C78-CDBE46041603}. The original value was {4C904448-74A9-11D0-AF6E-00C04FD8DC02}. (thanks to Russell Wright for that one)

URLs:

http://download.adobe.com/pub/adobe/acrobat/win/9.x/PDFiFilter64installer.zip
http://www.adobe.com/support/downloads/detail.jsp?ftpID=4025
http://support.microsoft.com/default.aspx/kb/832809
http://www.adobe.com/special/acrobat/configuring_pdf_ifilter_for_ms_sharepoint_2007.pdf
http://www.adobe.com/images/pdficon_small.gif
http://sharepointsolutions.blogspot.com/2009/01/installing-adobes-64-bit-pdf-ifilter-9.html

How to easy add Dll to the gac

Hi,

If you want to add dll to the gac with a simple right click, follow theses steps:

1. Foreach .NET version paste the apropriate script in a new file
2. Save it with ".reg" extension
3. Double click on each file to add the entry in the registery.

.Net 1.1

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\dllfile\shell\gacutil\command]@="c:\\windows\\Microsoft.NET\\Framework\\v1.1.4322\\gacutil.exe /i \"%1\""

.Net 2.0

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\dllfile\shell\gacutil\command]@="C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\V2.0\\Bin\\gacutil.exe /i \"%1\""


Thanks to Elad R...

Tuesday, March 10, 2009

New Release Content Type List Binder

Hi all,

We have done it again... :)

Content Type List Binder is a new application that help us bind between lists and content types.

How to:

1. Enter the site collection url and press the load data button.
2. Select the lists you want (or need) and the relavent content type.
3. Press on bind (check the insert content type radio button to add and remove content type to remove).

You can Download Here (If you are like me and use Chrome it will save the file as .htm, so just change the suffix to .msi).

Saturday, March 7, 2009

SPQuery syntax

SPQuery is the best way to write queries on MOSS.
MOSS is using CAML to get data in the best and quickest way from sites,lists and folder. using SPQuery is in most cases the "best practice" way to find information in MOSS and also used in Sharepoint web services.
We have gather a few impotent information about SPQuery syntax,


Properties:
  • SPQuery.Query:




  • SPQuery.RowLimit: An int that indicate the row limit.



  • SPQuery.Folder: Get a SPFolder object.  
    This is the best way to get items that are in folder.
  • SPQuery.ViewField: The same is a "SELECT" sentence.





Operators:

Eq = equal to

Neq = not equal to

BeginsWith = begins with

Contains = contains

Lt = less than

Leq = less than or equal to

Gt = greater than

Geq = greater than or equal to

IsNull = is null

IsNotNull = is not null



AND & OR CONDITIONS

Using and & or is very similar to using regular parentheses, between each to operation we need to add AND or OR for example:

  • AND:


We are using AND between 2 operators and add another tab when we add a new operator.

  • OR:


The same as AND.

  • AND & OR:


With AND & OR we are creating brackets, we create each one of the conditions and wrap them with AND/OR.


How to write CAML queries ?

A very useful tool allow you to build yours CAML queries: U2U Caml Query Builder.



Performance consideration:

If your farm is well indexed, retiewing datas using SPquey in the best method to improve performance. See also our post about working with large list in Sharepoint

Thursday, March 5, 2009

Template List ID

Administrator tasks list : 1200
Announcements list : 104
Blog Categories list : 303
Blog Comments list : 302
Blog Posts list : 301
Contacts list : 105
Custom grid for a list : 120
Custom Workflow Process : 118
Data Connection library : 130
Data sources : 110
Discussion board : 108
Document library : 101
Events list : 106
Gantt Tasks list : 150
Generic list : 100
Issue tracking : 1100
Links list : 103
List template gallery : 114
Master pages gallery : 116
Meeting Agenda list : 201
Meeting Attendees list : 202
Meeting Decisions list : 204
Meeting Objectives list : 207
Meeting Series list : 200
Meeting text box : 210
Meeting Things To Bring list : 211
Meeting Workspace Pages list : 212
No-Code Workflows : 117
Personal document library : 2002
Picture library : 109
Portal Sites list : 300
Private document library : 2003
Site template gallery : 111
Survey : 102
Tasks list : 107
User Information list : 112
Web Part gallery : 113
Wiki Page library : 119
Workflow History : 140
XML Form library : 115

Reference : http://simeonlobo.wordpress.com/2008/02/27/sharepoint-list-template-ids/

Content Type ID

Content Types ID

Item
0×01
Create a new list item


Reusable HTML
0×01002CF74A4DAE39480396EEA7A4BA2BE5FB
Reusable HTML

Reusable Text
0×01004D5A79BAFA4A4576B79C56FF3D0D662D

Page Output Cache
0×010087D89D279834C94E98E5E1B4A913C67E
Page Output Cache is a system content type template created by the Publishing Resources feature to define cache profiles.

Document
0×0101
Create a new document.

System Page Layout
0×01010007FF3E057FA8AB4AA42FCB67B453FFC1
System Page Layout is a system content type template created by the Publishing Resources feature, and it cannot be modified. To add columns to page layouts in the page layouts gallery and master page gallery, update the Page Layout content type template.

Page Layout
0×01010007FF3E057FA8AB4AA42FCB67B453FFC100E214EEE741181F4E9F7ACC43278EE811
Page Layout is a system content type template created by the Publishing Resources feature. All page layouts will have the column templates from Page Layout added.

System Master Page
0×0101000F1C8B9E0EB4BE489F09807B2C53288F
System Master Page is a system content type template created by the Publishing Resources feature, and it cannot be modified. To add columns to master pages in the page layouts gallery and master page gallery, update the Master Page content type template.

Publishing Master Page
0×0101000F1C8B9E0EB4BE489F09807B2C53288F0054AD6EF48B9F7B45A142F8173F171BD1
Master Page is a system content type template created by the Publishing Resources feature. All master pages will have the column templates from Master Page added.

Office Data Connection File
0×010100629D00608F814DD6AC8A86903AEE72AA

Universal Data Connection File
0×010100B4CBD48E029A4AD8B62CB0E41868F2B0
Provide a standard place for applications, such as Microsoft Office InfoPath, to store data connection information.

System Page
0×010100C568DB52D9D0A14D9B2FDCC96666E9F2
System Page is a system content type template created by the Publishing Resources feature, and it cannot be modified. To add columns to the Pages library, update the Page content type template.

Page
0×010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF39
Page is a system content type template created by the Publishing Resources feature. The column templates from Page will be added to all Pages libraries created by the Publishing feature.

Article Page
0×010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44DArticle Page is a system content type template created by the Publishing Resources feature. It is the associated content type template for the default page layouts used to create article pages in sites that have the Publishing feature enabled.

Welcome Page
0×010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390064DEA0F50FC8C147B0B6EA0636C4A7D4
Welcome Page is a system content type template created by the Publishing Resources feature. It is the associated content type template for the default page layout used to create welcome pages in sites that have the Publishing feature enabled.

Redirect Page
0×010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900FD0E870BA06948879DBD5F9813CD8799Redirect Page is a system content type template created by the Publishing Resources feature. It is the associated content type template for the redirect page layout

Form
0×010101
Fill out this form.

Picture
0×010102
Upload an image or a photograph.
Unknown Document Type0×010104Allows users to upload documents of any content type to a library. Unknown documents will be treated as their original content type in client applications.

Master Page
0×010105
Create a new master page.

User Workflow Document
0×010107
Items for use in user defined workflows.

Wiki Page
0×010108
Create a new wiki page.

Basic Page
0×010109
Create a new basic page.

Web Part Page
0×01010901
Create a new Web Part page.

Link to a Document
0×01010A
Create a link to a document in a different location.

Dublin Core Columns
0×01010B
The Dublin Core metadata element set.

Event
0×0102
Create a new meeting, deadline or other event.

Issue
0×0103
Track an issue or problem.

Announcement
0×0104
Create a new news item, status or other short piece of information.

Link
0×0105
Create a new link to a Web page or other resource.

Contact
0×0106
Store information about a business or personal contact.

Message
0×0107
Create a new message.

Task
0×0108
Track a work item that you or your team needs to complete.

Workflow Task
0×010801
A work item created by a workflow that you or your team needs to complete.

Office SharePoint Server Workflow Task
0×01080100C9C9515DE4E24001905074F980F93160
A work item created by a workflow that you or your team needs to complete.

Administrative Task
0×010802
An administrative work item that an administrator needs to complete.

Workflow History
0×0109
The history of a workflow.

Person
0×010A

SharePointGroup
0×010B

DomainGroup
0×010C

Post
0×0110
Create a new blog post.

Comment
0×0111
Create a new blog comment.

Far East Contact
0×0116
Store information about a business or personal contact.

Folder
0×0120
Create a new folder.

RootOfList
0×012001

Discussion
0×012002
Create a new discussion topic.

Reference:
http://claytonj.wordpress.com/category/office-12/moss-2007/

WebService "Service Unavailable" error message

When changing the application pool user it is important to add the user to the IIS_WPG group.

Yesterday, we so this error message and found the solution here which says that the reason for this kind of error message may be because one of the following occurs:
  1. The application pool is not running.
  2. The application pool account uses an incorrect password.
  3. The application pool account is not a member of both the IIS_WPG group and the STS_WPG group on the server.

In our case it was the third one, after adding the application pool user to the IIS_WPG group the WebService run like a magic.....

Liron

Wednesday, March 4, 2009

Off Topic: MOSS S.W.A.T Merchandise :-)

(LOL)

We've just printed out few MOSS S.W.A.T T-Shirts for our team.....






If you are interested to be the owner of this T-Shirt please let us know

Liron

Sunday, March 1, 2009

Update Moss Web.Config V2

The last week we spoke about another way to update sharepoint web.config by using custom xml.
I readed an excellent post of Gaetan Bouveret that give interesting details:

Specifically, he explains that we can add an "id" attribut to each node to prevent adding sames nodes twice

Samples :

To add a node like add appsetting:

<add path="configuration" id="{72DB2C92-8BC1-4767-A12C-94B67D46D0CF}">

  <appSettings />

 </add>


To update a node :

<update path="configuration/system.web">

    <siteMap defaultProvider="CurrentNavSiteMapProvider" enabled="true"/>

</update>



To delete node :

 <remove path="configuration/SharePoint/RuntimeFilter"
id="{0582988F-9C26-4990-8672-0099F4567B03}" />



Note: The "id" attribut is very important to prevent adding same nodes twice.

Saturday, February 28, 2009

How To Copy Permissions Between Site Collections

Hi again,

One of the more challenging issues in MOSS is permissions, specially if we need to move them between site collections.

To add permissions to item\folder\list\site we add SPRoleAssignment that contains SPUser (as SPPincipal), and SPRoleDefinition that contain the the BasePermissions or the Types (reader/contributor...).

Each role is have diffrent parameters in each site collection, for example my user can be in one site collection 1;#elad and in the other can be 5;#elad, the same user but a diffrent id. the same is for definition, contributor for example have the same base permissions in every site collection but have a differnt ID.

So what to do... ?

It is eazy, 
1. Create a new instant of your role user like this:

// role is the role assignment from the old site collection.
SPUser user = role.Member as SPUser;

2. Than create a new role assinment

// web is the site in the new site collection
SPRoleAssignment roleAssignment = new SPRoleAssignment(
                                   web.EnsureUser(user.LoginName) as SPPrincipal); 

Why EnsureUser ? 
The EnsureUser method will chack if the user exist in the corrent site and if not will create him as Limited Access permission. (10x to Michael Assouline that show me this method).

than add the role definitions to the new role assignment,

foreach (SPRoleDefinition roleDefinition in role.RoleDefinitionBindings)
{
// we cann't add Limited Access
if (roleDefinition.Type != SPRoleType.Guest)
        {
   definition = web.RoleDefinitions.GetByType(roleDefinition.Type);
   roleAssignment.RoleDefinitionBindings.Add(definition);
}
}

3. And now just add the new role to the item,

item.RoleAssignments.Add(roleAssignment); 


Wednesday, February 25, 2009

Update Moss Web.Config

1. Programatically using Sharepoint API

We can use SPWebConfigModification object like this:

This code update CustomErrors value

// Get an instance of my local web application
SPWebApplication webApp = new SPSite("http://localhost").WebApplication;
// Create my new modification to set the mode attibute to "Off".
// Example:
SPWebConfigModification modification = new SPWebConfigModification("mode", "system.web/customErrors");
modification.Owner = "SimpleSampleUniqueOwnerValue";

modification.Sequence = 0; modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
modification.Value = "Off";
// Add my new web.config modification.
webApp.WebConfigModifications.Add(modification);
// Save web.config changes.
webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
// Serialize the web application state and propagate changes across the farm.
webApp.Update();


This code Add safe control entry to the web.config :

SPWebService myService = SPWebService.ContentService;
SPWebConfigModification myModification = new SPWebConfigModification();
myModification.Path = "configuration/SharePoint/SafeControls";
myModification.Name = "SafeControl[@Assembly='MyCustomAssembly'][@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']";
myModification.Sequence = 0;
myModification.Owner = WebConfigModificationFeatureReceiver.OwnerId;
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "";
myService.WebConfigModifications.Add(myModification);myService.Update(); myService.ApplyWebConfigModifications();


References :
http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=32
http://blogs.devhorizon.com/reza/?p=459
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spwebconfigmodification.aspx



2. Deploying custom XML File in the Sharepoint CONFIG folder ( C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\CONFIG

Steps to perform it:

1. Write an xml file called webconfig.[myname].xml

2. Add yours web.config sections into "actions" node:

<?xml version=”1.0″ encoding=”utf-8″ ?>

<actions>

<add path=”configuration/appSettings”>

<add key=”MyFilePath” value=”C:\temp\path\” />

</add>

<add path=”configuration”>

<connectionStrings />

</add>

<add path=”configuration/connectionStrings”>

<remove name=”MySqlServerConnection” />

<add name=”MySqlServerConnection” connectionString=”server=[server];database=

db];Integrated Security=SSIP;” providerName=”System.Data.SqlClient” />

</add>

</actions>




3. Copy your xml file into C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\CONFIG folder

When you'll create a new web application or extend web application the web.config will be updated with yours sections by merging them into the web.config.

If you want to immediately apply the changes you have to run : stsadm –o copyappbincontent

Reference: http://claytonj.wordpress.com/2008/03/19/custom-webconfig-settings-in-sharepoint/


3. See also : http://blog.thekid.me.uk/archive/2007/03/24/web-config-modification-manager-for-sharepoint.aspx



Sunday, February 22, 2009

Document library internal fields

Recently i was needed to use OpenXml in Moss (hopefully i will write on this soon), one of the issue i needed to handle was the fact that it will only work of office 2007 files and not on pdf/office 2003/txt files and more.

After  a short google seach i found all the relevant suffix (http://msdn.microsoft.com/en-us/library/aa338205.aspx , http://office.microsoft.com/en-us/word/HA100069351033.aspx), so all i needed is the file suffix. However, i was very surprised to find out that non of the SPFile properties or the SPListItem properties contains the document suffix (the last one make sense).

Then i remembered that sharepoint document library (as so list) have hidden/frombase/readonly fields that contains all kind of parameters, like:

BaseName - Document prefix.
FileLeafRef - Prefix.Suffix.
EncodedAbsUrl - Full document url.
DocIcon - Document suffix.
Author - Created by.
Editor - Modified by.
FileDirRef - Directory id and directory name (seperated by  ;#).
ContentTypeId - Content type id.
FileSizeDisplay - File size.
GUID - File guid.

So i used the DocIcon field to get the suffix and to check if the document support OpenXml.

Not enough details in error message

We all have got the famous error message "An unexpected error has occurred", or a message that was to short like "The file is not exist".

In most cases it will be very helpful if we know more details, specially when getting "An unexpected error has occurred" then doesn't help us at all.

So to get more details open the web.config, find the root configuration\SharePoint\SafeMode and change the attribute CallStack from false to true. Then find configuration\system.web\customErrors and change the attribute mode from on to off.

Saturday, February 21, 2009

Operation is not valid due to the current state of the object

It's one of the common errors that we get when we developp with sharepoint object model.

To resolve this error you can check :

1. Application Pool Identity


When you use sharepoint object model from WEB SERVICE , you have to check that the identity of it application pool has the required rights to call the MOSS methods. In particular, the right to open site(SPite site = new SPsite).

2. Disposing of yours Sharepoint Objects

Check that you have correctly disposed yours Sharepoint Objects.
(see
Best Practices: Using Disposable Windows SharePoint Services Objects )

Specifically, if you writed code like this:
using (SPSite site = new SPSite(SPContext.Current.Site))
{
using (SPWeb web = site.OpenWeb(site.OpenWeb()))
{
string ItemID = web.Lists["myListName"].Items[0]["myItemID"].ToString();
}
}


It's preferable to modify this code by:
try
{
SPWeb webContext = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webContext.Site.ID))
{
using (SPWeb web = site.OpenWeb(webContext.ID))
{
string ItemID = web.Lists["myListName"].Items[0]["myItemID"].ToString();
}
}
});
}
catch (Exception ex)
{
}
finally
{
if (webContext != null)
webContext.Dispose();
}

Wednesday, February 18, 2009

How to add an PDF icon to MOSS document libraries

To specify the .gif file that you want to use for the icon that represents PDF documents in yours Document librairies, follows theses steps:

1. Copy the .gif file that you want to use for the icon to the following folder on the server:
Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\60\Template\Images


2. Edit the Docicon.xml file (located on \Program Files\Common Files\Microsoft Shared\Web server extensions\60\Template\Xml or \Program Files\Common Files\Microsoft Shared\Web server extensions\12\Template\Xml ) and add the following line in the < ByExtension > section

< key="pdf" value="MyPicture.gif">
*replace "MyPicture.gif" by the name of your picture

3. IISRESET


Reference : http://support.microsoft.com/kb/837849

Monday, February 16, 2009

CreatePage doesn't work

A strange behaviour we recently bumped into was that the "CreatePage" action redirect a user to the "Access Denide" page eventhough this user is a member of the site contributors.

In order to solve this situation follow these steps:

1. Go to Site Actions -> Site Settings ->Modify all site settings
2. Go to Galleries -> Master pages and page layouts
3. From the list toolbar, select Settings -> Document library settings
4. Select permissions for this document library
5. Add 'Restricted Read' access to the required groups

How to add SharePoint aspx template to a document library?


SharePoint allows us to upload to a document library an aspx and html custom pages and view them as SharePoint page.
However, when we tried to upload a custom page with SharePoint master page (like~/_layouts/application.master) or code it didn't worked, and we got a "Configuration Error" page.

The solution:


1. Add the following to the custom page:

<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="WebPartPages"
Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint,
Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@
Register Tagprefix="OSRVWC" Namespace="Microsoft.Office.Server.WebControls"
Assembly="Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="SPSWC" Namespace="Microsoft.SharePoint.Portal.WebControls"
Assembly="Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="SEARCHWC"
Namespace="Microsoft.Office.Server.Search.WebControls" Assembly="Microsoft.Office.Server.Search,
Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@
Register Tagprefix="PublishingWebControls" Namespace="Microsoft.SharePoint.Publishing.WebControls"
Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>


2. Then open the web.config and replace the tab <PageParserPath/> with the following path:

<PageParserPath
VirtualPath="/sites/*" IncludeSubFolders="true" CompilationMode="Always"
AllowServerSideScript="true" />


See also : http://www.bluedoglimited.com/SharePointThoughts/ViewPost.aspx?ID=242


Sunday, February 15, 2009

Working with large lists in Office SharePoint Server 2007

Microsoft published a very interresting white paper about working with large lists in moss:
http://technet.microsoft.com/en-us/library/cc262813.aspx
This white paper compare performance of differents methods that are used when working with SPList:
  • SPList with For/Each
  • SPList with SPQuery
  • SPList with DataTable
  • SPListItems with DataTable
  • Lists Web service
The results show that using SPQuery with indexed columns are recommended to improve performance of retriewing datas from large Sharepoint List.

Unauthorized (401.1) Exception when calling Sharepoint Web Services

We get this error when we work with moss farm deployment scenario that implements load balancing.
In fact, it's a security fix in adress resolution mechanism that prevent a machine to resolve the loopback address from accepting a connection unless that machine name matches the NETBIOS name

One solution is to use the server name instead of the load balanced IP.

Another solution is to modify configuration entries on all servers of our farm as described below:
  • Add the DisableLoopbackCheck registry entry discussed in this Microsoft KB article.
    Note: you will need to reboot your server before the DisableLoopbackCheck takes effect.
  • Be sure to add your load balanced host name for your web farm to the Hosts file on each front end web server. Use the loop-back IP address (127.0.0.1).
    This will ensure that each web server looks at itself to access the web services preventing any trips back out to the load-balancer - and possibly calling the web service another web server in the farm.
Mark Wagner posted on his blog an article that describes this issue : http://www.crsw.com/mark/default.aspx

See also Microsoft KB article :http://support.microsoft.com/default.aspx?scid=kb;EN-US;896861

SharePoint Dispose Checker Tool (SPDisposeCheck)

SharePoint Dispose Checker Tool (SPDisposeCheck) is finally available!
You can download it from http://code.msdn.microsoft.com/SPDisposeCheck.

"SPDisposeCheck is a tool to help you to check your assemblies that use the SharePoint API so that you can build better code. It provides assistance in correctly disposing of certain SharePoint objects to help you follow published best practice. This tool may not show all memory leaks in your code. Further investigation is advised if you continue to experience issues." (Paul Andrew)

For resuming, this tool allows moss developpers to check that they correctly use the recommended best practices, in particular:

Best Practices: Using Disposable Windows SharePoint Services Objects
Best Practices: Common Coding Issues When Using the SharePoint Object Model