Prash's Blog

Create SPList grouped by a field in SPView November 13, 2009

Filed under: SharePoint — prazjain @ 3:06 pm
Tags: ,

Here I do a groupby on SPList so that it can be viewed in TreeView UI with collapsible groups.

Step through of code:

  1. Get the reference to SPList
  2. Define a CAML query to group the list by “Title” of the SPListItem. More than one field can be added by adding as many <FieldRef ../> tags inside the same GroupBy Tag.
  3. Add the fields you would want to see in the view, and set the view as default view for the list.

Code snippet:


/// <summary>

/// Creates a new default view for the history list. This default view is grouped by title of the list.

/// </summary>

/// <param name="web"></param>

private void SetupGroupByView(SPWeb web)

{

SPList historyList = web.Lists["History"];

string viewQuery = @"

<GroupBy Collapse=""True"" GroupLimit=""100"">

<FieldRef Name=""Title"" Ascending=""True""/>

</GroupBy>";

StringCollection viewFields = new StringCollection();

viewFields.Add("Information");

historyList.Views.Add("Grouped By Title", viewFields, viewQuery, 100, true, true, SPViewCollection.SPViewType.Html, false);

}

Advertisements
 

Programmatically add fields to SPList and its Default View

Filed under: SharePoint — prazjain @ 2:33 pm
Tags: ,

I would show using a code snippet how to create a new SPList in SPWeb, add new fields to the list and then add those fields in the default view of the list.

Step through of the code:

  1. Create a new list in SPWeb
  2. Add new fields in the list
  3. Add the fields in the default view of the list

I have taken an example of creating a text field, you can as well use any data type i.e Checkbox, Choice etc.

Code Sample:


/// <summary>

/// Sets up the list

/// </summary>

/// <param name="web"></param>

private Guid SetUpHistoryList(SPWeb web)

{

Guid historyListGuid = web.Lists.Add("History", "History", SPListTemplateType.GenericList);

web.Update();

SPList historyList = web.Lists[historyListGuid];

historyList.Fields.Add("Information", SPFieldType.Text, false);

SPView defaultView = historyList.DefaultView;

defaultView.ViewFields.Add(historyList.Fields["Information"]);

defaultView.Update();

return historyListGuid;

}

 

Programmatically Add SPList as Webpart on SPWeb using ListViewWebPart

Filed under: SharePoint — prazjain @ 2:11 pm
Tags: ,

Here I would show how to add a list (that you already have in your site), on your default.aspx page for your web.

Step through of the code:

1) Get the file reference to the page where you want to display the webpart.

2) Check if the file exists, if not then we do not make any changes.

3) Get the reference to your list

4) Create a ListViewWebPart

5) Set ZoneID for ListViewWebPart to where you want to display the webpart i.e Left, Top etc.

6) Set ListName to the list you want to display in the webpart.

7) Set the ViewGuid to the guid of the View you are adding in the webpart

8) Get SPLimitedWebPartManager for the web.

9) Add the webpart to the SPLimitedWebPartManager

Code Sample


/// <summary>

/// Sets up the web part to display in default view

/// </summary>

/// <param name="web"></param>

private static void SetUpWebparts(SPWeb web)

{

SPFile file = web.GetFile("default.aspx");

if (file.Exists)

{

SPList projectHistoryList = web.Lists[StringConstants.ProjectHistory];

ListViewWebPart wp = new ListViewWebPart();

wp.ZoneID = "Top";

wp.ListName = projectHistoryList.ID.ToString("B").ToUpper();

wp.ViewGuid = projectHistoryList.DefaultView.ID.ToString("B").ToUpper();

SPLimitedWebPartManager coll = web.GetLimitedWebPartManager(web.Url + "default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

coll.AddWebPart(wp, "Top", 1);

}

}

 

SharePoint SPItemEventReceiver ItemUpdating and ItemUpdated being called multiple times July 30, 2009

Filed under: SharePoint — prazjain @ 5:04 pm
Tags:

Problem : SPItemEventReceiver’s ItemUpdating and ItemUpdated methods are called twice! (to be precise)

And if you have Update() or SystemUpdate() call on the document / item, this leads to getting an exception message on screen about “XYZ has already been modified”. This happens due to race condition between the two threads when updating the document / item.

Background

In SharePoint, an event receiver can be hooked to a SPList to listen to any events occuring on the SPList.

This is how you do it :

SPWeb spWeb = GetSPWebInstance();
// assuming that you have a document library by name of "My List"
SPList sharedDocuments = web.Lists["My List"];
// attach a ItemUpdated event.
SPEventReceiverDefinition spEventReceiverDef = sharedDocuments.EventReceivers.Add();
spEventReceiverDef.Class = "Fully.Qualified.Class.Name";
spEventReceiverDef.Assembly = "AssemblyName, Version=x.x.x.x, Culture=neutral, PublicKeyToken=thePublicKeyToken"
spEventReceiverDef.Sequence = 5000; // put any number here
spEventReceiverDef.Type = SPEventReceiverType.ItemUpdated;
spEventReceiverDef.Update();

To attach an ItemUpdating event receiver, all you need to do it replace the type from SPEventReceiverType.ItemUpdated to SPEventReceiverType.ItemUpdating, and ofcourse the class / assembly information if you have the implementation in a different class / assembly.

ItemUpdating gets called synchronously just before an item is updated. And ItemUpdated gets called after the item is updated.

Cause

When force checkout is enabled on document library, this is how the document editing works :

When you checkout a document for editing, a local copy of the document is created that saves all the changes made by the user. At the time of checking-in the document, this local copy updates the original copy (even if there are no changes), then there is another request that does check-in on the document.

This is the reason why ItemUpdating and ItemUpdated are called twice (once for each step of check-in process).

Solution

A Property : “vti_sourcecontrolcheckedoutby” is provided that can be used to distinguish if the update is because of check-in or due to other reasons.

If this property exist in BeforeProperties and not in AfterProperties of SPItemEventProperties instance then it means that the callback is for item check-in event, else it is for event other than item check-in.

So if you have a piece of code that you want to be executed only when the check-in is done then enclose it in a conditional statement like this :

public override void ItemUpdated(SPItemEventProperties properties)
 {
// perform actions only if the update event is triggered by check-in
 if (properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null &&
 properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] != null)
 {
// your code goes here
}
else
{
//ignore
}
}

