Dynamic Binding of SharePoint Lists with .Net Business Objects

Dynamic Binding of SharePoint Lists with .Net Business Objects

This document highly detailing the binding of .Net business objects with SharePoint list and also provides a framework which provides dynamic support of CRUD operations, In which the developer only needs to define a business object and mapping with list and its fields, rest will be done by the framework itself.
First of all, develop two class Attributes namely ListAttribute and FieldAttribute

a. ListAttribute maps the SharePoint List Name.
b. FieldAttribute maps the column of SharePoint list.

Code Snippet for ListAttribute

[AttributeUsage(AttributeTargets.Class)]
public class ListAttribute
{
string listName;

public ListAttribute(String _listName)
{
this.listName = _listName;
}

public string ListName
{
get { return this.listName; }
}
}

Code snippet for FieldAttribute

[AttributeUsage(AttributeTargets.Property)]
public class FieldAttribute : Attribute
{

public FieldAttribute(String listItemName)
{
this.listItemName = listItemName;
}
string listItemName;

public string ListItemName
{
set { this.listItemName = value; }
get { return this.listItemName; }
}
}

Now let’s develop the custom list named Demo in SharePoint and specify Title, Description, Date columns.

Develop the business object for Demo list. Below code snippet shows the class details. Business Object class is derived from the parent class BaseEntity. Reason of binding is that the framework supports generic methods for all types of CRUD operations, this benefits the business objects that are derived from the BaseEntity to be passed as a parameter.

[ListAttribute("Demo")]
public class TripLogList: BaseEntity
{
string title;
[FieldAttribute("Title")]
public string Title {
set { this.title = value; }
get { return this.title; }
}

string description;
[FieldAttribute("Description")]
public string Description
{
set { this.description = value; }
get { return this.description; }
}

DateTime dateTime;
[FieldAttribute("Date")]
public DateTime DateTime
{
set { this.dateTime = value; }
get { return this.dateTime; }
}

Int32 id;
[FieldAttribute("ID")]
public Int32 Id
{
set { this.id = value; }
get { return this.id; }
}
}

Develop windows form through which we can manipulate SharePoint list items and can perform Insert, update, delete and load operations.

Below screen shows all the items stored in the Demo list

Framework provides the PersistanceManager object through which the developer can directly call Insert, Update, Delete and LoadAll methods and these operations will be performed by the PersistanceManager itself. Developer does not need to manually bind the SharePoint list items with business objects and depending on the fieldname specified, automatic binding will be done on loading, insertion, updation and deletion of list.

To Insert,

Demo demoObj = new Demo();
demoObj.Title = txtitle.Text;
demoObj.Description = txtDescription.Text;
demoObj.DateTime = dtPicker.Value;
PersistanceManager.GetInstance().Insert(demoObj);

To update,

Demo demoObj = new Demo();
demoObj.Id = Convert.ToInt32(row.Cells["id"].Value.ToString());
demoObj.Title= row.Cells["Title"].Value.ToString();
demoObj.Description=row.Cells["Description"].Value.ToString();
demoObj.DateTime = Convert.ToDateTime(row.Cells["DateTime"].Value);
PersistanceManager.GetInstance().Update(demoObj);

To delete,

Demo demoObj = new Demo();
demoObj.Id = Convert.ToInt32(row.Cells["id"].Value.ToString());
PersistanceManager.GetInstance().Delete(demoObj);

To LoadAll,

ArrayList lst=PersistanceManager.GetInstance().LoadAll(typeof(Demo));

grdView.DataSource=lst; // Binding datasoure with datagridview object.

Framework Classes/Interfaces

IDataManager

An interface which contains generic methods. When defining new Persistance Manager for any data source this interface should be derived with it.

interface IDataManager
{
void Insert(BaseEntity baseEntity);
void Update(BaseEntity baseEntity);
void Delete(BaseEntity baseEntity);
ArrayList LoadAll(Type type);
}

SPPersistanceManager

Persistance Manager class for SharePoint. This class implements the Insert, Update, Delete and LoadAll operations. For e.g if you have SQL Server datasource you need to develop a new class named SQLPersistanceManager and defines implements IDataManager methods.

