Using Nintex rich text editor (RTE) control in a Nintex custom workflow action

In this post I will list the steps required to use Nintex rich text editor in a custom workflow activity. Because most of the steps are the same as when using a SingleLineInput control I will focus only on the difference. The difference is in the custom action’s configuration dialog application page. For the rest of the steps (creating the custom activity class, DependencyProperties, adapter class, etc.) you can check the Nintex Workflow SDK where there is also a sample project CustomWorkflowAction.

Steps to use RTE control in the configuration dialog page of a custom Nintex Action:

  1. In your project add reference to Nintex.Workflow.ApplicationPages.dll

  2. In your aspx page add

    <%@ Register TagPrefix=”Nintex” TagName=”RTE” Src=”~/_layouts/15/NINTEXWORKFLOW/RTE.ascx” %>

  3. Add the control

    <Nintex:ConfigurationProperty ID=”ConfigurationProperty8″ runat=”server” FieldTitle=”YourFieldTitle” RequiredField=”True”>

    <TemplateControlArea>

    <Nintex:RTE runat=”server” ID=”RTEControl1″ ApproverContext=”true” HideModeChooser=”True” height=”140″ >

    </Nintex:RTE>

    </TemplateControlArea>

    </Nintex:ConfigurationProperty>

  4. To read the value from the saved configuratioin and fill the control when the form is loaded use this javascript code in the function TPARetrieveConfig():

    setRTEValue(<%= RTEControl1.RTEClientId %>, configXml.selectSingleNode(“/NWActionConfig/Parameters/Parameter[@Name=RTEControl1]/PrimitiveValue/@Value”).text);

  5. To save the value of the control when the form is submitted use this code in the function TPAWriteConfig():

    configXml.selectSingleNode(“/NWActionConfig/Parameters/Parameter[@Name=’RTEControl1‘]/PrimitiveValue/@Value”).text = getRTEValue(<%=RTEControl1.RTEClientId %>);

  6. In the code behind of the page declare the control

    Nintex.Workflow.ApplicationPages.RTE RTEControl1;

The last step is important otherwise Visual studio will declare it automatically in the partial class (YourDialogPage.aspx.design.cs) but it will declare it as System.Web.UI.UserControl.

Because RTE control inherits from UserControl the project can be build and deployed without errors but the javascript code for reading and saving the control’s value will fail in runtime and the following Compilation Error would be thrown:

Error: Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1061: ‘System.Web.UI.UserControl’ does not contain a definition for ‘RTEClientId’ and no extension method ‘RTEClientId’ accepting a first argument of type ‘System.Web.UI.UserControl’ could be found (are you missing a using directive or an assembly reference?) Source Error: setRTEValue(<%= RTEControl1.RTEClientId %>, configXml.selectSingleNode(“/NWActionConfig/Parameters/Parameter[@Name=’RTEControl1′]/PrimitiveValue/@Value”).text);

 

Users can’t edit document in SharePoint 2013 with Word 2013

There are so many reasons that can prevent users from editing a document. If you are experiencing the same symptoms and have the same environment as described below then you are probably having the same problem and my solution should work for you too.

Case and Environment

  • SharePoint 2013 (build 15.0.4667.1000)
  • Word 2013, 32 bit (build 15.0.4615.1000)
  • Users can open and edit documents with Word 2010 without any problem
  • Users can open documents as read only but they can’t edit documents in Word 2013. Word 2013 hangs and the process must be killed.
  • IMPORTANT!: The document library or the content type has a choice field with only number choices (relatively big numbers)

Troubleshooting

After some time lost in troubleshooting (checking form another PC, inspecting the document content, checking permissions, inspecting the traffic with Fiddler,…) I didn’t find anything. Then I started removing columns from the content type one by one and testing the result. As soon as I removed one of the choice columns the problem was gone. Obviously Word 2013 is having troubles with SharePoint choice fields. That choice field had 15 choices and all were big numbers (2000,2001,…,2014). I added the choice field back and started to experiment with different range of consecutive numbers and got the following results:

Choice Values Edit in Word 2013
49,50,…,60 OK
49,50,…,62 OK
49,50,…,64 Failed
157,158,…,164 OK
154,155,…,164 Failed
1162,1163,1164 OK
1560,1561,1562,1563,1164 Failed

From the results we see that Word 2013 has more problems with bigger numbers, it can handle 14 choices with smaller numbers (sequence 49,50,..,62) but it can only handle 3 values with bigger numbers (sequence 1162,1163,1164).
The results presented above probably depend on the available resources for Word 2013, so on another more powerful PC it would probably be able to handle more choice values.
I can’t be sure what Word 2013 is trying to do when it has only number choices but we can add a text choice so Word 2013 treats them all as text. As soon as a text choice is added to the field Word 2013 works fine.
In my case I fixed it by adding a text choice “NA” so now the choice field has the following choices “NA”,”2000″,”2001″,…,”2014″.

