Using SPMetal with parameters

SPMetal is a very useful tool in Sharepoint 2010, introduced by Microsoft for creating  Entity Data Model of the underlying Sharepoint lists. Though it is still at a very nascent stage, it can still be very productive as far as sharepoint customization in .Net is concerned.

Well you might get many articles telling you how to generate the entity classes  using SPMetal .

Hence I would concentrate more on the configuration part of SPMetal. The default command for generating entities is as follows:

SPMetal /web:http://<ServerName>/<SiteName> /code:<EntityClassName>.cs 

In the above command, we have passed two arguments. The first one tells us the site for which we are generating the entities, the second one specifies the filename in which the entity classes are to be generated. The file thus generated will have entity classes for all the lists in the site. In fact it will have classes for all the content types too. i.e by default it will have classes inheriting from “item” and “Folder” content type. The entity classes in turn would have all the fields in the lists.

There would hardly be a case where you need all the entities and fields. Hence SPMetal gives you a functionality where in which you can limit the number of entities generated, the content types for which entity is generated and the fields that are to be included.

This can be achieved by passing a third argument to the above command. This argument refers an XML file which hosts configuration for the lists and fields which are required.

SPMetal /web:http://<ServerName>/<SiteName> /code:<EntityClassName>.cs /parameters: ParamElements.xml 

The above command has an argument named parameters meaning the parameters based on which the entities would be generated. The content of the xml file could be configured as given below:

SPMetal

Parameters XML to be passed as an argument to the SPMetal command

As can be seen in the above xml, it starts with an element named Web. Apart from the reference to the SPMetal command we have an attribute named class. This is an optional value where you can assign a value to the Data context class which is generated through this attribute. Along with class you can also specify the AccessModifier for the Data Context class.

Inside the web element is the List element. The Name attribute specifies the List of which an entity has to be created. Below the List element, is the ExcludeOtherLists element. By using this element we are telling SPMetal that it only needs to consider lists which are mentioned in the List element.

Within the List element is the element for ContentType where we have mentioned the name as Item. Below the ContentType Tag is the ExcludeContentType element which has name attribute set to Folder. This element tells the SPMetal command to exclude the Folder Content Type.

Similarly, inside the ContentType element, we have explicitly mentioned the columns which are required in the form of class properties of the list entity. We have explicitly asked SPMetal to ignore all the columns which are not mentioned in the columns element. The Name attribute in the column element refers the name of the field as it is used in CAML query. The Member attribute specifies the name we want to keep for this column in the entity class. We can have similar  names for the entity classes generated by having a Member attribute at the list level.

The post is based on my understanding of SPMetal until now. Will update it as and when new things arise.

Creating Event Receiver in sharepoint 2010

Sharepoint 2010 allows us to have EventReceiver on a specific list as against all the lists in the site. To achieve this all we have to do is configure the elements.xml file with details specific to the list on which we intend to trigger an event.

Steps for creating a sample event receiver in Sharepoint 2010

1. Create a new project of type Event Receiver in the sharepoint templates.

2. Select Farm based solutions and pass on an appropriate site URL.

3. Choose Event receiver settings

  • In the Type of event receiver select “List Item Events”.
  • Select the list on which you intend to have the event receiver. In my case I am doing it on my custom list named “source”.
  • Select the events on which you intend to have receivers. I have selected one synchronous event “An item is being added”  and an asynchronous event “An item was added”.
  • Click Finish.
choosing event receiver settings

choosing event receiver settings

4. In the solution explorer, open the Elements.xml file which has got created. You will find a “Receivers” tag inside Elements. Note that by default “ListTemplateId” attribute is set to 100 which is used for generic lists.

5. Replace this attribute with ListUrl with value of the url set to the list on which we intent to have receiver.

6. Note that there would be two “Receiver” sections inside the “Receivers” section corresponding to the two events which we had selected earlier. Refer the Elements.xml file as below

<?xml version=”1.0″ encoding=”utf-8″?>
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;
<Receivers ListUrl=”http://<<servername>>/sites/Home/Lists/Source”&gt;
<Receiver>
<Name>EventReceiver1ItemAdding</Name>
<Type>ItemAdding</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>EventHandlerDemo.EventReceiver1.EventReceiver1</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
<Receiver>
<Name>EventReceiver1ItemAdded</Name>
<Type>ItemAdded</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>EventHandlerDemo.EventReceiver1.EventReceiver1</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
</Receivers>
</Elements>

7. Open the EventReceiver.cs file from the solution explorer. You shall have events corresponding to the events which we found in the Elements.xml file.

8. You can have your custom code in these events as per your requirements.