public class SPPersistanceManager : IDataManager
{

String siteURL = System.Configuration.ConfigurationSettings.AppSettings.Get("SharePointSite");

//Load All Items

public ArrayList LoadAll(Type type)
{

ArrayList objlist = new ArrayList();

using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb())
{
String listName=FrameworkFacade.GetInstance().GetListName(type);
ArrayList fieldList = (ArrayList)FrameworkFacade.GetInstance().GetFields(type);
SPList list=web.Lists[listName];
foreach (SPListItem item in list.Items)
{
Demo tripLogObject = new Demo();

foreach (String fieldName in fieldList)
{

FrameworkFacade.GetInstance().SetFieldValue(tripLogObject, fieldName, item[fieldName]);

}
objlist.Add(tripLogObject);
}
}
}
return objlist;
}

//Insert Implementation

public void Insert(BaseEntity obj)
{
ArrayList fieldList = (ArrayList)FrameworkFacade.GetInstance().GetFields(obj.GetType());
using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList myList = web.Lists[FrameworkFacade.GetInstance().GetListName(obj.GetType())];
SPListItem myListItem = myList.Items.Add();

foreach (String fieldName in fieldList)
{
if (!fieldName.Equals("ID"))
{
myListItem[fieldName] = FrameworkFacade.GetInstance().GetFieldValue(obj, fieldName);
}

}
web.AllowUnsafeUpdates = true;
myListItem.Update();
web.AllowUnsafeUpdates = false;
}
}
}

//Update Implementation

public void Update(BaseEntity obj)
{

using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList myList = web.Lists[FrameworkFacade.GetInstance().GetListName(obj.GetType())];
SPListItem item = myList.GetItemById(Convert.ToInt32(FrameworkFacade.GetInstance().GetFieldValue(obj, "ID")));
ArrayList arrFields = FrameworkFacade.GetInstance().GetFields(obj.GetType());
foreach (String fieldName in arrFields)
{
if(fieldName!="ID")
item[fieldName] = FrameworkFacade.GetInstance().GetFieldValue(obj, fieldName);

}

item.Update();
}
}

}

//Delete Implementation

public void Delete(BaseEntity obj)
{

using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList myList = web.Lists[FrameworkFacade.GetInstance().GetListName(obj.GetType())];
Int32 value = Convert.ToInt32(FrameworkFacade.GetInstance().GetFieldValue(obj, "ID").ToString());
myList.Items.DeleteItemById(value);
}
}

}

}

FrameworkFacade

FrameworkFacade is a core class which traverses object metadata through reflection and helps to retrieve properties, custom attributes and setting or getting property values, invoking methods etc.

public class FrameworkFacade
{
static Object _lock = new Object();
static FrameworkFacade instance = null;
private FrameworkFacade() { }
public static FrameworkFacade GetInstance() {
lock (_lock)
{
return (instance == null) ? new FrameworkFacade() : instance;
}

}

//Get Field value
public Object GetFieldValue(Object obj, String propertyAttributeName)
{
object fieldValue = null;
Type type = obj.GetType();
var props = type.GetProperties();
foreach (System.Reflection.PropertyInfo propInfo in props)
{
Object[] propertyAttribute = propInfo.GetCustomAttributes(typeof(FieldAttribute), true);
if (((FieldAttribute)propertyAttribute[0]).ListItemName == propertyAttributeName)
{
System.Reflection.MethodInfo methodInfo =
propInfo.GetGetMethod();
fieldValue = methodInfo.Invoke(obj, null);
break;
}

}

return fieldValue.ToString();
}

//Set Field Value

public void SetFieldValue(Object obj, String propertyAttributeName, Object value)
{

Type type = obj.GetType();
var props = type.GetProperties();
foreach (System.Reflection.PropertyInfo propInfo in props)
{
Object[] propertyAttribute = propInfo.GetCustomAttributes(typeof(FieldAttribute), true);
if (((FieldAttribute)propertyAttribute[0]).ListItemName == propertyAttributeName)
{

if (propInfo.CanWrite)
{
propInfo.SetValue(obj, value, null);
}

break;
}
}
}

//Get ListAttribute value from type

public String GetListName(Type type)
{
String name = type.Assembly.FullName;
object[] obj = type.GetCustomAttributes(typeof(ListAttribute), true);
ListAttribute listAttribute = (ListAttribute)obj[0];
return listAttribute.ListName;

}

//Get All Fields from Type.

public System.Collections.ArrayList GetFields(Type type)
{
System.Collections.ArrayList fieldProperties = new System.Collections.ArrayList();
string name = type.Assembly.FullName;
System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(type.Assembly.Location);
System.Reflection.PropertyInfo[] propInfo = type.GetProperties();
foreach (System.Reflection.PropertyInfo property in propInfo)
{
object[] propAttributes = property.GetCustomAttributes(typeof(FieldAttribute), true);
foreach (object obj in propAttributes)
{
String fieldValue = ((FieldAttribute)obj).ListItemName;
fieldProperties.Add(fieldValue);
}
}
return fieldProperties;
}
#endregion
}