Solution

Since Word 2010 is working fine with the same SharePoint choice field its clear that this is a Word 2013 issue, a bug we hope will be fixed with future updates.
As a workaround the problem can be fixed by adding at least one text choice value for the choice field which has only number choices.

Delete current minor version of a document

Case

There is a document already published to 1.0 and a user has accidently created a draft version 1.1. This new minor version must be deleted so the document is back to version 1.0.

Investigation

In this particular case the version history contains the following versions: 0.1, 0.2, 0.3, 1.0, 1.1. There is no way to delete versions 1.0 and 1.1 neither using the UI nor programmatically. They both have IsCurrentVersion=True and trying to delete any of these two versions throws an exception clearly stating that a current version of a document cannot be deleted.
After failing to delete it programmatically I tried by unpublishing version 1.0 but that doesn’t solve the problem because version 1.1 is still there.
After some experiments with the library settings I found a workaround to bring the version history as it was before creating the minor version 1.1.

Solution

By temporarily disabling the versioning for the document library I was able to modify and bring the version history as it was before.
This solution only works if there is only one draft version, in our case 1.1. If more minor versions are created (1.2 or more) then this solution will not work.

For demonstration purposes let’s say the version history for a document is: 0.1, 0.2, 0.3, 1.0, 1.1. We want to delete 1.1 and keep the other versions.

Steps:

  1. Disable versioning for the library
  2. Checkout and check-in the document
  3. Turn the versioning back on. Version history now is 0.1, 0.2, 0.3, 1.1
  4. Unpublish the document. Now the Unpublish option is available for 1.1. (After this step the version history is 0.1, 0.2, 0.3, 0.4)
  5. Checkout then Major-check in the document. (After this step the version history is 0.1, 0.2, 0.3, 0.4, 1.0)
  6. Delete the minor version created in step 5 (In our example version 0.4). (The resulting version history: 0.1, 0.2, 0.3, 1.0, i.e. same as before 1.1 has been created)

If the contents of 1.0 and 1.1 are different then before performing the steps above save the file version 1.0 locally and uploaded it to the library after step 4.

On a production environment it’s important to choose a proper time to perform these steps when no user is working with the library otherwise they may create major versions by accident during the time when versioning is off for the library. For more information how temporarily disabling versioning affects a list check my other post Effects of temporarily disabling versioning for a SharePoint document library

If you have event receivers registered for the document library you may want to remove them temporarily if you don’t get the behaviour explained in the steps above. To remove and add back the event receivers for a list check my other post Add, Modify or Delete List Event Receivers with PowerShell

User field in Event Receivers when using Claims based authentication and Classic mode authentication

When accessing a user field in event receivers there are few differences in the returned values when Classic mode authentication is used from the value when Claims based authentication is used. The difference is present in AfterProperties of ItemAdding and ItemUpdating event. This is true for SharePoint 2010 and SharePoint 2013 and its present only for custom lists but not for document libraries. I’ve done some testing and the results are presented in this post.

Testing

For testing I created a custom list that contains one User field, added the event receiver and overrode all the list item event handlers. For every event I tried to get the value of the user field from properties.BeforeProperties, properties.AfterProperties and properties.ListItem. The test is performed when adding/changing/deleting the item’s user field using the UI (New and Edit form) and when adding/changing/deleting the field pragmatically. The test is repeated when using Classic authentication and when using Claims based authentication. Also the test is repeated for SharePoint 2010 and SharePoint 2013.

Test results

From the results it turns out that when getting the value of a user field from AfterProperties in ItemAdding and ItemUpdating events the value is different when using the New and Edit form from the value when adding and updating the field pragmatically. This difference is present only when using Claims based authentication.
Below are shown the results only for the events that have this problem. At the end of this post you can find the complete test results for SharePoint 2013. In the tests user1 and user2 are used and they happen to have ID of 41 and 42.

Results when using claims based authentication :

When adding, modifying and deleting item using the UI:

Event From Value
ItemAdding AfterProperties -1;#i:0#.w|domain\user1
ItemUpdating AfterProperties -1;#i:0#.w|domain\user2

When adding,modifying and deleting an item programatically:

Event From Value
ItemAdding AfterProperties 41
ItemUpdating AfterProperties 42
Results when using classic authentication:

When adding,modifying and deleting an item using the UI:

Event From Value
ItemAdding AfterProperties 41
ItemUpdating AfterProperties 42

When adding,modifying and deleting an item programatically:

Event From Value
ItemAdding AfterProperties 41
ItemUpdating AfterProperties 42

You can see that the problem is only with claims based authentication while with classic authentication the results are the same when the item is added/modified using the UI and when it’s added/modified programmatically.
One small difference between SharePoint 2010 and SharePoint 2013 is that in SharePoint 2010 even if the user field is not changed the AfterProperties in ItemUpdating event will have the value “-1;#i:0#.w|domain\user1”. In SharePoint 2013 if the field is not changed then the AfterProperties in ItemUpdating event contain the user ID.

