SlideShare a Scribd company logo
1 of 32
Download to read offline
Advanced SharePoint
2010 and 2013 Web Part
Development




Rob Windsor
rwindsor@portalsolutions.net
@robwindsor
About Me
•   Senior SharePoint Architect with Portal Solutions
•   Technical Contributor to the Pluralsight On-Demand Library
•   Microsoft MVP, MCPD, MCT
•   Founder and Past-President of the North Toronto .NET UG
•   Co-author of Prof. Visual Basic 2012 and .NET 4.5 (Wrox)
Session Prerequisites
• Experience developing for SharePoint
• Experience building Web Parts
Agenda
•   Visual Web Parts
•   Persistent Web Part Properties
•   Editor Parts
•   Connectable Web Parts
•   Web Part Verbs
•   Asynchronous Web Parts
•   Web Part Gallery
•   Web Part Pages
Visual Web Parts
• Visual web parts traditionally combine a web part with a
  user control
• User controls have full design experience in Visual Studio
• User interface and code behind defined in user control
• Web part “injects” user control dynamically using
  Page.LoadControl
 private const string _ascxPath = @"~/_CONTROLTEMPLATES/.../MyUserControl.ascx";

 protected override void CreateChildControls()
 {
     Control control = Page.LoadControl(_ascxPath);
     Controls.Add(control);
 }
Web Parts in Sandboxed Solutions
• Split page rendering
    Page code runs in ASP.NET worker process
    Sandboxed web part code runs in sandbox worker process
    HTML markup and JavaScript from two worker processes merged
• Sandbox restrictions
      Reduced set of server object model API
      Restricted access outside SharePoint
      No elevation of permissions
      Cannot deploy files to SharePoint system folders
      Must be ASP.NET web parts
      Can only use ASP.NET controls
      No web part connections
Sandbox Visual Web Part Template
• Native visual web part template not compatible
  with sandboxed solutions
   Attempts to deploy user control to system folders
• Visual Studio 2010 Power Tools introduced a
  sandbox compatible template
   No user control
   Designer makes web part behave like a user control
   Markup in user control converted to code at design time
• Visual Studio 2012 only has this template
DEMO
Visual Web Parts
Web Part Properties
• Web Parts support persistent properties
• Configure properties via attributes
    Personalizable(param)
       Directs SharePoint to persist property value
       Parameter indicates if property may be personalized
    WebBrowsable(true)
       Directs SharePoint to generate interface to edit property
    WebDisplayName, WebDescription
       The prompt and tooltip that accompany the data entry element
    Category
       The group in which the properties will be shown

             [Personalizable(PersonalizationScope.Shared)]
             [WebBrowsable(true)]
             [WebDisplayName("Year")]
             [Category("Pluralsight")]
             public int Year { get; set; }
DEMO
Web Part Properties
Cross Site Script Safeguards
• Added in SharePoint 2010
• Indicates developer has taken steps to ensure code is safe
  against scripting attacks
• Two key pieces
    SafeAgainstScript attribute of SafeControl entry
    RequiresDesignerPermission attribute
• Contributors can only set web part properties if:
    SafeAgainstScript is true (not the default)
    RequiresDesignerPermission is false (default)
DEMO
Cross Site Script
Safeguards
Editor Parts
• Editor parts enable user customization
• Editor parts contained within an editor zone
• ASP.NET supplies standard editor parts
     Layout, appearance, etc
• Developers can create custom editor parts
     Similar development experience to Web Part
     Control over interface used to edit properties
     Ability to validate user input
• In web part
     Override CreateEditorParts
• In editor part
     Override CreateChildControls, SyncChanges and
      ApplyChanges
DEMO
Editor Parts
Creating Connectable Web Parts
• Pass data from one web part to another
• Loosely-coupled connection
    Communication managed by WebPartManager
    Provider web part supplies data
    Consumer web parts retrieve data
• Interface used to define data contract
    ASP.NET has standard connection contracts
       Shown later in this module
    Can use custom connection contracts
• SharePoint provides user interface elements to establish
  connections
• Not compatible with sandboxed solutions
DEMO
Web Part
Connections
Web Part Connections using Ajax
• Communication between web parts requires a postback
• Generally, only consumer web part needs to be updated
• Can use partial page rendering (UpdatePanel) to only
  update consumer
• Problem:
    Event triggered by provider
    UpdatePanel in consumer