239 thoughts on “Dynamic Binding of SharePoint Lists with .Net Business Objects

  1. I don’t even know how I stopped up here, however I thought this publish was once great. I don’t recognize who you are but definitely you’re going to a famous blogger for those who aren’t already 😉 Cheers!

  2. Superb site you have here but I was wondering if you knew of any forums that cover the same topics discussed here? I’d really like to be a part of community where I can get suggestions from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Bless you!

  3. This might be definitely one of the extremely useful websites. We’ve arrive across on this particular subject. Actually great. I am also an expert in this topic so I could fully understand your effort.

  4. I like what you guys are up too. Such clever work and reporting! Carry on the superb works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my web site :). “The bigger the information media, the less courage and freedom they allow. Bigness means weakness.” by Eric Sevareid.

  5. Unquestionably imagine that that you said. Your favorite reason appeared to be at the internet the simplest factor to keep in mind of. I say to you, I certainly get irked while people think about worries that they just do not know about. You managed to hit the nail upon the top and also outlined out the entire thing without having side effect , people could take a signal. Will probably be again to get more. Thank you!

  6. I like this web site very much, Its a real nice place to read and find information. “What is called genius is the abundance of life and health.” by Henry David Thoreau.

  7. I am now not positive the place you’re getting your information, but good topic. I needs to spend some time finding out more or understanding more. Thank you for fantastic information I used to be searching for this info for my mission.

  8. I was just seeking this information for a while. After six hours of continuous Googleing, finally I got it in your website. I wonder what is the lack of Google strategy that do not rank this type of informative sites in top of the list. Generally the top web sites are full of garbage.

  9. I genuinely enjoy examining on this web site , it has got superb articles . “I have a new philosophy. I’m only going to dread one day at a time.” by Charles M. Schulz.

  10. My wife and i were really fortunate that Jordan could carry out his homework from your precious recommendations he got via your weblog. It is now and once more perplexing just to be giving out key points which often most people may possibly have been selling. We actually acknowledge we have the website owner to appreciate for that. The specific illustrations you might have produced, the straightforward site navigation, the friendships you may support to create – it’s all incredible, and it’s assisting our son and our family reckon that that content is enjoyable, which is certainly seriously essential. Thank you for all!

  11. I ‘d point out that we visitors actually are relatively endowed to be in a good network with plenty of wonderful people with very beneficial methods. I’m somewhat honored to have used your site and look forward to quite a lot of additional amazing minutes reading on this website. Thank you once more for all the pieces of information.

  12. Hey I definetly adore your write-up and it has been so marvelous hence I am going to save. One thing to say the Superb research this article has is definetly extraordinary ! No one goes that extra mile these days? Well Done !! Also another suggestion you shouldset up a Translator for your Global Audience !!!

  13. Hey, you used to write wonderful, but the last few posts have been kinda boring… I miss your great writings. Past several posts are just a little bit out of track! come on!”To dare is to lose one’s footing momentarily. To not dare is to lose oneself.” by Sren Aaby Kierkegaard.

  14. Does your blog have a contact page? I’m having a tough time locating it but, I’d like to shoot you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it develop over time.

  15. I am typically to running a blog and i actually appreciate your content. The article has really peaks my interest. I am going to bookmark your web site and maintain checking for new information.

  16. Neat blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog shine. Please let me know where you got your design. With thanks

  17. Hey There. I found your blog using msn. This is an extremely well written article. I’ll be sure to bookmark it and return to read more of your useful information. Thanks for the post. I will definitely return.

  18. Awesome read. I just passed this onto a buddy who was doing some research on that. He just bought me lunch since I found it for him! Thus let me rephrase: Thanx for lunch!

  19. This is a good time to sit around along with rest! I treasure this time of year! Thank you with regard to the manageable read. I am going to be undoubtedly back with respect to extra.

  20. Nice post. I learn something more challenging on completely different blogs everyday. It’s going to at all times be stimulating to learn content from other writers and observe a little bit one thing from their store. I’d favor to use some with the content material on my blog whether or not you don’t mind. Natually I’ll offer you a link on your net blog. Thanks for sharing.

  21. Overgrading:Prior to advent of the unbiased grading solutions, unethical or even ignorant traders created a nice residing away brand new collectors by simply purposely overgrading loose change or not finding out how to rank by themselves.

  22. This is undoubtedly a good time to lie down and also rest! I like this time of season! Thank you concerning the simple read. I will certainly be actually back concerning more.

  23. Just want to say your article is as amazing. The clearness in your post is simply spectacular and i can assume you’re an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the rewarding work.

  24. Congratulations on having one of the most sophisticated blogs Ive come across in some time! Its just incredible how much you can take away from something simply because of how visually beautiful it is. Youve put together a great blog space –great graphics, videos, layout. This is definitely a must-see blog!

  25. Thanks a lot for being my personal mentor on this matter. My spouse and i enjoyed your article greatly and most of all cherished how you handled the aspect I regarded as controversial. You happen to be always extremely kind to readers much like me and assist me in my existence. Thank you.

  26. Terrific start reading, Merely flushed it into a fabulous associate who had previously been doing a bit of examine along which. And that he merely sold me snack as a result of I located it all designed for the guy have fun Thereby okay rephrase that will Appreciate lunch meal!

  27. It is perfect time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I want to suggest you some interesting things or advice. Maybe you could write next articles referring to this article. I want to read more things about it!

  28. These thoughts as well worked as the fantastic way to recognize that other people have the identical dreams similar to my very own to find out way more on the subject of this condition.

  29. Hey there, You’ve done an excellent job. I’ll definitely digg it and personally suggest to my friends. I’m confident they will be benefited from this site.|

  30. I do not even know how I ended up here, but I thought this post was good. I don’t know who you are but definitely you are going to a famous blogger if you are not already 😉 Cheers!

  31. Normally I don’t read post on blogs, but I would like to say that this write-up very compelled me to check out and do it! Your writing style has been surprised me. Thank you, very nice article.

  32. Anti-aging skin care dietary supplements will fix the healthiness of the organs and circulatory system as well as take good care of your own hypersensitive as well as wrinkle-prone dried-out skin! Anti-aging natual skin care dietary supplements normally contain productive anti-aging parts that offer the body’s all-natural capacity to assist get rid of age spots, toxins and also chemical toxins that will impede wholesome epidermis, improve skin color suppleness and adaptability, lessen skin wrinkly skin along with drooping.

  33. Nice post. I was checking constantly this blog and I’m impressed! Extremely helpful info specially the last part 🙂 I care for such information a lot. I was seeking this certain information for a very long time. Thank you and good luck.

  34. Nice post. I learn something totally new and challenging on blogs I stumbleupon on a daily basis. It will always be interesting to read articles from other writers and use a little something from their websites.

  35. We’re a group of volunteers and starting a new scheme in our community. Your site provided us with valuable info to work on. You’ve done a formidable job and our whole community will be thankful to you.

  36. obviously like your web site but you have to test the spelling on several of your posts. Several of them are rife with spelling issues and I to find it very troublesome to inform the truth however I will certainly come back again.

  37. To obtain these loans also faster criminal background has got to match the particular criteria similar to you need to be 18years as well as previously mentioned, employed along with month-to-month income unto 1000 lbs , offers along with active bank account and quite a few crucial has to be the actual resident regarding UK.

  38. I like what you guys are up also. Such clever work and reporting! Keep up the superb works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my site :). “Blessed is he who has found his work let him ask no other blessedness.” by Thomas Carlyle.

  39. Thanks for your marvelous posting! I certainly enjoyed reading it, you could be a great author.I will remember to bookmark your blog and will eventually come back later in life. I want to encourage you to continue your great writing, have a nice afternoon!

  40. I really wanted to post a quick word to appreciate you for all of the wonderful steps you are giving out on this site. My time consuming internet research has at the end been paid with good quality strategies to exchange with my colleagues. I would believe that we site visitors are very much fortunate to live in a superb place with many lovely individuals with interesting principles. I feel very much lucky to have discovered your weblog and look forward to many more fun moments reading here. Thanks once again for everything.

  41. As a web-site owner I believe the subject matter here is reallygreat. I appreciate it for your time. You should keep it up forever! Best of luck…

  42. Youre so cool! I dont suppose Ive read something like this before. So nice to seek out somebody with some unique thoughts on this subject. realy thanks for starting this up. this website is one thing that’s needed on the web, somebody with slightly originality. helpful job for bringing something new to the internet!

  43. Hi there I believe that you have a great web log going here, I noticed it on Yahoo and plan on returning continually for the info that you all are featuring.|Thanks for making my day a little tad much better with this terrific page!nice post!

  44. I do enjoy the way you have framed this issue and it does indeed present me personally some fodder for consideration. Nonetheless, because of everything that I have personally seen, I really trust when the feed-back stack on that men and women keep on point and not get started on a tirade associated with the news of the day. Anyway, thank you for this exceptional point and while I do not concur with it in totality, I regard your point of view.

  45. Just want to say your article is as astounding. The clarity in your post is just spectacular and i could assume you’re an expert on this subject. Well with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please carry on the rewarding work.

  46. Youre so cool! I dont suppose Ive read anything like this before. So nice to seek out any individual with some authentic thoughts on this subject. realy thanks for starting this up. this website is one thing that is wanted on the web, somebody with a bit of originality. useful job for bringing something new to the internet!

  47. Undergrading: We might all like to get a cash for a portion of their true price. Yet could you undertake it through intentionally knocking the grade of someone else’s gold coin to weaken its benefit? Lots of people would certainly, it seems like, since this is perhaps the most common exercise within numismatics.

  48. Hello there, I think your site might be having web browser compatibility issues. When I look at your site in Safari, it looks fine however, if opening in I.E., it’s got some overlapping issues. I merely wanted to provide you with a quick heads up! Apart from that, great site!

  49. Can I simply say what a relief to discover somebody who actually understands what they’re talking about on the web. You definitely know how to bring an issue to light and make it important. More and more people need to read this and understand this side of your story. I can’t believe you are not more popular given that you certainly have the gift.

  50. If you’re still on the fence: grab your favorite earphones, head down to a Best Buy and ask to plug them into a Zune then an iPod and see which one sounds better to you, and which interface makes you smile more. Then you’ll know which is right for you.

  51. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why throw away your intelligence on just posting videos to your blog when you could be giving us something informative to read?

  52. F*ckin’ awesome issues here. I am very satisfied to look your article. Thank you a lot and i am looking ahead to touch you. Will you kindly drop me a mail? How to make money fast

  53. This page appears to get a good ammount of visitors. How do you advertise it? It offers a nice individual twist on things. I guess having something authentic or substantial to talk about is the most important thing.

  54. Thanks for the writeup. I definitely agree with what you are saying. I have been talking about this subject a lot lately with my brother so hopefully this will get him to see my point of view. Fingers crossed!

  55. Thank you so much with regard to giving everyone an update on this topic on your web-site. Please realize that if a brand-new post becomes available or when any modifications occur on the current publication, I would want to consider reading more and finding out how to make good utilization of those methods you talk about. Thanks for your time and consideration of other folks by making your blog available.

  56. I actually still can not quite believe that I could end up being one of those reading through the important guidelines found on your website. My family and I are seriously thankful on your generosity and for providing me the potential to pursue my chosen career path. Many thanks for the important information I managed to get from your web-site.

  57. According to my research, after a foreclosures home is marketed at an auction, it is common to the borrower to still have any remaining balance on the mortgage. There are many financial institutions who seek to have all fees and liens paid by the up coming buyer. Nonetheless, depending on specified programs, legislation, and state guidelines there may be quite a few loans that are not easily resolved through the transfer of financial products. Therefore, the duty still falls on the debtor that has acquired his or her property in foreclosure process. Many thanks for sharing your ideas on this website.

  58. I do know this isn’t precisely on subject, but i have a website online using the same program as well and i am getting troubles with my feedback displaying. is there a setting i’m missing? it’s possible chances are you’ll help me out? thanx.

  59. I’ve been exploring for a little for any high quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this info So i’m happy to convey that I’ve a very good uncanny feeling I discovered just what I needed. I most certainly will make sure to do not forget this site and give it a glance regularly.

  60. Hi webmaster, commenters and everybody else !!! The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!b Keep ’em coming… you all do such a great job at such Concepts… can’t tell you how much I, for one appreciate all you do!

  61. Hmm is anyone else having problems with the pictures on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.

  62. Thank you so much for giving everyone remarkably special opportunity to discover important secrets from here. It’s always so great and also jam-packed with a great time for me personally and my office co-workers to search your website minimum three times in 7 days to learn the fresh stuff you have got. And lastly, I am usually happy considering the astounding principles served by you. Selected 4 ideas in this article are without a doubt the most efficient we’ve ever had.

  63. Wonderful goods from you, man. I’ve be mindful your stuff previous to and you are simply extremely great. I actually like what you’ve bought here, really like what you’re stating and the best way wherein you assert it. You make it enjoyable and you continue to care for to stay it smart. I can’t wait to learn far more from you. That is really a great web site.

Leave a reply to car refinance Cancel reply