Consequences

Because of these differences it’s possible that your old code which has worked fine with classic authentication will not work with claims based authentication.
For example with classic based authentication in ItemAdding and ItemUpdating events the modified value of a user field can be retrieved as below:

 SPUser user = new SPFieldUserValue(properties.Web, properties.AfterProperties["UserField"].ToString()).User;

This code will not work when using Claims based authentication because the value of properties.AfeterProperties[“UserField”] is “-1;#i:0#.w|domain\user1”

Solution

Because its happening only when adding and modifying a user field using the New and Edit form it seems that the problem is with the PeapleEditor control. For some reason it doesn’t work as well with claims based authentication as it does with classic authentication.
To solve the problem I changed my code for getting the user from AfterProperties so it would work for Claims authentication no matter is the field changed using the PeapleEditor control or programmatically.

public static SPUser GetUserFromAfterProperties(object property, SPWeb web)
{
	SPUser user = null;
	string fieldValue = property == null ? null : property.ToString();

	//If adding/editing item directly in the list using NewItem/EditItem form
	if (fieldValue.Contains(";#"))
	{
		string loginName = fieldValue.Contains(";#") ? fieldValue.Split(new string[] { ";#" }, StringSplitOptions.None)[1] : null;
		user = web.EnsureUser(loginName);
	}
	//If adding/editing item programatically
	else
	{
		user = new SPFieldUserValue(web, poperty.ToString()).User;
	}

	return user;
}

To get the user from after properties call the above function in your event receiver:

SPUser user = GetUserFromAfterProperties(properties.AfterProperties["YourUserField"], properties.Web);

All test results

For reference below are all the results from the tests for SharePoint 2013 for Claims based authentication and Classic authentication, both when working with a list item using the UI and programmatically.

Resluts when using claims based authentication:

When adding, modifying and deleting item using the UI:

Event From Value
ItemAdding AfterProperties -1;#i:0#.w|neodomain0\u1
ItemAdding BeforeProperties N/A
ItemAdding ListItem ListItem = null
ItemAdded AfterProperties 41
ItemAdded BeforeProperties N/A
ItemAdded ListItem 41;#u1
ItemUpdating AfterProperties -1;#i:0#.w|neodomain0\u2
ItemUpdating BeforeProperties N/A
ItemUpdating ListItem 41;#u1
ItemUpdated AfterProperties 42
ItemUpdated BeforeProperties N/A
ItemUpdated ListItem 42;#u2
ItemDeleting AfterProperties N/A
ItemDeleting BeforeProperties N/A
ItemDeleting ListItem 42;#u2
ItemDeleted AfterProperties N/A
ItemDeleted BeforeProperties N/A
ItemDeleted ListItem ListItem = null

When adding,modifying and deleting an item programatically:

Event From Value
ItemAdding AfterProperties 41
ItemAdding BeforeProperties N/A
ItemAdding ListItem ListItem = null
ItemAdded AfterProperties 41
ItemAdded BeforeProperties N/A
ItemAdded ListItem 41;#u1
ItemUpdating AfterProperties 42
ItemUpdating BeforeProperties N/A
ItemUpdating ListItem 41;#u1
ItemUpdated AfterProperties 42
ItemUpdated BeforeProperties N/A
ItemUpdated ListItem 42;#u2
ItemDeleting AfterProperties N/A
ItemDeleting BeforeProperties N/A
ItemDeleting ListItem 42;#u2
ItemDeleted AfterProperties N/A
ItemDeleted BeforeProperties N/A
ItemDeleted ListItem ListItem = null
Results when using classic authentication:

When adding,modifying and deleting an item using the UI:

Event Properties Result
ItemAdding AfterProperties 8
ItemAdding BeforeProperties N/A
ItemAdding ListItem ListItem = null
ItemAdded AfterProperties 8
ItemAdded BeforeProperties N/A
ItemAdded ListItem 8;#u1
ItemUpdating AfterProperties 9
ItemUpdating BeforeProperties N/A
ItemUpdating ListItem 8;#u1
ItemUpdated AfterProperties 9
ItemUpdated BeforeProperties N/A
ItemUpdated ListItem 9;#u2
ItemDeleting AfterProperties N/A
ItemDeleting BeforeProperties N/A
ItemDeleting ListItem 9;#u2
ItemDeleted AfterProperties N/A
ItemDeleted BeforeProperties N/A
ItemDeleted ListItem ListItem = null

When adding,modifying and deleting an item programatically:

Event Properties Result
ItemAdding AfterProperties 8
ItemAdding BeforeProperties N/A
ItemAdding ListItem ListItem = null
ItemAdded AfterProperties 8
ItemAdded BeforeProperties N/A
ItemAdded ListItem 8;#u1
ItemUpdating AfterProperties 9
ItemUpdating BeforeProperties N/A
ItemUpdating ListItem 8;#u1
ItemUpdated AfterProperties 9
ItemUpdated BeforeProperties N/A
ItemUpdated ListItem 9;#u2
ItemDeleting AfterProperties N/A
ItemDeleting BeforeProperties N/A
ItemDeleting ListItem 9;#u2
ItemDeleted AfterProperties N/A
ItemDeleted BeforeProperties N/A
ItemDeleted ListItem ListItem = null

Get all sites of a specific template with PowerShell

The following script gets all the sites of a specific template in a web application and writes the URLs on the screen and saves them in a text file. In this example it searches for all team sites (WebTemplateId=1). To get the sites of another OOTB or custom template use the ID or the name of that template.

All sites are checked no matter the level because SPSite.AllWebs gets the collection of all Web sites that are contained within the site collection, including the top-level site and its subsides.

Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

$webTemplateId = 1
$filePath = C:\AllSites.txt
$webApplication = Get-SPWebApplication http://webApplicationUrl
$sites = $webApplication.Sites
foreach ($site in $sites)
{
    try
    {
        foreach ($web in $site.AllWebs)
        {
            try
            {
                if ($web.WebTemplateId -eq $webTemplateId) # or use ($web.WebTemplate -eq &quot;STS&quot;)
                {
                    Write-Host $web.Url
                    $web.Url | Out-File -FilePath $filePath -Append -Width 256
                }
            }
            finally
            {
                $web.Dispose();
            }
        }
    }
    finally
    {
        if($site -ne $null)
        {
            $site.Dispose();
        }
    }
}

Here are the values of WebTemplateId and the name of out-of-the-box templates in SharePoint 2010. Most of them have the same value for SharePoint 2013 too.

ID Name
0 GLOBAL#0 Global template
1 STS#0 Team Site
1 STS#1 Blank Site
1 STS#2 Document Workspace
2 MPS#0 Basic Meeting Workspace
2 MPS#1 Blank Meeting Workspace
2 MPS#2 Decision Meeting Workspace
2 MPS#3 Social Meeting Workspace
2 MPS#4 Multipage Meeting Workspace
3 CENTRALADMIN#0 Central Admin Site
4 WIKI#0 Wiki Site
9 BLOG#0 Blog
15 SGS#0 Group Work Site
16 TENANTADMIN#0 Tenant Admin Site
2764 ACCSRV#0 Access Services Site
2764 ACCSRV#1 Assets Web Database
2764 ACCSRV#3 Charitable Contributions
2764 ACCSRV#4 Contacts Web Database
2764 ACCSRV#6 Issues Web Database
7 BDR#0 Document Center
14483 OFFILE#0 (obsolete) Records Center
14483 OFFILE#1 Records Center
40 OSRV#0 Shared Services
3100 PPSMASite#0 PerformancePoint
3200 BICenterSite#0 Business Intelligence Center
20 SPS#0 SharePoint Portal Server Site
21 SPSPERS#0 SharePoint Portal Server
22 SPSMSITE#0 Personalization Site
30 SPSTOC#0 Contents area Template
31 SPSTOPIC#0 Topic area template
32 SPSNEWS#0 News Site
39 CMSPUBLISHING#0 Publishing Site
53 BLANKINTERNET#0 Publishing Site
53 BLANKINTERNET#1 Press Releases Site
53 BLANKINTERNET#2 Publishing Site with Workflow
33 SPSNHOME#0 News Site
34 SPSSITES#0 Site Directory
36 SPSCOMMU#0 Community area template
38 SPSREPORTCENTER#0 Report Center
47 SPSPORTAL#0 Collaboration Portal
50 SRCHCEN#0 Enterprise Search Center
51 PROFILES#0 Profiles
52 BLANKINTERNETCONTAINER#0 Publishing Portal
54 SPSMSITEHOST#0 My Site Host
56 ENTERWIKI#0 Enterprise Wiki
90 SRCHCENTERLITE#0 Basic Search Center
90 SRCHCENTERLITE#1 Basic Search Center
2000 SRCHCENTERFAST#0 FAST Search Center
61 visprus#0 Visio Process Repository

String in item’s property bag truncated to 255 characters in a document library

Problem

String value in property bag truncated to 255 characters for some documents in a document library.

Case

There are string values saved in the property bag of documents in a document library. The problem of strings truncated to 255 characters is noticed only in some documents. The problem is tested and is present in SharePoint 2010 and SharePoint 2013. For standard lists (not document libraries) the issue is never noticed.

Investigation