Putting your code block in correct conditional section would make sure that your code gets executed for the check-in event callback.

 

Unable to preview / add SearchFacets webpart in SharePoint July 27, 2009

Filed under: SharePoint — prazjain @ 11:00 pm
Tags: ,

Recently when I tried to install the search facets webpart in my development environment, I was to find that it would not be as quick as I had thought it would be.

I followed all the steps in the guide but it would not allow me to preview the SearchFacets webpart (it allows me to preview the other two webparts). If I try to skip it, and go ahead with adding and using it, I just would not be able to add it!

I have raised this over here : http://facetedsearch.codeplex.com/Thread/View.aspx?ThreadId=62960&ANCHOR#Post216315 but still have to receive a reply that could possibly help me.

Apparently my colleague (whose VM I had copied over to my machine) was able to preview it and add it!

So given that we are both using the same VM copy, one is able to install and add it other one is not. Or maybe its some silly configuration I missed ?

In the mean time  while waiting for the reply, I have tried reinstalling my sql server and sharepoint server on the virtual machine. But it has not worked out yet.

In the worse case scenario, I would have tried creating a new VM image altogether and do it from scratch, but without knowing why it happened I cannot be sure it would not happen next time.

If anyone had faced the same problem and was able to resolve it, do post your comments about it.

 

Sharepoint IdentityNotMappedException Some or all identity references could not be translated July 16, 2009

Filed under: SharePoint — prazjain @ 8:15 pm
Tags:

Error : Failed to create sample data

Exception : An exception of type System.Security.Principal.IdentityNotMappedException was thrown.  Additional exception information: Some or all identity references could not be translated.

How I got this error

Today while working on sharepoint to get Search working, I had a suspicion that my sharepoint installation might have got corrupted.

( Reason behind that is I had to rename my VM machine after installing sharepoint. As my VM was a copy of my colleague’s VM so we had same DB server names and other things which could mess things up.

So I followed the steps from one of the websites and it all seemed fine, until today when I could see some places where machine name / user names  etc were messed up because of which I could not get the search working in sharepoint.
)

So that meant either I revert back to a previous snapshot on my VM (and install all softwares I had installed since then ) or try installing Sql Server and Sharepoint again.

I chose the second option.

Both installed fine, but when it came to Configuration Wizard of Sharepoint, it failed at Task 8 : Failed to create sample data.

Exception

An exception of type System.Security.Principal.IdentityNotMappedException was thrown.  Additional exception information: Some or all identity references could not be translated.
System.Security.Principal.IdentityNotMappedException: Some or all identity references could not be translated.

Resolution

After googling it for some, I did these changes :

1) Remove all websites that had anything to do with sharepoint on my developer machine.

2) Remove application pools that had anything to do with sharepoint.

3) Added my current user LMACHINE\Administrator to my sql server 2005 instance as sys admin.

4) One of the application pools could not be deleted namely “Sharepoint – 80”, I investigated further and found that username was incorrect for this application pool. I corrected it and re-entered password.

Finally ran the Sharepoint Configuration wizard  again, and this time it worked !

What a relief.

The re-install of Sql Server 2005 and Sharepoint on my dev box, which according to estimates should have taken 30 mins, actually took 3 hours but how can you put that in a project plan.

 

Using SPFolder UniqueContentTypeOrder to Hide menu options July 15, 2009

Filed under: SharePoint — prazjain @ 5:41 pm
Tags: ,

I would explain the usage of this property by an example.
The example would be to hide a few items from the new menu button in menu bar.

I write a function that takes in a folder type and the list of content types that you want to hide from the

menu bar.

Now if you try to remove everything from the new menu button, you would get a runtime exception (just

like i got, so do not try that. Instead you might want to hide the new menu button!)

private void HideAllContentTypes(SPFolder rootFolder, IList<string> contentTypeNames)
 {
 IList<SPContentType> contentTypeCollection = rootFolder.ContentTypeOrder;

 List<SPContentType> contentTypes = new List<SPContentType>();

 foreach (SPContentType contentType in contentTypeCollection)
 {
 if (contentTypeNames.Contains(contentType.Name))
 continue;
 else
 contentTypes.Add(contentType);
 }

 rootFolder.UniqueContentTypeOrder = contentTypes;
 rootFolder.Update();
 }

Explanation of the code goes here :

1) IList<SPContentType> contentTypeCollection = rootFolder.ContentTypeOrder;
This step is important because you need to call SPFolder’s ContentTypeOrder property so that it initializes

internal storage structure and then when you later on call UniqueContentTypeOrder and set a collection on

it, you would not get a runtime exception.

2) Iterate through the SPContentType collection and create a new collection that does not include the

content types that you hate 🙂

3) Now you can assign SPFolder’s UniqueContentTypeOrder property with your new SPContentType

collection. Note you would get an runtime exception here if you tried to be smart and did not perform step 1.

4) Never forget to call Update() once you are done.