Whether developing a small customization or a large enterprise solution, one goal is to minimize redundancy in Code. In this presentation, Sparkhound Consultant Ted Wagner shows how the MVP design pattern is used in SharePoint to create business models that can be reused easily between other ASP or C# application.
2. Introduction – Ted Wagner
BS in Game Software Development
SharePoint SME for over 3 Years.
Conducted multiple training sessions for
SharePoint 2010 and 2013.
Worked for Sparkhound over a year.
2
3. “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. 4
Thank you for being a part of the
8th Annual Houston TechFest!
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:
5. 5
Overview
Review the MVP pattern
Setting up models to promote
encapsulation and testing
Setting up Presenters and Views for
separation of functionality to promote
testing
7. 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 class
Many different variations
7
8. Microsoft Corporation. (2014). The Model-View-Presenter (MVP) Pattern. Retrieved September 3, 2014, from Microsoft Developer Network: http://msdn.microsoft.What is MVP?
MVP image (Microsoft
8
Supervising Presenter
Corporation, 2014)
9. Why use MVP with SharePoint?
MVC is technically “not supported”
Designs are usually scoped to one view –
Web Parts
Increase Unit Testing
Encapsulation of SharePoint Methods and
Assemblies
9
10. Model
Data Model
1. Data Model
1. Representation of columns within a List or Library
2. Business Model
1. Represented as an interface
2. Data access object used to query database
10
11. View
Class Containing visual controls
Handles events
Contains Page Events, JavaScript, CSS,
JQuery and any other Front-End functionality
Views do not have knowledge of the model
An interface is designated to the view for
updating the view state when the model is
updated.
11
12. Presenter
The class that combines the view to the data
models.
Updates the view.
One presenter per view
Easily attach to Unit testing projects for
automation.
12
13. LINQ to SharePoint
Utilize LINQ to easily query SharePoint Lists
Provides quick way to cast objects to generics
for encapsulation
Quickly generate models representing
SharePoint Lists using SPMetal
13
14. Setting up Solution
Create a Class Library
Project for storing Models
Create Project for SharePoint
Solutions
Sign key
Add assembly to package
Package->Advanced->Add
14
15. 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
models
15
16. 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; }
}
17. 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
18. Using DataContext Model
Using Preconfigured data models from SPMetal
Pros
Generates exact column names
No need to create data models
Cons
Cannot keep SharePoint functionality within the model
Hard to find and update models
18
19. 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>();
}
}
20. Using Custom Data Model
Designing your own Data Model
Pros
Flexibility to control what data is passed
Control names
Encapsulate SharePoint references
Cons
Must create each data model manually
20
21. 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>();
}
22. Setting up the presenter
The presenter will reference the view through an
interface
Overload the constructor to pass the view
All functionality is handled by the presenter
Best Practices
Use bool functions to catch errors.
Return false for errors to keep other functionality from
continuing.
22
23. Example
Constructor accepting view and assigning it to a
variable
23
public CustomerInfoPresenter(ICustomerInfoView View)
{
view = View;
}
24. 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;
}
}
25. Setting up the view
Views use properties to assign values and populate
controls
Minimum functionality in views
Represent 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; }
}
26. 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...");
}
}
27. Example – Page Load
27
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CustomerInfoPresenter presenter = new
CustomerInfoPresenter(this);
presenter.GetCustomerInfo();
}
}
28. Pros/Cons
Pros
Encapsulation
Easily give code to other developers
Reusability with other projects and applications
Ability to manipulate and bind data after query
Cons
Issues with cross site collection queries
LINQ is not Thread Safe
Slower than CAML
Extra coding overhead
28
29. 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
30. 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;
32. 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
35. Works Cited
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
35
Why are we doing this? In honor of the Sparkies and Sparkie family members who have (or continue to fight) fought prostate cancer
Background:
- The Sparkhound Foundation is our non-profit charitable giving organization
- Prostate cancer is the second leading cause of death in American men.
SLIDE PURPOSE: This is where everything starts – us defining with our customers how we can make an impact in their business regardless of the technology!
SPIEL: Technology should be transformative, not a to-do list. Because, really, just about any firm can change the way your IT works. Our mission is for IT to change the way your business works. The difference is a game-changer.
SLIDE PURPOSE: This is where everything starts – us defining with our customers how we can make an impact in their business regardless of the technology!
SPIEL: Technology should be transformative, not a to-do list. Because, really, just about any firm can change the way your IT works. Our mission is for IT to change the way your business works. The difference is a game-changer.
Error handling to a minimum to keep errors from being passed over.
Example: pass error in customer first name, but do not use customer first name in persenter/view
Code overhead – presenter basically replacing code behind on page