After many tests and investigating the traffic with Fiddler the moment when the trunction happens is discovered. The string is truncated by Office. When a document is modified with Office and saved back in the document library all the values in the property bag of that document are truncated to 255 characters. If many key-value pairs contain strings longer than 255 characters they are all truncated to 255 characters. If checking out the documents for editing is required for the document library then the truncation of the properties does not happen immediately when the changes are saved by the user but when the document is checked in. It is tested with Word, Excel and PowerPoint and the results are the same. The properties are not truncated when the document is viewed or checked in/out without modifying the content of the document.

Solution

The limit of 255 characters is forced by Office and I couldn’t fine (and I think there is no way) to increase this limit. The only solution is to redisign and instead of property in the property bag to use a column of type multi line of text with the property SPFieldMultiLineText.UnlimitedLengthInDocumentLibrary set to TRUE.
Then with a PowerShell script or C# code the values can be copied from the property bag item.Propreties[“YourKey”] to the new field item[“fieldName”].

The already truncated values can be brought back by restoring an older version of the item if the versioning is enabled for the document library.

Conclusion

The item’s property bag should be use to save small pieces of information and is not practical to save strings that may grow big over the time. SharePoint allows saving very long strings in the property bag (tested with string with hundred of milions of characters) but that should not be done especialy in document libraries because of the limits of MS Office.

A better place to save strings longer than 255 characters is a column of type multi line of text with the property SPFieldMultiLineText.UnlimitedLengthInDocumentLibrary set to TRUE. The field can be set to hidden if the users should not be able to view or edit the field value.

More tests (extremes)

While I was at it I continued testing by saving very long strings in the property bag and check how Office reactes on that.

I mentioned above that strings longer than 255 characters in the property bag are not affected by Office when opening the document in read only mode but for extreemlly long strings the Office is affected and it can’t open the document.

After saving string with millions of characters in the property bag Office fails to open the document and one of the following error messages will be shown:

The file Doc1.docx cannot be opened because there are problems with the contents

The file Doc1.docx cannot be opened because there are problems with the contents


Microsoft Word has stopped working

Microsoft Word has stopped working

These error messages are very generic and may be shown for hundreds of different reasons.
The errors are shown randomlly and sometimes Office succeeds to open the document. The random nature of these events can probably be explained with the actual state and available resources to Office on the client machine when it tries to open the problematic documents with extremely long string in the property bag.

LIKE or UNLIKE a list item programmatically

If Likes are enable in the Rating Settings of a list then users can like/unlike a list item using the UI. A list item can also be liked/unliked programmatically.
There are to ways to like/unlike an item programmatically.

1.Using Reputation class.

This is the recommended way.Reputation class is used to set Likes and Ratings for list items.
To like an item:

    Reputation.SetLike(listID, itemID, true);

To unlike an item:

	Reputation.SetLike(listID, itemID, false);

2.Directly by updating the item’s LikesCount and LikedBy fields.

    SPFieldUserValueCollection likedBy = new SPFieldUserValueCollection(web, item["LikedBy"].ToString());

	SPUser user = web.EnsureUser("YOURDOMAIN\\USERNAME");
	SPFieldUserValue newUser = new SPFieldUserValue(web, user.ID, user.Name);
	
	likedBy.Add(newUser);
	int likes = likedBy.Distinct().Count();
	item["LikesCount"] = likes;
	item["LikedBy"] = likedBy;
	item.SystemUpdate(false);

If you increase LikesCount without adding new user in LikedBy field the item will show the increased number of likes temporary but with the first like/unlike from a user using the UI the number of likes will be automatically corrected to reflect the number of users that have liked the item.

To unlike decrease LikeCount field value and remove the user from LikedBy.

Unable to edit document properties using the Edit form.

Problem

For some documents users are unable to edit document properties with the Edit form.

Case

A document library in SharePoint 2010 contains Word documents. Users open the Edit form by clicking ‘Edit Properties’ in ECB menu and change the values of the fields. When clicking Save button the form is submitted successfully without any error but the changes are not saved.

The problem is present for most of the fields but not all the fields. Name and Title can be changed for all the documents.
This happens only for some docx documents.

Investigation

First I tried to edit the properties of the problematic document so I can check for any errors. No error is thrown and the edit form is submitted but the changed field values are not saved. Not errors registered in Event Viewer or ULS logs.

I saved a copy of one of the problematic document and uploaded it to another new library. The document’s properties still can’t be edited. So this is not related with the document library.

I created a new document and I could edit the document’s properties without any problem. I opened the problematic document, copied its content and pasted it in the new document that was working fine. After this the new document is having the same problem and no custom fields could be edited with the list’s edit form. So it is clear that the content of the document is the problem. I started to remove the document content piece by piece and test the result. It turned out that hyperlinks to network shares in the document are causing the problem. As soon as I remove the hyperlinks to network paths from the document content the problem is gone and I can edit the document’s properties.

Tested by adding a hyperlink to a network share in a new document and the problem is not present. So the hyperlinks are not always the problem but only in the old problematic documents.