9. For any additional event you can override the event in the code behind (.cs) file and make its respective entry as a new receiver in the Elements.xml file.

10. Thats to it. Your Event receiver is ready to be deployed.

11. Test it by creating an item in your designated list and one item in non designated list.

Joins in CAML Query

Finally in SharePoint 2010, you can have Joins on List using CAML.

Here is an example:

For Test purpose I have created four lists having relation between them. i.e. Cities, Customers, Product and Orders.
The Customers list contains a lookup field pointing to the Cities list to specify in which city a customer lives. The Orders list contains a lookup field to the Customers and Product list to specify who’s the customer of a given order and what product he has ordered. Please make sure you have these relations in place as lookup fields are the basis on which we apply joins in CAML.

1. Declaring List Object: We have created an object of the Customers list from which records are to be fetched.

SPList CustomerList = SPContext.Current.Web.Lists["Customers"];

2. Setting Join Property: One thing you woul notice below is that SPQuery object has been enhanced with a property named Joins.  This is the property which you need to set.
SPQuery CustomerCityQuery = new SPQuery();
CustomerCityQuery.Joins =

“<Join Type=’INNER’ ListAlias=’Cities‘>” +
“<Eq>” +
“<FieldRef Name=’City‘ RefType=’Id‘ />” +
“<FieldRef List=’Cities‘ Name=’ID‘ />” +
“</Eq>” +
“</Join>”;

The “Join” tag has an attribute named “Type”. It specifies the type of join we intend to have. In my case I have set it to “INNER”, the “ListAlias” property points to the list with which we are having this join i.e. Cities.

In my case, I have a lookup column in my Customers list named City which points to the Id in the list Cities. Hence the first “FieldRef” tag has its “Name” set to City  and “RefType” is set to Id.

The second “FieldRef” tag has attribute “List” set to Cities and “RefType” is set to ID signifying the column of the list on which Join has to be implemented.

3. Setting Projected fields: These are fields in joined lists that can be included in the view when one or more other lists have been joined in a query. In my case I have included CityName, State and Country columns from Cities list while creating lookup from Customers. In the below code I am adding CityName & State to the projected fields property of SPQuery.

StringBuilder ProjectedFields = new StringBuilder();

ProjectedFields.Append(“<Field Name=’CityName‘ Type=’Lookup’ List=’Cities’ ShowField=’CityName‘ />”);
ProjectedFields.Append(“<Field Name=’State’ Type=’Lookup’ List=’Cities‘ ShowField=’State‘ />“);
CustomerCityQuery.ProjectedFields = ProjectedFields.ToString();

4. The code ahead is similar to what we have in normal SPQuery operations without joins.
SPListItemCollection Results = CustomerList.GetItems(CustomerCityQuery);
foreach (SPListItem Result in Results)
{
SPFieldLookupValue CityTitle = new SPFieldLookupValue(Result["CityName"].ToString());
SPFieldLookupValue CityCountry = new SPFieldLookupValue(Result["State"].ToString());
Response.Write(string.Format(“Customer {0} lives in {1} – {2}”,
Result.Title,
CityTitle.LookupValue,
CityCountry.LookupValue));
}

This was my first attempt to have joins using CAML for Sharepoint 2010. Will refine this post as and when possible.

Oops – Object Oriented Political System

Hey friends please do not take this article seriously. Its just that, I was sitting idle, thinking about the current situation in our country. Being a Techie, Its quite natural for me to relate the various real life aspects of this political environment to Classes and entities in our Object oriented world.

I have tried to capture a part of my silly thought into our exciting world of Classes and Objects. The programming language used for this article is C# and the development environment is Visual Studio 2008.

Well then…… Lets get started…

Since Anna Hazare, has been the most talked about person these days, here is a class dedicated to “Anna”

Anna Hazare

Class Anna

The class name is “AnnaHazare“.

It inherits from MahatmaGandhi and implements two interfaces namely ILokmanyaTilak and IMahatmaPhule.

It indicates that our Anna has adopted the ideology of fasting from Mahatma Gandhi, his ability to garner nationwide support from Lokmanya Tilak where as his struggle to bring about social development has came from Mahatma Phule. The Methods “StartFast” and “NationWideProtest” take in one parameter which is “ReasonForProtest” emphasizing the reason for which Anna is protesting. The third method “SocialDevelopment” has no specific reason. The return type of all these methods/functions is “BetterIndia”.  Details of class BetterIndia could be found below.

Harvinder Singh

Class Harvinder singh