• Solution:
    Pass reference to control that triggers update from provider to consumer
    Consumer registers control as AsyncPostbackControl with ScriptManager
DEMO
Web Part Connections
Using Ajax
Web Part Verbs

• Add additional menu options to
  dropdown at top-right of Web Part
• Can be handled client-side, server-
  side or both.
Web Part Verbs
  public override WebPartVerbCollection Verbs
  {
      get
      {
          var verbs = new List<WebPartVerb>();

          var verb1 = new WebPartVerb(this.ID + "_ClientSideRssOpenerVerb",
              string.Format("window.open('{0}','RSSXML')", this.FeedUrl));
          verb1.Description = "Open RSS Feed in an external window";
          verb1.Text = "Open RSS Feed";
          verbs.Add(verb1);

          var verb2 = new WebPartVerb(this.ID + "_ServerSideRssOpenerVerb",
              new WebPartEventHandler(ServerSideVerbHandler));
          verb2.Description = "Load the RSS Source Feed.";
          verb2.Text = "View RSS Source Feed";
          verbs.Add(verb2);

          var allverbs = new WebPartVerbCollection(base.Verbs, verbs);
          return allverbs;
      }
  }
DEMO
Web Part Verbs
Asynchronous Web Parts
• Long running tasks are blocking calls
   One web part can bring a page to a crawl
   When on the same page, multiple instances can kill the
    user experience
• Make long running tasks asynchronous
   Don’t hold up page processing
Asynchronous Web Parts
 protected void Page_PreRender(object sender, EventArgs e) {
     Page.RegisterAsyncTask(
         new PageAsyncTask(
             new BeginEventHandler(BeginFeed),
             new EndEventHandler(EndFeed),
             new EndEventHandler(TimoutFeed),
             null, true));
 }

 public IAsyncResult BeginFeed(object sender, EventArgs e, AsyncCallback cb, object state) {
     _feedCaller = GetFeed;
     return _feedCaller.BeginInvoke(cb, state);
 }

 public void EndFeed(IAsyncResult ar) {
     var feed = _feedCaller.EndInvoke(ar);

     var posts = from item in feed.Descendants("item")
                 select new
                 {
                     Title = item.Element("title").Value,
                     Description = item.Element("description").Value,
                     Published = DateTime.Parse(item.Element("pubDate").Value)
                 };
     posts = posts.Skip(_pageNum * _hostPart.PageSize).Take(_hostPart.PageSize);

     FeedListView.DataSource = posts.ToList();
     FeedListView.DataBind();
 }
DEMO
Async Web Parts
Cleaning the Web Part Gallery
• Files provisioned into Content DB do not get
  removed on Feature deactivation
   This includes webpart / dwp files added to Web Part
    Gallery
• Deletion of files can be done in Feature receiver
   Examine element manifests to find web parts
   Remove from web part gallery
Cleaning the Web Part Gallery
 public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
 {
     var site = properties.Feature.Parent as SPSite;
     if (site == null) return;

     var parts = new List<string>();
     var elements = properties.Definition.GetElementDefinitions(CultureInfo.CurrentCulture);
     foreach (SPElementDefinition element in elements) {
         if (element.ElementType != "Module") continue;

         var node = element.XmlDefinition;
         if (node.Attributes["Url"].Value != "_catalogs/wp") continue;

         foreach (XmlElement childNode in node.ChildNodes) {
             if (childNode.Name == "File") {
                 parts.Add(childNode.GetAttribute("Url"));
             }
         }
     }

     var web = site.RootWeb;
     var gallery = web.Lists["Web Part Gallery"];
     var items = gallery.Items;

     for (int i = items.Count - 1; i >= 0; i--) {
         var item = items[i];
         if (parts.Contains(item.File.Name))
         {
             item.Delete();
         }
     }
 }
DEMO
Cleaning the Web
Part Gallery
Creating Web Part Page Templates
• Create a site page
• Set base type to
  Microsoft.SharePoint.WebPartPages.WebPartPage
• Add one or more web part zones to page
• Provision page instances using Module
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<!-- Other register directives -->
<%@ Register Tagprefix="WebPartPages"
    Namespace="Microsoft.SharePoint.WebPartPages"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, …" %>

<%@ Page Language="C#"
    Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage"
    MasterPageFile="~masterurl/default.master" %>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <WebPartPages:WebPartZone
        ID="MainZone" runat="server"
        FrameType="TitleBarOnly"
        Title="Main Web Part Zone" />
