Category Archives: SharePoint Development

ReadOnly, Hidden and Sealed Fields

That’s another question that I Answered in MSDN Social forums and thought of sharing with you here 🙂
Q :
The documentation regarding those attributes is not informative enough.
Hidden :
Optional Boolean . If TRUE , the field is completely hidden from the user interface. Setting ReadOnly to TRUE means the field is not displayed in New or Edit forms but can still be included in views.
ReadOnly :
Optional Boolean . If TRUE , the field is not displayed in New or Edit forms but can be included in views. Setting the Hidden attribute to TRUE completely hides the field from the UI.
Anybody knows the differences ?And what about CanToggleHidden attribute ?

A :

Similarities : Both aren’t displayed anywhere unless you configure a view to show any of them.
Differences : Hidden Fields can be updated through the object model but ReadOnly fields can’t be updated through OM like “Created” And “Created By” fields.

If you are still confused, consider the following example :You have a field that you use only by the object model for setting or getting a flag and you don’t want the field to be visible to anybody and non updatable through the UI, however you want it to be updatable through the object model.
For me, I was creating a list that stores the applications of Scholarships offered by a foundation and we needed the status of each application to be totally hidden but updatable through the OM.
Theoritically, this should be an east task :
SPSite site=SPContext.Current.Site;
SPWeb web=site.OpenWeb();
SPList list =web.Lists[“ScholarshipApplicationsList”];
string id=list.Fields.Add(“Status”,SPFieldType.Boolean,false);
SPField statusField = list.Fields.GetField(id);
statusField.Hidden=true;
statusField.Update();

But if you try this you’ll receive a nice exception
Why? The Hidden property checks if CanToggleHidden property is true and throws an exception if its not.
Fair enough, all we do then is set the CanToggleHidden property to true and do the update but there is no such a property in the object model.
So I’ve decided to use “Reflection” ..
SPField statusField= web.Lists[“ScholarshipApplicationsList”].Fields[“Status”];
Type type = spfield.GetType();
MethodInfo mi = type.GetMethod(”SetFieldBoolValue”,
BindingFlags.NonPublic BindingFlags.Instance);
mi.Invoke(spfield, new object[] { “CanToggleHidden”, true });
statusField.Hidden = true;
statusField.Update();
And if you want to use CAML, this is much more easier :
<field displayname=”Status” type=”Boolean” required=”FALSE” name=”NewField” cantogglehidden=”TRUE” hidden=”TRUE”>

Q :
Thanks Ayman El-Hattab.I’ve created a few hidden fields but now I’m trying to delete them using the following code :
list.Fields[“Status”].Delete();
But I’m gettin the following exception :
“You cannot delete a hidden column ”

A :
Unhide the field , then delete it. CanToggleHidden attribute is now set to true, so you can hide and unhide the field as you wish.

Lovely 12 Hive :)

A couple of hours ago, while surfing the MSDN Forums and I experienced a very interesting Question, well, let’s me share with you here the Question and my answer.

Q : We are creating a custom field type in a multilingual publishing site, we need to use the DisplayPattern to render the field value plus other Data that is language specific? Any ideas ?

A : Again , “The 12 hive is our teacher”.You know the little “New!” Icon that is displayed beside an Item when it’s newly created ?I’ve once created an Arabic/English site and I found out that the image is rendered in Arabic in the Arabic context and in English in the English Context which is great. Then you can definetly do that too either by Code or by CAML.
Let’s see if we can achieve that by means of CAML.
Open the 12 hive, Templates, Featues and open the folder of the fields feature, then open fieldswss.xml.
check the field titled “LinkTitleNoMenu” and let’s have a look at its display pattern.I’ve copied a part of it here, what I care about is the undlerlined part of the CAML below ..

<DisplayPattern>
<IfEqual>
<Expr1><LookupColumn Name=”FSObjType”/></Expr1>
<Expr2>1</Expr2>
<Then><Field Name=”LinkFilenameNoMenu”/></Then>
<Else>
<HTML><![CDATA[<a onfocus=”OnLink(this)” href=”]]></HTML><URL/>
<HTML><![CDATA[” ONCLICK=”GoToLink(this);return false;” target=”_self”>]]>
</HTML>
<Column HTMLEncode=’TRUE’ Name=”Title” Default=’$Resources:core,NoTitle;’>
</Column>
<HTML><![CDATA[</a>]]></HTML>
<IfNew>
<HTML><![CDATA[<IMG SRC=”/_layouts/[%=System.Threading.Thread.CurrentThread.CurrentUICulture.LCID%]/images/new.gif” alt=”]]></HTML>
<HTML>$Resources:core,new_gif_alttext</HTML>
<HTML><![CDATA[“>]]></HTML>
</IfNew>
</Else>
</IfEqual>
</DisplayPattern>

Got it ?You can write server-side code inside your display pattern :0 TERRIFIC
By the way I just discovered that when trying to answer your question but a little humble piece of advice to you is ” Love your 12 hive, Check out the OOB features, 12 Hive can really teach us a lot of cool stuff related to the UX

That was my answer and I’m waiting for him/her to mark it as answered LOL!
see you

Hey SharePoint, please do not to handle that exception for me, I’ll take care of it!

