36
Optimizing Code Reusability For SharePoint Using LINQ and the MVP Design Pattern Houston Tech Fest 2014

Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

Embed Size (px)

DESCRIPTION

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.

Citation preview

Page 1: 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

Page 2: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 3: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

“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

Page 4: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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!

Page 5: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

5

Overview

Review the MVP patternSetting up models to promote encapsulation and testingSetting up Presenters and Views for separation of functionality to promote testing

Page 6: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

Outcome

Reusable SharePoint solutions to be used between various applications and SharePoint projects.

6

Page 7: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 8: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 9: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 10: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 11: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 12: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 13: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 14: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

Setting up Solution

Create a Class Library Project for storing ModelsCreate Project for SharePoint SolutionsSign keyAdd assembly to package

Package->Advanced->Add

14

Page 15: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 16: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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; } }

Page 17: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 18: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 19: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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>(); } }

Page 20: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 21: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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>(); }

Page 22: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 23: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

Example

Constructor accepting view and assigning it to a variable

23

public CustomerInfoPresenter(ICustomerInfoView View) { view = View; }

Page 24: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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; } }

Page 25: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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; } }

Page 26: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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..."); } }

Page 27: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

Example – Page Load

27

protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { CustomerInfoPresenter presenter = new CustomerInfoPresenter(this);

presenter.GetCustomerInfo(); } }

Page 28: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 29: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 30: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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;

Page 31: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

Questions

31

Page 32: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 33: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

Contact Info

Ted [email protected]

33

Page 34: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

34

Thanks to all our Sponsors!

Page 35: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

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

Page 36: Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP Design Pattern

36