The above class is for Harvinder Singh. The guy who slapped Sharad Pawar and Sukhram. Well this person has no political or social stature when compared to Anna. He stands no where when compared to great people like Bhagat Singh, Rajguru and other revolutionaries. But today he represents the young generation of India, who do not get proper opportunity to prosper. Who are frustrated watching our political leaders in-activeness and are annoyed by daily news of huge sums being siphoned out of public coffers. He is just another common man whom we might forget in few days. But he sure was the hero of that moment. He did sent out a strong message to our political class that our patience is running out. In public we might not accept it, but the news did give many of us a reason to cheer.
The first method in this class “SlapPolitician” is for his slapping act. It takes the politicians name as an input parameter. This method is overridden from Bhagat Singh. Well, I know that Bhagat Singh has never performed such act. But as most of us might be aware, Bhagat Singh threw a crude bomb in parliament. His intention was never to kill anybody. His aim was to send out a strong message to the british  about our ability. Similarly Harvinder Singh had his knife with him during his slapping act. He could have used it easily, but that was not his intention.

The other method is “AbusePolitician” for his post slapping commentary. Even this method takes in a politician as a parameter. The return type for both these methods is “HappyIndia” :)

 Lokmanya Tilak, Mahatma Gandhi

Class and Interface representing the influence of our great leaders

Bhagat Singh, Rajguru

Class and Interface representing our young leaders during freedom struggle

Well the above screen shot depicts our great leaders with one of there prime functional behavior taking form of a method.

political leader

Class representing major part of our political class

I know, I am a bit unfair when it comes to the above class. I am sure not all our leaders are corrupt and goons. Few of them, like our current PM, Dr.Manmohan Singh and Pranab mukherjee are arguable the most safest hands to run a diverse country like ours. That too at a time when developed nations around the world are having a tough time to keep there house in order. So the above depiction is definitely not for them, its a kind of perception which has been created about these people because of few rotten eggs. Off course, no one has the courage to throw these rotten eggs out of the basket.:(
The class has properties like NameOfPolitician, IsCorrupt, IsInJail, NumberOfCriminalCases & SizeOfScams etc. which are quite self explanatory. The constructor takes in one parameter of politician, based on which it initializes the “PoliticalLeader” object. The constructor uses various methods like “CheckIfCorrupt”, “GetSizeOfScams”, “GetNumberOfCriminalCases” etc, from the Interfaces implemented, to initialize the object.

types of politicianThe above screenshot has classes like HappyIndia and BetterIndia which describes the mood and the state of the nation respectively. The classes represent the outcomes of the various protests and agitations. The two interfaces, ICorrupt and ICriminal are implemented in PoliticalLeader class. The Methods in these interfaces are implemented to find various related properties like if the politician is Corrupt, The size of his scams, whether he/she is currently in jail etc.

Two enums are used in this example, the first one is ReasonForProtest – It represents the reason for which protest was carried out like Lokpal, RightToReject etc. The second one is a small collection of politicians who are either controversial or are usually in the news for wrong reasons.

Recent protests in IndiaFinally, the above class “Protest”, is a small representation of the protests which were carried out in the recent past.

An object is created for both AnnaHazare and HarvinderSingh. Based on their protesting style,  two methods namely “PeacefullProtest” and “ViolentProtest” are being incorporated. Anna’s protest like his recent fast for Lokpal bill and the proposed nation wide agitation for Right to Reject form the functionality of the first method i.e. “PeacefullProtest”. Where as Harvinder Singhs slapping act to sukhram and Pawar followed by his free flowing abuses for politicians form the functionality of the other method i.e. “ViolentProtest”.

So friends, this is a small attempt by me to put my thoughts in the form of words, by using a popular programming language. Like I have already said, this article is created just for the sake of humor.  I enjoyed the thought and the efforts needed to put it into this blog. Hope you like it too. And if at all you do, please let me know your feedback.

Exploits at Kaas – Valley of flowers

About Kaas

Located 26 km away from Satara, Kaas (Location on Wikimapia) is a huge plateau stretching for more than 10 kms, with amazing variety of flowers and wildlife. This place is a paradise for photographers. The best time to visit Kaas is September to October. The plateau lies on top of a huge mountain. It is surrounded by a huge water reservoir formed behind Kanher dam, on almost three sides. Sajjangad, abode of swami Ramdas, can be seen on the left side of the plateau. Kaas, because of its high altitude, appears to be the highest point in that area. surrounded by valley from all sides. The ghat leading to Kaas from Satara, is quite narrow and appears to be risky at times, because of its steep curves. The reservoir and the forest surrounding it is a natural tranquil for nature lovers. The prominence of this place is increasing every passing season.

This slideshow requires JavaScript.

Our visit to Kaas

We happened to visit this place on 2′Oct 2011. We were not very sure about the time of the visit. Most of us thought its quite late in the season, and we would be missing the peak time when the blossoming is at its maximum. But most of these speculations turned out to be incorrect. The plateau was huge, and covered entirely with lush green natural lawn. There is no sign of man made constructions anywhere around. The serene atmosphere of the dawn along with the fresh aroma of early morning dew was mesmerizing. Just saying ‘this place was beautiful’ would be an understatement. It was very very very very beautiful. It amazed us to no limit. It was our sheer luck that there was mild drizzling just a couple of days back which lent a new lease of life to the flowers. Well, some appreciation to our whole team ;) , we got up early at around 3.30 – 4.00 and were at the venue before 6.00 in the morning because of which we could capture the early morning dew on the flower petals. There were quite a lot of people already at the venue. Most of them were photographers and nature enthusiasts. Its good to see how these people appreciate the nature. Their affection for nature was quite visible in the way the were moving around admiring the unending stretches of flowers. There were a few who were literally spending hours just to get one good shot of the flower. Well, even we were busy trying to capture as much as possible in our cameras. Never mind the quality of images, but we did our best. The place offers ample variety flowers and that too in huge numbers. When seen from a distance, these flowers give a distinct color to that place. A few variety of those flowers can be seen below.