</asp:Content>
Adding Web Parts to Web Part Pages
• Use SPLimitedWebPartManager
     Get reference from property of Page object
• Use SPLimitedWebPartManager.AddWebPart to add
var page = web.GetFile("SiteAssets/Test02.aspx");
using (var manager = page.GetLimitedWebPartManager(
    PersonalizationScope.Shared)) {
    if (!manager.WebParts.Contains(webPartTitle))
    {
        var part = new MostPopularProducts2.MostPopularProducts2();
        part.Title = "Most Popular Products";
        part.Category = "Condiments";
        part.Year = 1997;
        manager.AddWebPart(part, "Left", 0);
    }
}


        Note: Contains method shown in code sample is a custom extension
DEMO
Creating Web Part
Pages and Adding
Web Parts
Additional Stuff
• Closing versus deleting web parts
   Closing a web part does not remove it from page
   Having many closed web parts on a page can degrade
    performance
   Set AllowClose to false to remove option to close from
    web part verbs
• Versioning
   DO NOT change the assembly version of your
    assemblies
   SharePoint stores the full name with version of all web
    parts in galleries and on pages
   Use the AssemblyFileVersion instead
Thank You
• Big thanks to the organizers, sponsors and you for making
  this event possible
• Please fill out your evaluation
• Please keep in touch


    rwindsor@portalsolutions.net
    @robwindsor
    msmvps.com/blogs/windsor

More Related Content

What's hot

Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIRob Windsor
 
SharePoint 2010 Client Object Model
SharePoint 2010 Client Object ModelSharePoint 2010 Client Object Model
SharePoint 2010 Client Object ModelG. Scott Singleton
 
Understanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST APIUnderstanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST APIChris Beckett
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.NetHitesh Santani
 
SPTechCon 2014 How to develop and debug client side code in SharePoint
SPTechCon 2014 How to develop and debug client side code in SharePointSPTechCon 2014 How to develop and debug client side code in SharePoint
SPTechCon 2014 How to develop and debug client side code in SharePointMark Rackley
 
Taking Advantage of the SharePoint 2013 REST API
Taking Advantage of the SharePoint 2013 REST APITaking Advantage of the SharePoint 2013 REST API
Taking Advantage of the SharePoint 2013 REST APIEric Shupps
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvcGuo Albert
 
Are you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsAre you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsLiam Cleary [MVP]
 
Introduction to Client Side Dev in SharePoint Workshop
Introduction to Client Side Dev in SharePoint WorkshopIntroduction to Client Side Dev in SharePoint Workshop
Introduction to Client Side Dev in SharePoint WorkshopMark Rackley
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application Madhuri Kavade
 
Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365Kashif Imran
 
Introduction to the SharePoint 2013 REST API
Introduction to the SharePoint 2013 REST APIIntroduction to the SharePoint 2013 REST API
Introduction to the SharePoint 2013 REST APISparkhound Inc.
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Ben Robb
 
SharePoint REST vs CSOM
SharePoint REST vs CSOMSharePoint REST vs CSOM
SharePoint REST vs CSOMMark Rackley
 

What's hot (20)

Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
 
SharePoint 2010 Client Object Model
SharePoint 2010 Client Object ModelSharePoint 2010 Client Object Model
SharePoint 2010 Client Object Model
 
ASP.NET - Web Programming
ASP.NET - Web ProgrammingASP.NET - Web Programming
ASP.NET - Web Programming
 
Understanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST APIUnderstanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST API
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
 
SPTechCon 2014 How to develop and debug client side code in SharePoint
SPTechCon 2014 How to develop and debug client side code in SharePointSPTechCon 2014 How to develop and debug client side code in SharePoint
SPTechCon 2014 How to develop and debug client side code in SharePoint
 
Taking Advantage of the SharePoint 2013 REST API
Taking Advantage of the SharePoint 2013 REST APITaking Advantage of the SharePoint 2013 REST API
Taking Advantage of the SharePoint 2013 REST API
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
Are you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsAre you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint Apps
 
Introduction to Client Side Dev in SharePoint Workshop
Introduction to Client Side Dev in SharePoint WorkshopIntroduction to Client Side Dev in SharePoint Workshop
Introduction to Client Side Dev in SharePoint Workshop
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
 
Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365
 