It’s a good practice to catch the UnauthorizedAccessException within your sharepoint code , it might be thrown if the logged in user does not have enought permissions to get some code execued in his security context .
However, the SharePoint platform handles this exception on the developer’s behalf by redirecting to _layouts/AccessDenied.aspx page .
To override this behavior, you can set the property SPSecurity.CatchAccessDeniedException to false, telling SharePoint “Please do not to handle the exception for me, I’ll take care of it“.

Example :
bool AccessDeniedflag = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
try
{
SPList list = web.GetList(web.ServerRelativeUrl+”/Lists/ListName”);
SPListItem item = list.Items[0];
item[“title”] = “ayman-elhattab.blogspot.com”;
item.Update();
}
catch(UnauthorizedAccessException ex)
{
// Redirect to your custom page
SPUtility.Redirect(“MyAccessDeniedPage.aspx”,SPRedirectFlags.RelativeToLayoutsPage,this.Context);
}
finally
{
SPSecurity.CatchAccessDeniedException = AccessDeniedflag;
}

Protecting SharePoint lists against deleteion!

That was a problem that we encountered in one of our projects. We needed to prevent some lists and libraries from being deleted even by site collection adminsitartors.

Actually there are two ways to do that :

1) Using Event Handlers
Firstly I though of extending SPListEventReceiver, I expected the presence of a function called “ListDeleting”. Unfortunately, there is no such thing as “ListDeleting”.

Ali Al-Kahki ( My ITWorx colleague ) came up with a very nice workaround listed below :

public override void ItemDeleting(SPItemEventProperties properties)
{
if (properties.ListItemId == 0)
{
properties.Cancel = true;
properties.ErrorMessage = “You are not allowed to delete the list”;
}
}

2) Using SPList.AllowDeletion

When I was exploring the SharePoint object model, I discovered a very interesting property in the SPList class. When setting this property to false, the “Delete list” option will not be displayed in the list settings page .Even if you try to delete the list programmatically an exception will be thrown as long as this property is set to false.

SPList list = web.GetList(web.ServerRelativeUrl+”/Lists/ListName”);
list.AllowDeletion = false;
list.update();

I prefer the second approach but I like Ali’s workaround 🙂

MSDN Social Forums : Conversation about using resources in features definition files!

This morning, i was surfing the SharePoint forum @ msdn social forums searching for some stuff. A guy there was asking how he could globalize his features definition files ( removing language specific contenrs ) and obtaining those values dynamically from resources files. His company was developing a language pack for a service they offer built on MOSS 2007.
I answered his question , he marked it as answered so I just thought of sharing this conversation with you.
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/c58cf229-b219-4491-b25d-c97c3305901a/#837904e3-0a50-45f5-aca8-fc566407798b

Simplifying SharePoint debugging by creating the troubleshooting toolbox!

This is the title of my first article for http://www.sharepointmagazine.net/ where I introduce some of the troubleshooting utilities and tools that can really make a SharePoint developer’s life easier since troubleshooting can really be a nightmare for those who are new to the sharepoint platform.
Waiting for your feedback 🙂
http://sharepointmagazine.net/technical/development/getting-started-with-sharepoint-programming-simplifying-sharepoint-debugging-by-creating-the-troubleshooting-toolbox

Cannot access SSP administration site collection

Me and my colleagues @ ITWorx came across this weird issue on different environments when trying to access the SSP administration site collection.

Symptoms : When we try to navigate to the SSP administration site default page, we receive the error highlighted in red below. However, we were able to access other SSP administrative pages by typing the URL in the browser.
“Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. 
Parser Error Message: The base type 
‘Microsoft.Office.Server.Internal.UI.SharedServicesAdminDefaultPage’ is not allowed for this page. The type is not registered as safe.”

Resolution: Add the following line to the SafeControls Section in the web.config of the SSP web application.

<SafeControl Assembly=”Microsoft.Office.Server.UI, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” Namespace=”Microsoft.Office.Server.Internal.UI” TypeName=”*” />

It’s also worth mentioning that my friend Amir ElKady bought me a Pepsi Can for solving him this issue 🙂
Thanks Amir

Limited Access ???

A question that I always receive from my colleagues! What is the limited access permission level ?
Users with permissions to access specific lists ONLY, will have Limited Access permission level within the parent site. And this works in the same way for list items and list folders. Remember that a list inherits from a site and a folder inherits from a list and a list item inherits from a folder or a list. The Limited Access permission level cannot be customized or deleted and you cannot assign this permission level to users or SharePoint groups.
For more information about “Limited Access” permission level, I’d recommend usingSPLimitedAccessDiscovery which breaks down why some accounts show up on SharePoint sites as “Limited Access”.

SharePoint List Association Manager

AW Systems has just released an open source tool called SLAM (SharePoint List Association Manager). Check it out now on CodePlex at http://www.codeplex.com/SLAM.

SLAM lets us do just that by allowing developers to describe complex relationships between lists and content types in a way not previously possible in SharePoint (at least not without a great deal of time and effort). With SLAM, these associations are managed automatically. Developers can then concentrate on building web parts and Custom Field Types that draw on those relationships using familiar and straightforward SQL queries.