For those who are planning to visit this place, September to mid October is the right time to visit. Satara is the nearest city to this place. You could find many hotels in Satara. With respect to the venue, try to reach there as early as possible. Primarily to experience the early morning freshness. But apart from that, parking cars is also a major issue at Kaas. We were lucky enough to find a place for our cars, but people coming later on had to walk a couple of kilometers from the parking lot.Local authorities have made provisions for a state transport bus from the parking lot upto the plateau. But those are too crowded to carry delicate items like cameras and lenses. Apart from the above, please carry sufficient amount of water and please keep this place clean. There were quite a few people littering around throwing away chocolate wrappers etc. This place is quite huge and cannot be cleaned every now n then. Also try and avoid stamping over the flowers. For more pics on Kaas, please visit my album Kaas- Valley of flowers Driving Directions for Kaas:

Trek to Sudhagad

Plan for the trek

After our Koraigad trek last month, we had decided that henceforth we will not be planning for treks well in advance. It should be done at the last moment or at the most a week in advance. Since the last time it was just four of us (Hems, Andy, Tara & me), this time we wanted more people with us. Swapnil(Swapya) and Prasad(Po2) were insisting on a trek for quite some time.

So we decided upon a date that is 25th June. The Destination was not to be decided till the very end. On Thursday, two days before the trek we had our conference call amongst the members. On the call were Hems, Sachin, Swapnil, Po2, Andy and me. I suggested Tikona or Naneghat as possible places for trek. Swapya suggested a waterfall somewhere near jawahar. Po2 suggested SudhaGad. Sudhagad, I had never heard of this fort before. Po2 said it is somewhere near Pali(A village near Khopoli, known for one of AshtVinayaks eight famous temples. Lord Ballareshwar is the reigning deity of this village). Po2 insisted about this place saying it is not a very big trek, and would be worth a visit. So we finalised on SudhaGad. The next day we spread the news in our group. By Friday evening we were fifteen of us including five of Po2’s office colleagues. So according to the plan, we were going to start from Vasai. Po2 started from his home. He picked Jayesh, Swapnil & Sachin en-route to Evershine gate. Meanwhile I picked Hemant and Anand from their place and returned to our meeting point at Evershine Gate.

Thane - Belapur road

On our way to Sudhagad (Location on Wikimapia)

According to the plan, we set out from Vasai-Virar in two cars. We picked Nilesh at Airoli. Po2′s office colleagues were coming in the third car from Mumbai. We  met them at Belapur. Pranit, who works in night shift these days was going to meet us at belapur. But due to some personal issue, he could not join us.

We reached khopoli by 9:00 where Amit, the only member of todays team from Pune on his bike, had reached far earlier. We proceeded towards Pali, reaching the temple by in around an hour. After a quick darshan, we moved on towards our destination which was still 12 kms ahead. We lost some time in between coz, Casper, Po2′s colleague had lost his way in between. After a brief search operation by Amit and Swappy, we found them. :)   and reached a small hamlet named Pachapur.

Mission Sudhagad