I discovered that the problematic documents have been originally created with Word 2003 as .doc files. The .doc files have been converted to .docx documents and uploaded to the library. I converted one of the affected documents back to .doc and re uploaded it. The problem was not present and I could edit the properties of the file. As soon as I converted it to .docx again the problem was back.

It’s clear that it has something to do with how hyperlinks to network paths added in a doc file are converted when converting a doc file to docx file. One way to fix it is to open the docx file and remove and re-add the hyperlink with Word 2007 or newer version.

There were thousands of documents in the library and probably many of them converted from doc to docx before they have been uploaded to the document library. There were just few document discovered that had this properties editing problem. Fixing those few problematic documents by opening them and remove then re-add the hyperlinks in the content was acceptable but there was a possibility that more documents will be discovered in the future and fixing manually every one of them would not be a very good solution.

I copied one of the problematic documents and tested it in 9 different farms with different SharePoint build version (from 14.0.4762 to 14.0.7116.5000). In three of the farms the problem was present. In 6 of the farms the document was not having the problem and I could edit its properties. All of the three farms with the problem were with different SharePoint build version but all of them had installed Cumulative Update of April 2012 before. The other farms without the problem had older build versions or much newer build version (SP2 and up). To discover which Cumulative update introduced this issue and which CU fixed the issue I performed the test with one VM with SharePoint build version prior CU April 2012. Here are the results:

  • Initial build version: 14.0.6117.5002 (February 2012) Test result: -issue not present
  • Installed CU April 2012, version 14.0.6120.5006 Test result: –issue present (introduced with this CU)
  • Installed CU June 2012, version 14.0.6123.5000 Test result: -issue still present
  • Installed CU August 2012, version 14.0.6126.5000 Test result: -issue still present
  • Installed CU October 2012, version 14.0.6129.5003 Test result: -issue still present
  • Installed CU December 2012, version 14.0.6131.5003 Test result: -issue still present
  • Installed CU February 2013, version 14.0.6134.5000 Test result: -issue still present
  • Installed CU April 2013, version 14.0.6137.5000 Test result: –issue not present (solved with this CU)

Conclusion

This issue is introduced with SharePoint CU April 2012 and resolved with SharePoint CU April 2013.

The problem is present only with documents originally created as doc files that contain hyperlinks to network shared folders and are converted to docx before uploading to a SharePoint document library.

Solution

Here are three different ways to fix this problem:

  1. Install the latest SharePoint cumulative updates or at least CU of April 2013. This is the best way to solve this problem for good.
  2. If for some reason you don’t want to update the farm and you have only few documents with this problem you can open the problematic documents with Word 2007 or newer, remove the hyperlinks to network shares and re-add them back (of course not with copy-paste but manually choosing on the Ribbon Insert->Hyperlink).
  3. Convert the problematic docx files back to doc files if that’s acceptable for you. With doc file you will loose all the functionality that docx files offer so you should better consider option 1 and 2 first.

“This file cannot be saved because some properties are missing or invalid”

Error


This file cannot be saved because some properties are missing or invalid.
Use the Document Information Panel to provide the correct property values. Errors for required properties are marked with a red asterisk, and errors for invalid properties are marked with a red dashed border.

Only specific pattern allowed. Only data in the following pattern is allowed: ‘.*\S.*’

Case

There is a document library in SharePoint 2010 site. Users are using Office 2010 32-bit.Saving an open document from client computers doesn’t work for all the client PCs. On some PCs saving the document fails and this error is shown: “This file cannot be saved because some properties are missing or invalid. Use the Document Information Panel to provide the correct property values. Errors for required properties are marked with a red asterisk, and errors for invalid properties are marked with a red dashed border”.
In the Document Information Panel there are no properties marked with red and everything looks fine.

Investigation

There are two cases I discovered that experience this problem and both are caused from the same bug in Office.

Case 1:

Labels are enabled for the content type in the document library and the label specified contains line breaks, for example {Field1}\n{Field2}.
The error occurs even without inserting the label in the document’s content. After removing the line breaks from the label the documents can be saved.

Case 2:

There were some hidden columns in the document library’s content type. I made them Optional and opened a document from a PC that is having the problem. In the Document Information Panel there was one property marked with a red dashed border.

This file cannot be saved because some properties are missing or invalid.

Right clicking and selecting “Full error description…” popped-up the following message: “Only specific pattern allowed. Only data in the following pattern is allowed: ‘.*\S.*’”.

“Only specific pattern allowed.

It turns out that the validation is not allowing line breaks in the property. After removing the line breaks I was able to save the document.

The question now is why the problem was present only on some of the PCs. Checking the Office build version discovered that the problem was present only on client PCs with Office 2010 14.0.7106.5003. Client PCs with Office 2010 without service packs (14.0.476.1000) are not having this problem. This is a bug introduced with Office 2010 updates. Microsoft is aware of this bug and they are working on it and will be fixed with the next Office 2010 updates. It’s been few months since then (October 2013) and the issue is still present. Hopefully they will release the hotfix soon.