Introduction to the SharePoint 2013 REST API
Introduction to the SharePoint 2013 REST APIIntroduction to the SharePoint 2013 REST API
Introduction to the SharePoint 2013 REST API
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010
 
Sharepoint Online
Sharepoint OnlineSharepoint Online
Sharepoint Online
 
SharePoint REST vs CSOM
SharePoint REST vs CSOMSharePoint REST vs CSOM
SharePoint REST vs CSOM
 
Advanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And ConstructsAdvanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And Constructs
 
Oracle ADF Case Study
Oracle ADF Case StudyOracle ADF Case Study
Oracle ADF Case Study
 
Ajax
AjaxAjax
Ajax
 

Similar to Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTechCon

SharePoint Object Model, Web Services and Events
SharePoint Object Model, Web Services and EventsSharePoint Object Model, Web Services and Events
SharePoint Object Model, Web Services and EventsMohan Arumugam
 
Parallelminds.web partdemo1
Parallelminds.web partdemo1Parallelminds.web partdemo1
Parallelminds.web partdemo1parallelminder
 
SharePoint 2010 Training Session 5
SharePoint 2010 Training Session 5SharePoint 2010 Training Session 5
SharePoint 2010 Training Session 5Usman Zafar Malik
 
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...SPTechCon
 
Web Components v1
Web Components v1Web Components v1
Web Components v1Mike Wilcox
 
Hdv309 - Real World Sandboxed Solutions
Hdv309 - Real World Sandboxed SolutionsHdv309 - Real World Sandboxed Solutions
Hdv309 - Real World Sandboxed Solutionswoutervugt
 
Parallelminds.web partdemo
Parallelminds.web partdemoParallelminds.web partdemo
Parallelminds.web partdemoManishaChothe
 
SharePoint 2007 Presentation
SharePoint 2007 PresentationSharePoint 2007 Presentation
SharePoint 2007 PresentationAjay Jain
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentChui-Wen Chiu
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSujit Kumar
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web FrameworkLuther Baker
 
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Roy de Kleijn
 
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0Arun Gupta
 
Share point 2010_overview-day4-code
Share point 2010_overview-day4-codeShare point 2010_overview-day4-code
Share point 2010_overview-day4-codeNarayana Reddy
 
Share point 2010_overview-day4-code
Share point 2010_overview-day4-codeShare point 2010_overview-day4-code
Share point 2010_overview-day4-codeNarayana Reddy
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET PresentationRasel Khan
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauSpiffy
 

Similar to Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTechCon (20)

SharePoint Object Model, Web Services and Events
SharePoint Object Model, Web Services and EventsSharePoint Object Model, Web Services and Events
SharePoint Object Model, Web Services and Events
 
Parallelminds.web partdemo1
Parallelminds.web partdemo1Parallelminds.web partdemo1
Parallelminds.web partdemo1
 
A View about ASP .NET and their objectives
A View about ASP .NET and their objectivesA View about ASP .NET and their objectives
A View about ASP .NET and their objectives
 
SharePoint 2010 Training Session 5
SharePoint 2010 Training Session 5SharePoint 2010 Training Session 5
SharePoint 2010 Training Session 5
 
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
Hdv309 - Real World Sandboxed Solutions
Hdv309 - Real World Sandboxed SolutionsHdv309 - Real World Sandboxed Solutions
Hdv309 - Real World Sandboxed Solutions
 
Parallelminds.web partdemo
Parallelminds.web partdemoParallelminds.web partdemo
Parallelminds.web partdemo
 
SharePoint 2007 Presentation
SharePoint 2007 PresentationSharePoint 2007 Presentation
SharePoint 2007 Presentation
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced Visualforce
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web Framework
 
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
 
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
 
Share point 2010_overview-day4-code
Share point 2010_overview-day4-codeShare point 2010_overview-day4-code
Share point 2010_overview-day4-code
 
Share point 2010_overview-day4-code
Share point 2010_overview-day4-codeShare point 2010_overview-day4-code
Share point 2010_overview-day4-code
 
HTML5 Refresher
HTML5 RefresherHTML5 Refresher
HTML5 Refresher
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
 

More from SPTechCon

Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechConDeep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechConSPTechCon
 
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...SPTechCon
 
