Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern
-
Upload
sparkhound-inc -
Category
Technology
-
view
58 -
download
5
description
Transcript of Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern
Optimizing Code Reusability For SharePoint Using LINQ and the MVP Design Pattern
Houston Tech Fest 2014
Introduction – Ted Wagner
BS in Game Software DevelopmentSharePoint SME for over 3 Years.Conducted multiple training sessions for SharePoint 2010 and 2013.Worked for Sparkhound over a year.
2
“Be a hero. Grow a beard.”During September, the Sparkhound Foundation is sponsoring the growth of facial hair.
Why? To help raise funds for research and treatment of prostate cancer. Learn more at Septembeard.org.
$680,380 raised since
2011
4
Please turn off all electronic devices or set them to vibrate.
If you must take a phone call, please do so in the lobby so as not to disturb others.
Thanks to our Diamond Sponsors:
Thank you for being a part of the
8th Annual Houston TechFest!
5
Overview
Review the MVP patternSetting up models to promote encapsulation and testingSetting up Presenters and Views for separation of functionality to promote testing
Outcome
Reusable SharePoint solutions to be used between various applications and SharePoint projects.
6
What is MVP?
A design pattern used to separate functionality from controls to maximize the amount of code that can be tested automatically.Separation of the logic of events and the updates made to the application data.Uses an Interface to reference the view instead of the view classMany different variations
7
What is MVP?
8
Microsoft Corporation. (2014). The Model-View-Presenter (MVP) Pattern. Retrieved September 3, 2014, from Microsoft Developer Network: http://msdn.microsoft.com/en-us/library/ff649571.aspx
MVP image (Microsoft Corporation, 2014)
Supervising Presenter
Why use MVP with SharePoint?
MVC is technically “not supported”Designs are usually scoped to one view – Web PartsIncrease Unit TestingEncapsulation of SharePoint Methods and Assemblies
9
Model
Data Model1. Data Model
1. Representation of columns within a List or Library
2. Business Model1. Represented as an interface2. Data access object used to query database
10
View
Class Containing visual controlsHandles eventsContains Page Events, JavaScript, CSS, JQuery and any other Front-End functionalityViews do not have knowledge of the modelAn interface is designated to the view for updating the view state when the model is updated. 1
1
Presenter
The class that combines the view to the data models.Updates the view.One presenter per viewEasily attach to Unit testing projects for automation.
12
LINQ to SharePoint
Utilize LINQ to easily query SharePoint ListsProvides quick way to cast objects to generics for encapsulationQuickly generate models representing SharePoint Lists using SPMetal
13
Setting up Solution
Create a Class Library Project for storing ModelsCreate Project for SharePoint SolutionsSign keyAdd assembly to package
Package->Advanced->Add
14
Setting up your Models
• Create a separate project for you models only
• Setup your data models• Setup Data Access Objects and business
model interfaces
Best Practices• Keep all SharePoint references in the
models• Keep error handling to a minimum in the
models15
Data Model Example
16
public class CustomerModel { public string CustId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } public bool Vendor { get; set; } }
Generate DataContext With SPMetal
• SPMetal – located in the BIN folder in Hive• Create Environment Variable referencing
SPMetal in hive folder• System Properties -> Advanced Settings ->
Advanced• Create Folder for storing DataContext Files
17
C:\SPMetal /web:http://sparkhound.ted.local /code:CustomerDataContext.cs
Using DataContext ModelUsing Preconfigured data models from SPMetal
ProsGenerates exact column namesNo need to create data models
ConsCannot keep SharePoint functionality within the modelHard to find and update models
18
Example
19
public List<CustomerItem> GetCustomers() {
using (TechfestdatacontextDataContext dc = new TechfestdatacontextDataContext(SPContext.Current.Site.Url)) { EntityList<CustomerItem> customers = dc.GetList<CustomerItem>("Customer");
var allCustomers = from c in customers select c;
return allCustomers.ToList<CustomerItem>(); } }
Using Custom Data ModelDesigning your own Data Model
ProsFlexibility to control what data is passedControl namesEncapsulate SharePoint references
ConsMust create each data model manually
20
Example
21
using(TechfestdatacontextDataContext dc = new TechfestdatacontextDataContext(SPContext.Current.Site.Url)) { EntityList<RegisterItem> register = dc.GetList<RegisterItem>("Register");
var customerDetails = from r in register where r.CustID == CustId select new RegisterModel { CustId = r.CustID, Credit = Convert.ToDouble(r.Credit), Debit = Convert.ToDouble(r.Debit), Date = Convert.ToDateTime(r.Date), RegisterId = r.Title };
return customerDetails.ToList<RegisterModel>(); }
Setting up the presenter
The presenter will reference the view through an interfaceOverload the constructor to pass the viewAll functionality is handled by the presenter
Best PracticesUse bool functions to catch errors. Return false for errors to keep other functionality from continuing.
22
Example
Constructor accepting view and assigning it to a variable
23
public CustomerInfoPresenter(ICustomerInfoView View) { view = View; }
Example
24
public bool GetCustomerInfo() { try { CustomerBusinessObject model = new CustomerBusinessObject(); view.GetCustomers = model.GetCustomers();
return true; } catch (Exception ex) { view.ErrorMsg = "Error Getting Customer Info: " + ex.Message; return false; } }
Setting up the view
Views use properties to assign values and populate controls Minimum functionality in viewsRepresent data in an interface to pass data
25
public interface ICustomerInfoView { List<CustomerItem> GetCustomers {get; set;} List<RegisterModel> CustomerData {get; set;} string ErrorMsg { get; set; } }
Example
26
public List<CustomerItem> GetCustomers { get { return CustomerDDL.DataSource as List<CustomerItem>; } set { CustomerDDL.DataTextField = "LastName"; CustomerDDL.DataValueField = "Title"; CustomerDDL.DataSource = value; CustomerDDL.DataBind();
CustomerDDL.Items.Insert(0, "Please select a customer..."); } }
Example – Page Load
27
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { CustomerInfoPresenter presenter = new CustomerInfoPresenter(this);
presenter.GetCustomerInfo(); } }
Pros/ConsPros
EncapsulationEasily give code to other developers
Reusability with other projects and applicationsAbility to manipulate and bind data after query
ConsIssues with cross site collection queriesLINQ is not Thread SafeSlower than CAMLExtra coding overhead
28
Overcoming cross site collection queries
1. Extend DataContext Model to include a new constructor that accepts different site collections.
2. Change the Current Context to the site collection being queried.
29
Overcoming cross site collection queries
30
var CurrentContext = HttpContext.Current;(using SPSite site = new SPSite(SiteCollectionUrl)){
(using(SPWeb web = site.OpenWeb()){
HttpRequest request = new HttpRequest(“”, SiteCollectionURL, “”);HttpContext.Current = new HttpContext(request, new HttpRespone(new StringWriter()));
//Perform Linq Query}
}
HttpContext.Current = CurrentContext;
Questions
31
Please Leave Feedback
32
If you leave session feedback and provide contact information in the survey, you will be qualified for a prize
Scan the QR Code to the right or go to http://bit.ly/1p13f3n
34
Thanks to all our Sponsors!
Works CitedMicrosoft Corporation. (2014). The Model-View-Presenter (MVP) Pattern. Retrieved September 3, 2014, from Microsoft Developer Network: http://msdn.microsoft.com/en-us/library/ff649571.aspx
35
36