Solution

(Bug fixed. Check UPDATE 24/03/2014 at the end of this post.)

Because this is a bug in Office 2010, as a temporary “solution” I uninstalled Office 2010 14.0.7106.5003 and installed a clean Office 2010 14.0.476.1000 without service packs. I’ll stick with 14.0.476.1000 until Microsoft fixes this bug. Hopefully it won’t take too long until they release the hotfix.

UPDATE 22/01/2014:
To find out which update is the problem I performed the following:

-Installed clean Office 2010 (32 bit) 14.0.476.100 – The issue is not present

-Then Installed Service Pack 2 14.0.7015.1000 –The issue is not present

-Then installed the updates after SP2 one by one until the problem started.

Discovered that KB2826026 (08/10/2013) is the update that has introduced this bug.

-To make sure that this is the only problematic update I uninstalled KB2826026 and installed the other latest updates (except KB2826026) and the issue is not present.

Microsoft hasn’t released the fix for this bug yet. Uninstalling KB2826026 solves the problem temporarily until the hotfix is released.

UPDATE 25/02/2014:
“The KB2826026 has been replaced by the KB2837583 (released 11/02/2014) but Microsoft did not remove the bug brought by the first KB. So you have to uninstall the KB2837583 otherwise you will have this bug again …” – visitor’s comment (Nicolas).

In my case uninstalling KB2826026 (now KB2837583) fixed the problem. If in your case that doesn’t solve the problem then try by uninstalling other updates released after September 2013. Check the comments below.

UPDATE 12/03/2014:

KB2837583 (released 11/02/2014) is now replaced with KB2878225(release 11/03/2014) but the bug is still not fixed. So this update (KB2878225) must be uninstalled too.

UPDATE 24/03/2014:

Good news! The bug is fixed with hotfix KB2878228. You have to download and install it manually because its not included with the automatic updates.

Basic operations with Domino .NET API for export purposes

This post is a very short guide on how to access a Notes database and read the data with a .NET application using Lotus Notes Interop. The code snippets are not optimized for use in a .NET application for continues access to Notes database. Its more meant for one time execution for export purposes. I’ve used the code presented here in a migration process from Lotus Notes document management solution to a custom SharePoint document management solution. Of course in that process I’ve developed other tools as needed to manipulate the data and documents before uploading to SharePoint as well as tools to upload and for post-upload data manipulation. As the title states this post is only for the first part, getting information out of Lotus Notes.

The code samples are tested and used on a PC with Windows 7 and Notes 7 client installed.
There is some Lotus Script presented too. For that part Domino Designer 7 is used.

Short Introduction to Notes databases

It’s important to know that Notes database is not a relational database but a document-centric database.
For people with SQL Server background it may be helpful to make a loose parallel between Notes database and a SQL database table.
A Notes database contains views.
Think of a view in Notes database as a SQL database table.
A document in a Lotus Notes database is similar to a row in a SQL table.
Documents in Notes database contain items which are similar to fields in a table in SQL with one big difference being that an item in Notes DB can have one or more objects (array of objects).
As mentioned before this is a very rough comparison between Notes database and SQL database and its meant just for getting an idea what is what in Notes DB in case you have never worked with Lotus Notes before.

Initialize Lotus Notes session

Reference to Interop.Domino.dll is required to be added in the project.

using Domino;

NotesSession lotusNotesSession = new NotesSession();
lotusNotesSession.Initialize("yourPassword");

Get and Open a Notes database

NotesDatabase localDatabase = lotusNotesSession.GetDatabase("ServerName", "DatabaseName.nsf", false);
localDatabase.Open();

In some cases this didn’t work for me and I had to loop through all the databases to get the DB I needed

NotesDbDirectory dbDict = lotusNotesSession.GetDbDirectory("ServerName");
NotesDatabase localDatabase = dbDict.GetFirstDatabase(DB_TYPES.NOTES_DATABASE);
while (localDatabase != null)
{
	if (localDatabase.Title == "DatabaseName")
		break;
	else
		localDatabase = dbDict.GetNextDatabase();
}

localDatabase.Open();

Get all the views of a database

public List<NotesView> GetAllViews(NotesDatabase localDatabase)
{
   object[] viewsArray = localDatabase.Views;
   List<NotesView> views = new List<NotesView>();

   foreach (object viewObject in viewsArray)
   {
      NotesView oneView = oneObject as NotesView;
      views.Add(oneView);
   }
   return views;
}

Get a view with a given name

NotesView view = localDatabase.GetView("ViewName");

Get the items names for a document

		
public List<string>	GetItemNames(int id)
{
	NotesDocument document = view.GetNthDocument(id);
	object items = document.Items;
	Array itemArray = (System.Array)items;
	List<string> itemNames = new List<string>();

	for (int icount = 0; icount < itemArray.Length; icount++)
	{
		NotesItem item = (Domino.NotesItem)itemArray.GetValue(icount);
		itemNames.Add(item.Name);
	}
	return itemNames;
}