“Managing Up” in Difficult Situations by Bill English - SPTechCon
“Managing Up” in Difficult Situations by Bill English - SPTechCon“Managing Up” in Difficult Situations by Bill English - SPTechCon
“Managing Up” in Difficult Situations by Bill English - SPTechConSPTechCon
 
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...SPTechCon
 
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...SPTechCon
 
Microsoft Keynote by Richard Riley - SPTechCon
Microsoft Keynote by Richard Riley - SPTechConMicrosoft Keynote by Richard Riley - SPTechCon
Microsoft Keynote by Richard Riley - SPTechConSPTechCon
 
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechConTen Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechConSPTechCon
 
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...SPTechCon
 
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechConLaw & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechConSPTechCon
 
What IS SharePoint Development? by Mark Rackley - SPTechCon
 What IS SharePoint Development? by Mark Rackley - SPTechCon What IS SharePoint Development? by Mark Rackley - SPTechCon
What IS SharePoint Development? by Mark Rackley - SPTechConSPTechCon
 
The SharePoint and jQuery Guide by Mark Rackley - SPTechCon
The SharePoint and jQuery Guide by Mark Rackley - SPTechConThe SharePoint and jQuery Guide by Mark Rackley - SPTechCon
The SharePoint and jQuery Guide by Mark Rackley - SPTechConSPTechCon
 
Understanding and Implementing Governance for SharePoint 2010 by Bill English...
Understanding and Implementing Governance for SharePoint 2010 by Bill English...Understanding and Implementing Governance for SharePoint 2010 by Bill English...
Understanding and Implementing Governance for SharePoint 2010 by Bill English...SPTechCon
 
Integrate External Data with the Business Connectivity Services by Tom Resing...
Integrate External Data with the Business Connectivity Services by Tom Resing...Integrate External Data with the Business Connectivity Services by Tom Resing...
Integrate External Data with the Business Connectivity Services by Tom Resing...SPTechCon
 
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...SPTechCon
 
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...SPTechCon
 
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...SPTechCon
 
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...SPTechCon
 
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...SPTechCon
 
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...SPTechCon
 
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechConCreating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechConSPTechCon
 

More from SPTechCon (20)

Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechConDeep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
 
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
 
“Managing Up” in Difficult Situations by Bill English - SPTechCon
“Managing Up” in Difficult Situations by Bill English - SPTechCon“Managing Up” in Difficult Situations by Bill English - SPTechCon
“Managing Up” in Difficult Situations by Bill English - SPTechCon
 
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
 
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
 
Microsoft Keynote by Richard Riley - SPTechCon
Microsoft Keynote by Richard Riley - SPTechConMicrosoft Keynote by Richard Riley - SPTechCon
Microsoft Keynote by Richard Riley - SPTechCon
 
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechConTen Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
 
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
 
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechConLaw & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
 
What IS SharePoint Development? by Mark Rackley - SPTechCon
 What IS SharePoint Development? by Mark Rackley - SPTechCon What IS SharePoint Development? by Mark Rackley - SPTechCon
What IS SharePoint Development? by Mark Rackley - SPTechCon
 
The SharePoint and jQuery Guide by Mark Rackley - SPTechCon
The SharePoint and jQuery Guide by Mark Rackley - SPTechConThe SharePoint and jQuery Guide by Mark Rackley - SPTechCon
The SharePoint and jQuery Guide by Mark Rackley - SPTechCon
 
Understanding and Implementing Governance for SharePoint 2010 by Bill English...
Understanding and Implementing Governance for SharePoint 2010 by Bill English...Understanding and Implementing Governance for SharePoint 2010 by Bill English...
Understanding and Implementing Governance for SharePoint 2010 by Bill English...
 
Integrate External Data with the Business Connectivity Services by Tom Resing...
Integrate External Data with the Business Connectivity Services by Tom Resing...Integrate External Data with the Business Connectivity Services by Tom Resing...
Integrate External Data with the Business Connectivity Services by Tom Resing...
 
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
 
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
 
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
 
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
 
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
 
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
 
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechConCreating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
 

Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTechCon

  • 1. Advanced SharePoint 2010 and 2013 Web Part Development Rob Windsor rwindsor@portalsolutions.net @robwindsor
  • 2. About Me • Senior SharePoint Architect with Portal Solutions • Technical Contributor to the Pluralsight On-Demand Library • Microsoft MVP, MCPD, MCT • Founder and Past-President of the North Toronto .NET UG • Co-author of Prof. Visual Basic 2012 and .NET 4.5 (Wrox)
  • 3. Session Prerequisites • Experience developing for SharePoint • Experience building Web Parts
  • 4. Agenda • Visual Web Parts • Persistent Web Part Properties • Editor Parts • Connectable Web Parts • Web Part Verbs • Asynchronous Web Parts • Web Part Gallery • Web Part Pages
  • 5. Visual Web Parts • Visual web parts traditionally combine a web part with a user control • User controls have full design experience in Visual Studio • User interface and code behind defined in user control • Web part “injects” user control dynamically using Page.LoadControl private const string _ascxPath = @"~/_CONTROLTEMPLATES/.../MyUserControl.ascx"; protected override void CreateChildControls() { Control control = Page.LoadControl(_ascxPath); Controls.Add(control); }
  • 6. Web Parts in Sandboxed Solutions • Split page rendering  Page code runs in ASP.NET worker process  Sandboxed web part code runs in sandbox worker process  HTML markup and JavaScript from two worker processes merged • Sandbox restrictions  Reduced set of server object model API  Restricted access outside SharePoint  No elevation of permissions  Cannot deploy files to SharePoint system folders  Must be ASP.NET web parts  Can only use ASP.NET controls  No web part connections
  • 7. Sandbox Visual Web Part Template • Native visual web part template not compatible with sandboxed solutions  Attempts to deploy user control to system folders • Visual Studio 2010 Power Tools introduced a sandbox compatible template  No user control  Designer makes web part behave like a user control  Markup in user control converted to code at design time • Visual Studio 2012 only has this template
  • 9. Web Part Properties • Web Parts support persistent properties • Configure properties via attributes  Personalizable(param)  Directs SharePoint to persist property value  Parameter indicates if property may be personalized  WebBrowsable(true)  Directs SharePoint to generate interface to edit property  WebDisplayName, WebDescription  The prompt and tooltip that accompany the data entry element  Category  The group in which the properties will be shown [Personalizable(PersonalizationScope.Shared)] [WebBrowsable(true)] [WebDisplayName("Year")] [Category("Pluralsight")] public int Year { get; set; }
  • 11. Cross Site Script Safeguards • Added in SharePoint 2010 • Indicates developer has taken steps to ensure code is safe against scripting attacks • Two key pieces  SafeAgainstScript attribute of SafeControl entry  RequiresDesignerPermission attribute • Contributors can only set web part properties if:  SafeAgainstScript is true (not the default)  RequiresDesignerPermission is false (default)
  • 13. Editor Parts • Editor parts enable user customization • Editor parts contained within an editor zone • ASP.NET supplies standard editor parts  Layout, appearance, etc • Developers can create custom editor parts  Similar development experience to Web Part  Control over interface used to edit properties  Ability to validate user input • In web part  Override CreateEditorParts • In editor part  Override CreateChildControls, SyncChanges and ApplyChanges
  • 15. Creating Connectable Web Parts • Pass data from one web part to another • Loosely-coupled connection  Communication managed by WebPartManager  Provider web part supplies data  Consumer web parts retrieve data • Interface used to define data contract  ASP.NET has standard connection contracts  Shown later in this module  Can use custom connection contracts • SharePoint provides user interface elements to establish connections • Not compatible with sandboxed solutions
  • 17. Web Part Connections using Ajax • Communication between web parts requires a postback • Generally, only consumer web part needs to be updated • Can use partial page rendering (UpdatePanel) to only update consumer • Problem:  Event triggered by provider  UpdatePanel in consumer • Solution:  Pass reference to control that triggers update from provider to consumer  Consumer registers control as AsyncPostbackControl with ScriptManager
  • 19. Web Part Verbs • Add additional menu options to dropdown at top-right of Web Part • Can be handled client-side, server- side or both.
  • 20. Web Part Verbs public override WebPartVerbCollection Verbs { get { var verbs = new List<WebPartVerb>(); var verb1 = new WebPartVerb(this.ID + "_ClientSideRssOpenerVerb", string.Format("window.open('{0}','RSSXML')", this.FeedUrl)); verb1.Description = "Open RSS Feed in an external window"; verb1.Text = "Open RSS Feed"; verbs.Add(verb1); var verb2 = new WebPartVerb(this.ID + "_ServerSideRssOpenerVerb", new WebPartEventHandler(ServerSideVerbHandler)); verb2.Description = "Load the RSS Source Feed."; verb2.Text = "View RSS Source Feed"; verbs.Add(verb2); var allverbs = new WebPartVerbCollection(base.Verbs, verbs); return allverbs; } }
  • 22. Asynchronous Web Parts • Long running tasks are blocking calls  One web part can bring a page to a crawl  When on the same page, multiple instances can kill the user experience • Make long running tasks asynchronous  Don’t hold up page processing
  • 23. Asynchronous Web Parts protected void Page_PreRender(object sender, EventArgs e) { Page.RegisterAsyncTask( new PageAsyncTask( new BeginEventHandler(BeginFeed), new EndEventHandler(EndFeed), new EndEventHandler(TimoutFeed), null, true)); } public IAsyncResult BeginFeed(object sender, EventArgs e, AsyncCallback cb, object state) { _feedCaller = GetFeed; return _feedCaller.BeginInvoke(cb, state); } public void EndFeed(IAsyncResult ar) { var feed = _feedCaller.EndInvoke(ar); var posts = from item in feed.Descendants("item") select new { Title = item.Element("title").Value, Description = item.Element("description").Value, Published = DateTime.Parse(item.Element("pubDate").Value) }; posts = posts.Skip(_pageNum * _hostPart.PageSize).Take(_hostPart.PageSize); FeedListView.DataSource = posts.ToList(); FeedListView.DataBind(); }
  • 25. Cleaning the Web Part Gallery • Files provisioned into Content DB do not get removed on Feature deactivation  This includes webpart / dwp files added to Web Part Gallery • Deletion of files can be done in Feature receiver  Examine element manifests to find web parts  Remove from web part gallery
  • 26. Cleaning the Web Part Gallery public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { var site = properties.Feature.Parent as SPSite; if (site == null) return; var parts = new List<string>(); var elements = properties.Definition.GetElementDefinitions(CultureInfo.CurrentCulture); foreach (SPElementDefinition element in elements) { if (element.ElementType != "Module") continue; var node = element.XmlDefinition; if (node.Attributes["Url"].Value != "_catalogs/wp") continue; foreach (XmlElement childNode in node.ChildNodes) { if (childNode.Name == "File") { parts.Add(childNode.GetAttribute("Url")); } } } var web = site.RootWeb; var gallery = web.Lists["Web Part Gallery"]; var items = gallery.Items; for (int i = items.Count - 1; i >= 0; i--) { var item = items[i]; if (parts.Contains(item.File.Name)) { item.Delete(); } } }
  • 28. Creating Web Part Page Templates • Create a site page • Set base type to Microsoft.SharePoint.WebPartPages.WebPartPage • Add one or more web part zones to page • Provision page instances using Module <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %> <!-- Other register directives --> <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, …" %> <%@ Page Language="C#" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage" MasterPageFile="~masterurl/default.master" %> <asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server"> <WebPartPages:WebPartZone ID="MainZone" runat="server" FrameType="TitleBarOnly" Title="Main Web Part Zone" /> </asp:Content>
  • 29. Adding Web Parts to Web Part Pages • Use SPLimitedWebPartManager  Get reference from property of Page object • Use SPLimitedWebPartManager.AddWebPart to add var page = web.GetFile("SiteAssets/Test02.aspx"); using (var manager = page.GetLimitedWebPartManager( PersonalizationScope.Shared)) { if (!manager.WebParts.Contains(webPartTitle)) { var part = new MostPopularProducts2.MostPopularProducts2(); part.Title = "Most Popular Products"; part.Category = "Condiments"; part.Year = 1997; manager.AddWebPart(part, "Left", 0); } } Note: Contains method shown in code sample is a custom extension
  • 30. DEMO Creating Web Part Pages and Adding Web Parts
  • 31. Additional Stuff • Closing versus deleting web parts  Closing a web part does not remove it from page  Having many closed web parts on a page can degrade performance  Set AllowClose to false to remove option to close from web part verbs • Versioning  DO NOT change the assembly version of your assemblies  SharePoint stores the full name with version of all web parts in galleries and on pages  Use the AssemblyFileVersion instead
  • 32. Thank You • Big thanks to the organizers, sponsors and you for making this event possible • Please fill out your evaluation • Please keep in touch rwindsor@portalsolutions.net @robwindsor msmvps.com/blogs/windsor