The fort appeared to be huge from the base.  As we left the village behind on our way to the fort, the mud hutments of the villagers were getting replaced by trees. After a while we were actually in a very dense patch of the forest. Since the location of this fort is somewhat remote, and it is not known to many people, there were not many people around us.
This is in sharp contrast to other famous forts like Lohgad or Raigad which always have large number of visitors. Lonely though, but we were enjoying every moment of our trek. The pristine beauty of this place is still intact. After around 20 mins of climbing we reached the first amongst the four hillocks. Local authorities have built a ladder like structure to get over this obstacle. A local guy told us there is a small temple of Lord Shiva on the fort. Every year large number of people from the surrounding area visit this temple during Jatra. This ladder was built for their convenience.

Going ahead we crossed one hill after the other. Each one was different from the previous one. There were plains covered with lush green grass cover. Various types of seasonal flowers were adding to its beauty. The perimeter of the fort is very well fortified with its formidable walls still in reasonably good shape. The path which we had taken was actually the rear side of the fort. The main entrance is not very accessible. After about an hour or so, we came across steps which were leading to a huge Darwaza (Gate), covered by two bastions of the fort around 150-200 meters away. The bastion is built in such a strategic fashion that if enemy is trying to intrude inside, he can be fiercely  defended. There are vents to pour  boiling oil on the enemy, places from where archers can hit enemy troops. Standing on the bastions edge, one could see almost half of the forts perimeter. It also gives a very wide view of horizon, whereby a watch can be kept on approaching army. Such minute things were thought at a time when there were no cranes or vehicles to carry construction material, no advanced communication mechanism, no computer to design a blue print of the structure. Those great minds who envisioned it and the strong hands which built it, certainly deserve a manacha mujra (Salute).

Bastions at Pachapur darwaza

After spending some time over the bastion, we proceeded towards the main fort which was still half an hour away. Nilesh, amongst us was very exhausted. But like all of us he made it to the top.

The perimeter of this fort is quite big. The fort is spread across 55 acres. There are many lakes on the fort. There is a palace of Pant Sachiv on the fort, where 50 people can stay comfortably. Also there is a temple of Bhorai Devi, where 25-30 persons can be accommodated. Different kind of medicinal plants and trees can be seen in the surrounding forest. The entrance from where we had come is called Pachapur Darwaza. Another fort named Tella-baila can be seen from one end of the fort.

On top of Pachapur darwaza

Twin forts : Tella- Baila can be seen in the background

Many aspects of this fort match with those of Raigad. Like Raigad, sudhagad also has a machi called Tak-mak-tok. The main entrance called the Dindi darwaza is very much similar to Maha Darwaza at Raigad. Like raigad, sudhagad has ample supply of water. Because of these similarities, Sudhagad is called a Replica of Raigad. Legend says that Sudhagad was one of the few forts shortlisted by Shivaji Maharaj for his capital. But he selected Raigad due to its proximity to Arabian sea.

We had some snacks which we had carried with us. But we had exhausted all water we had on our way up the fort. There were couple of streams which we came across. But the water didn’t appear to be potable enough. The lakes on top had water, but it was quite murky. A villager took us to a place behind the Pant Sachiv palace. There was a small water stream flowing. This place was kept clean by the local people. It is their source of water in monsoon. Water from this stream was crystal clean.

After roaming around on the fort for a couple of hours, we started our way back. It took us around 45 mins to reach the base village. On  our way back, we had some snacks at khopoli after which Amit went his way to Pune. We proceeded towards our home. By 10.00 we were at our home… Tired, but with a sense of accomplishment…

Sharepoint – Error in SPWorkflowTask.AlterTask Method

Recently I was working on a Sharepoint workflow.
We had to raise an event from our application form, which would trigger the eventHandler. We had used “OnTaskChange” event for that respective task in the workflow.
There were four different conditions on the “OnTaskChange” event which were segregated based on the If-Else condition.
It such happened that I was able to execute the first three conditions. The control was going to the workflow from the Application page, and I was able to debug the flow and the If-Else conditions as well.
But when I raised the fourth condition, It was not getting executed. After debugging I found that It is not reaching the workflow either.
It was giving “Object reference not set to an instance of an object” error on the

“SPWorkflowTask.AlterTask”

Method. The method basically accepts three parameters,
1. The Task Item
2. HashTable
3. Synchronisation Flag

Interestingly none of the three parameters were Null. Even after searching on the internet, I couldn’t get a break through. I checked the correlation token being set for the task on creation and the one passed “OnTaskChanged”.
After spending a lot of time, one of my colleague told me to check for the values being passed in the HashTable. That was it. Before executing the AlterTask method, the Workflow runtime checks the items in the workflow. If it finds any of the Item from the Hashtable missing, it does not allow the AlterTask method to execute.
In my case too, I was passing a null value for one of my flag, which  was getting checked in the workflow. After setting the flag, the workflow started working as expected.