Get items value for all documents in a view

For simplicity this method returns list of strings, every string containing metadata for a document. Values of the items are separated with the characters combination “;;;###”. If an item has more than one object in the object array then they are all added by separating them with the characters combination “;###”.
Also for simplicity this method takes all the items values as string. It can be modified as needed to deal with other types.

public List<string> GetDocumentsMetadata(NotesView view, List<string> itemNames)
{
	List<string> metadata = new List<String>();
	
	NotesDocument document = view.GetFirstDocument();
			
	while (document != null)
	{
        string itemsString = string.Empty;
		foreach (string itemName in itemNames)
		{
            string value = string.Empty;
			try
			{
				object[] valueArrey = document.GetItemValue(itemName);
				for (int icount = 0; icount < valueArrey.Length; icount++)
				{
					value += valueArrey[icount] == null ? string.Empty : valueArrey[icount].ToString() + ";###";
				}
			}
			catch
			{
				value = "N/A";
			}
			itemsString += value + ";;;###";
	   }

		document = view.GetNextDocument(document);

		metadata.Add(itemsString);
	}
	
	return metadata;
}

After getting the metadata it can be saved in a file and later processed for Notes-to-SharePoint migration.

Exporting Notes documents as RTF files

I had troubles exporting the document content as rich text file (RTF) using the .NET API for Notes. Its possible to export the text of the document which is stored in an item of type IT_TYPE.RICHTEXT but that doesn’t include the formatting nor the images of the documents. All what it returns is the plain text content of the document.
To export the document content as RTF I had to create an agent with Domino Designer. A great help was Rtftest.zip.
The agent loops through all the documents in a specified view and exports the documents as RTF. The resulting RTF files were not perfect (look and feel wise) but were very close to the original. Some of the problems I noticed were: Styling may not be the same 100 % as when viewed with Notes, some tables may be with no visible borders, and similar small problems. In any case the result was more than acceptable although the users had to inspect the documents quickly and make small changes after the files were converted to .docx files and uploaded to SharePoint.

Exporting Notes document’s embedded files (attachments)

There are two ways to export all the attachments from all Notes Documents in a view using LotusScript:

Using NotesRichTextNavigator

	Dim doc As NotesDocument
	Set doc = view.GetFirstDocument
	Dim title As String
	Do Until doc Is Nothing
		Dim body As NotesRichTextItem
		Set body = doc.GetFirstItem("YourDocBodyFieldName")

		Dim attachment As NotesEmbeddedObject
		Dim rtnav As NotesRichTextNavigator
		Set rtnav = body.CreateNavigator
		If rtnav.FindFirstElement(RTELEM_TYPE_FILEATTACHMENT) Then
			Do
				Set attachment = rtnav.GetElement()
				filepath$ = "C:\YourFolder\" & attachment.Source
				Call attachment.ExtractFile(filepath$)
			Loop While rtnav.FindNextElement()
		End If
		
		Set doc = view.GetNextDocument(doc)
	Loop

By getting EmbeddedObjects from NotesRichTextItem

	Dim doc As NotesDocument
	Set doc = view.GetFirstDocument
	Dim title As String
	Do Until doc Is Nothing
		Dim body As NotesRichTextItem
		Set body = doc.GetFirstItem("YourBodyFieldName")
		
		If Not Isempty (body.EmbeddedObjects) Then
			Forall att In body.EmbeddedObjects
				If att.Type = EMBED_ATTACHMENT Then
					filepath = "fullPathWhereToSaveTheFile"
					Call att.ExtractFile(filepath)
				End If
			End Forall
		End If
				
		Set doc = view.GetNextDocument(doc)
	Loop

This method with EmbeddedObjects is useful if you want to keep track which attachment belongs to which document. You can include that information in the filepath variable, or write a string with more information on the fly as the files are being extracted and than save it as a csv file.

How to catch ‘Access Denied’ exception with try-catch in SharePoint

Problem:

Can’t catch ‘Access Denied” exception in try-catch block.

Case:

When the code tries to access an object that it has no permissions to access ‘access denied’ exception is thrown and by default it is handled by SharePoint by redirecting to ‘Access Denied’ page. That page doesn’t show much information for troubleshooting.
If you put the code that causes ‘access denied’ exception in try-catch block you will not be able to catch that exception because SharePoint has already handled it.

Solution:

To change this default behavior SPSecurity.CatchAccessDeniedException should be set to FALSE before your try-catch block.

bool originalState = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
try
{
	//your code that throws Access Denied exception
}
catch
{
	//get more info about the exception 
}
finally
{
	SPSecurity.CatchAccessDeniedException = originalState;
}
%d bloggers like this: