Monday, March 20, 2017

Create HelloWorld WebPart in the new SharePoint Framework

Create HelloWorld WebPart in the new SharePoint Framework

Objective

In this lab, you will build a SharePoint client-side web part.

Scenario

Client-side web parts are client-side components that run inside the context of a SharePoint page. Client-side web parts can be deployed to SharePoint Online, and you can also use modern JavaScript tools and libraries to build them.
Client-side web parts support:
•Building with HTML and JavaScript.
•Both SharePoint online and on-premises environments.
Note: The SharePoint Framework is currently in preview and is subject to change. SharePoint Framework client-side web parts are not currently supported for use in production environments.

Virtual Machines

  1. QSC 1511 Master

Exercise 1 : Create a new web part project

In this exercise, you will create a new web part project.
  1. Sign in to the virtual machine
    Sign in to the virtual machine using Developer as the username and P@ssw0rd! as the password.

    You can find the credentials needed for this lab on the Content tab in the lab environment.
  2. Open a Command Prompt window
    In the Search bar, type cmd, and then press Enter.
  3. Create a project folder
    At the command prompt, type md helloworld-webpart.
  4. Change to the project folder
    At the command prompt, type cd helloworld-webpart.
  5. Run the Yeoman SharePoint Generator
    Create a new HelloWorld web part by running the Yeoman SharePoint Generator. At the command prompt, type yo @microsoft/sharepoint.
  6. Accept the default helloworld-webpart
    When prompted, accept the default helloworld-webpart as your solution name and choose Enter.
  7. Place files in the current folder
    Select Use the current folder for where to place the files.
  8. Set the web part name
    Accept the default HelloWorld as your web part name and choose Enter.
  9. Accept the default description
    Accept the default HelloWorld description as your web part description and choose Enter.
  10. Accept the default No javascript web framework
    Accept the default No javascript web framework as the framework you would like to use and choose Enter.
    At this point, Yeoman will install the required dependencies and scaffold the solution files along with the HelloWorld web part. This might take a few minutes.
  11. Review the scaffold completion message
    When the scaffold is complete, you should see the message shown in the Screenshot indicating a successful scaffold.
    For information about known issues, see http://dev.office.com/sharepoint/docs/spfx/web-parts/basics/known-issues.
  12. Close Command Prompt Window
    Close Command Prompt Window.
You have now created a new web part project.

Exercise 2 : Preview the web part

In this exercise,you will preview your web part, build and run it on a local web server. 
  1. Open new Command Prompt window
    Open new Command Prompt window.
  2. At the command prompt, type cd helloworld-webpart
    At the command prompt, type cd helloworld-webpart
  3. Run gulp serve to build and preview the web part
    Make sure you are still in the helloworld-webpart directory and enter the command gulp serve to build and preview your web part:

    The client-side toolchain uses HTTPS endpoint by default. However, since a default certificate is not configured for the local dev environment, your browser will report a certificate error. Depending on the browser you are using, you may need to add exception (for example, Mozilla Firefox) or click Advanced and select to proceed to the website (for example, Microsoft Edge or Google Chrome).
    This command will execute a series of gulp tasks to create a local, Node-based HTTPS server on 'localhost:4321' and launch your default browser to preview web parts from your local dev environment.
  4. Review gulp
    SharePoint client-side development tools use gulp as the task runner to handle build process tasks such as those shown in the Knowledge [Bulb in head] window.

    You can access gulp at http://gulpjs.com/.
    • Bundle and minify JavaScript and CSS files.
    • Run tools to call the bundling and minification tasks before each build.
    • Compile SASS files to CSS.
    • Compile TypeScript files to JavaScript.

    If you are new to gulp, you can read Using Gulp which describes using gulp with Visual Studio in conjunction with building ASP.NET 5 projects.

    Visual Studio Code provides built-in support for gulp and other task runners. Choose Ctrl+Shift+B on Windows or Cmd+Shift+B on Mac to debug and preview your web part.
  5. Click the + to open the toolbox
    To add the HelloWorld web part, choose the add (+) button to open the toolbox

    The add button opens the toolbox where you can see a list of web parts available for you to add. The list will include the HelloWorld web part as well other web parts available locally in your development environment.
    SharePoint workbench is a developer design surface that enables you to quickly preview and test web parts without deploying them in SharePoint. SharePoint workbench includes the client-side page and the client-side canvas in which you can add, delete and test your web parts in development.
  6. Choose HelloWorld to add the web part to the page
    Choose HelloWorld to add the web part to the page
  7. View the web part
    View the web part on the page.

    Congratulations! You have just added your first client-side web part to a client-side page.
  8. View the web part property pane
    Now, choose the pencil icon on the far left of the web part to reveal the web part property pane.
    The property pane is where you can define properties to customize your web part. The property pane is client-side driven and provides a consistent design across SharePoint.
  9. Modify the description text
    Modify the text in the Description text box to Client-side web parts are awesome!
    Notice how the text in the web part also changes as you type.

    One of the new capabilities available to the property pane is to configure its update behavior, which can be set to reactive or non-reactive. By default the update behavior is reactive and enables you to see the changes as you edit the properties. The changes are saved instantly as when the behavior is reactive.
You have now previewed your web part, built and run it on a local web server. 

Exercise 3 : Web part project structure

You can use Visual Studio Code to explore the web part project structure.

Because the SharePoint client-side solution is HTML/TypeScript based, you can use any code editor or IDE that supports client-side development to build your web part, such as:
  • Visual Studio Code
  • Sublime
  • Atom
  • Webstorm
Note: This lab uses Visual Studio code in the steps and examples. You can use any IDE that you prefer.

Using Visual Studio 2015
Currently, support for SharePoint client-side projects in Visual Studio is available through NodeJS Tools for Visual Studio.
  1. Change to the src\webparts\helloWorld folder
    At the command prompt, go to the src\webparts\helloWorld directory.
    Make sure you are in the C:\Users\Developer\helloworld-webpart folder.
  2. Enter the command code
    Enter the command code . (please note: code "dot")  to open the web part project in Visual Studio Code.
    Make sure you enter the command code  . including the .
  3. Review the Web part class
    HelloWorldWebPart.ts defines the main entry point for the web part. The web part class HelloWorldWebPart extends the BaseClientSideWebPart. Any client-side web part should extend the BaseClientSideWebPart class in order to be defined as a valid web part.
    public constructor(context: IWebPartContext) {
        super(context);
    }

    TypeScript is the primary language for building SharePoint client-side web parts. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. SharePoint client-side development tools are built using TypeScript classes, modules, and interfaces to help developers build robust client-side web parts.
  4. Review property type IHelloWorldWebPartProps
    BaseClientSideWebPart implements the minimal functionality that is required to build a web part. This class also provides many parameters to validate and access to read-only properties such as displayMode, web part properties, web part context, web part instanceId, the web part domElement and much more.

    Notice that the web part class is defined to accept a property type IHelloWorldWebPartProps.

    The property type is defined as an interface in a separate file IHelloWorldWebPartProps.ts.
    export interface IHelloWorldWebPartProps {
        description: string;
    }

    This property definition is used to define custom property types for your web part, which is described in the property pane section later.
  5. Review the web part render method
    The DOM element where the web part should be rendered is available in the render method. This method is used to render the web part inside that DOM element.
    In the HelloWorld web part, the DOM element is set to a DIV. The method parameters include the display mode (either Read or Edit) and the configured web part properties if any.

    public render(): void {
      this.domElement.innerHTML = `
       

         

           

             

                Welcome to SharePoint!
               
    Customize SharePoint experiences using Web Parts.

               
    ${this.properties.description}

               
                  Learn more
               

             

           

       

     
    `;
    }
  6. Review how you would load a React component
    This model is flexible enough so that web parts can be built in any JavaScript framework and loaded into the DOM element. The Knowledge [Bulb in head] window shows an example of how you would load a React component instead of plain HTML.
    render(): void {
        let e = React.createElement(TodoComponent, this.properties);
        ReactDom.render(e, this.domElement);
    }

    Note: The Yeoman SharePoint generator lets you choose React as your framework of choice when adding a new web part to the project.
  7. Configure the Web part property pane
    The property pane is also defined in the HelloWorldWebPart class. The propertyPaneSettings property is where you need to define the property pane.

    When the properties are defined, you can access them in your web part using this.properties., as shown in the render method in the Knowledge [Bulb in head] window.
    ${this.properties.description}


    Read the Integrating property pane with a web part article to learn more about how to work with the property pane and property pane field types.

    http://dev.office.com/sharepoint/docs/spfx/web-parts/basics/integrate-with-property-pane
  8. Replace the propertyPaneSettings method
    Replace the propertyPaneSettings method with the code in the Knowledge [Bulb in head] window which shows how to add property types other than TextField.

    You can select the code, right-click, click Copy, and then in the code window, right-click and Paste.
    protected get propertyPaneSettings(): IPropertyPaneSettings {
      return {
        pages: [
          {
            header: {
              description: strings.PropertyPaneDescription
            },
            groups: [
              {
                groupName: strings.BasicGroupName,
                groupFields: [
                PropertyPaneTextField('description', {
                  label: 'Description'
                }),
                PropertyPaneTextField('test', {
                  label: 'Multi-line Text Field',
                  multiline: true
                }),
                PropertyPaneCheckbox('test1', {
                  text: 'Checkbox'
                }),
                PropertyPaneDropdown('test2', {
                  label: 'Dropdown',
                  options: [
                    { key: '1', text: 'One' },
                    { key: '2', text: 'Two' },
                    { key: '3', text: 'Three' },
                    { key: '4', text: 'Four' }
                  ]}),
                PropertyPaneToggle('test3', {
                  label: 'Toggle',
                  onText: 'On',
                  offText: 'Off'
                })
              ]
              }
            ]
          }
        ]
      };
    }
  9. Import property fields
    Since we added new property fields, let's import those from the framework.

    Scroll to the top of the file and add the the fields shown in the Knowledge [Bulb in head] window to the import section from @microsoft/sp-client-preview:
    PropertyPaneCheckbox,
    PropertyPaneDropdown,
    PropertyPaneToggle
  10. Review the complete import section
    The complete import section will look like the sample shown in the Knowledge [Bulb in head] window.
    import {
      BaseClientSideWebPart,
      IPropertyPaneSettings,
      IWebPartContext,
      PropertyPaneTextField,
      PropertyPaneCheckbox,
      PropertyPaneDropdown,
      PropertyPaneToggle
    } from '@microsoft/sp-client-preview';
  11. Save the file
    Save the file.
  12. Replace the code in IHelloWorldWebPartProps.ts
    Open IHelloWorldWebPartProps.ts and replace the existing code with the code in the Knowledge [Bulb in head] window.

    These properties map to our fields we just added.
    export interface IHelloWorldWebPartProps {
        description: string;
        test: string;
        test1: boolean;
        test2: string;
        test3: boolean;
    }
    export interface IHelloWorldWebPartProps {
        description: string;
        test: string;
        test1: boolean;
        test2: string;
        test3: boolean;
    }
    
  13. Save the file
    Save the file.
  14. Switch back to the HelloWorldWebPart.ts file
    Switch back to the HelloWorldWebPart.ts file.
    After you add your properties to the web part properties, you can access the property in the same way you accessed the description property earlier:

    ${this.properties.test2}

  15. Modify HelloWorldWebPart.manifest.json properties
    Open HelloWorldWebPart.manifest.json and modify the properties to the values shown in the Knowledge [Bulb in head] window.

    To set the default value for the property, you will need to update the web part manifest's properties property bag.
    "properties": {
      "description": "HelloWorld",
      "test": "Multi-line text field",
      "test1": true,
      "test2": "2",
      "test3": true
    }
  16. Review the web part manifest
    The HelloWorldWebPart.manifest.json file defines the web part metadata such as version, id, display name, icon, and description. Every web part should contain this manifest.
    {
      "$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
      "id": "2f1ef3e2-5f37-4da8-b1ff-52c468a28ae2",
      "componentType": "WebPart",
      "version": "0.0.1",
      "manifestVersion": 2,
      "preconfiguredEntries": [
        {
          "groupId": "2f1ef3e2-5f37-4da8-b1ff-52c468a28ae2",
          "group": {
            "default": "Under Development"
          },
          "title": {
            "default": "HelloWorld"
          },
          "description": {
            "default": "HelloWorld description"
          },
          "officeFabricIconFontName": "Page",
          "properties": {
            "description": "HelloWorld",
            "test": "Multi-line text field",
            "test1": true,
            "test2": "2",
            "test3": true
          }
        }
      ]
    }

Exercise 4 : Set up your Office 365 tenant

To build and deploy client-side web parts using the preview release of the SharePoint Framework, you will need an Office 365 tenant and a developer site collection.

Note: The SharePoint Framework is currently in preview and is subject to change. SharePoint Framework client-side web parts are not currently supported for use in production environments.
  1. Sign in to your Office 365 tenant
    Open Chrome, and then navigate to http://portal.office.com. Sign in using the Office 365 username and password shown on te Content tab in the lab environment.
    If you prefer, you can sign in to your own Office 365 E5 or developer tenant.
  2. Navigate to your SharePoint site
    In Office 365, click SharePoint and record your site URL.
  3. Create an app catalog site
    You will need an app catalog to upload and deploy web parts. Go to the SharePoint Admin Center by entering the URL https://yourtenantprefix-admin.sharepoint.com in your browser. Replace yourtenantprefix with your Office 365 tenant prefix.
  4. Select the App Catalog
    In the left sidebar, choose the apps menu item and then choose App Catalog.
  5. Choose OK to create a new app catalog site
    Choose OK to create a new app catalog site.
  6. Enter app catalog details
    In the next page, enter the details as shown in the Knowledge [Bulb in head] window.
    • Title: App Catalog
    • Web Site Address suffix: apps
    • Administrator: Enter your username and choose the resolve button to resolve the username.
  7. Choose OK to create the app catalog site
    Choose OK to create the app catalog site.
    SharePoint will create the app catalog site and you will be able to see its progress in the SharePoint admin center.
  8. Create a new Developer site collection
    You also need a Developer Site.

    Go to the SharePoint Admin Center by entering the URL https://yourtenantprefix-admin.sharepoint.com in your browser. Replace yourtenantprefix with your Office 365 Tenant prefix.
  9. Choose New -> Private Site Collection
    In the SharePoint ribbon, choose New -> Private Site Collection.
  10. Add details
    In the dialog box, enter the details shown in the Knowledge [Bulb in head] window.
    • Title: Developer Site
    • Web Site Address suffix: dev
    • Template Selection: Select Developer Site as the site collection template.
    • Administrator: Enter your username and choose the resolve button to resolve the username.
  11. Create the site collection
    Choose OK to create the site collection.
    SharePoint will create the developer site and you will be able to see its progress in the SharePoint admin center. After the site is created, you can browse to your developer site collection.
  12. Set up a document library
    Choose the gears icon on the top right and then choose Site Settings to open the settings page.
    Make sure you are on your dev site. /Sites/dev
    In order to use the preview features, you will need to set up a document library with a new column and upload SharePoint workbench. This procedure uses the default document library in your developer site collection. This will be called Documents in the left navigation.
  13. Choose Site libraries and lists
    Choose Site libraries and lists under the Site Administration category.
  14. Choose Customize Documents
    Choose Customize Documents.
  15. Choose Create column
    Choose Create column under Columns.
  16. Enter ClientSideApplicationId as the column name
    Enter ClientSideApplicationId as the column name and leave the other fields at their current values.
  17. Choose OK
    Choose OK to create the column.
  18. Save the SharePoint workbench file
    Download the workbench.aspx file at https://github.com/SharePoint/sp-dev-docs/blob/master/workbench.aspx to your desktop.

    Open the context menu (right-click) on the "raw" link in the middle of the page and choose Save Link As to save the file as workbench.aspx to your desktop.
    You need to upload the SharePoint workbench to test your web parts on SharePoint.
  19. Upload the workbench.aspx file
    Upload the file to the Documents library in the dev site collection.
    If you get the following exception when moving to the workbench.aspx page:

    "The requested operation is part of an experimental feature that is not supported in the current environment. The requested operation is part of an experimental feature that is not supported in the current environment."

    You are not using a developer tenant. You might be using a first release or normal tenant.

Exercise 5 : Preview the web part in SharePoint

SharePoint workbench is also hosted in SharePoint to preview and test your local web parts in development. The key advantage is that now you are running in SharePoint context and that you will be able to interact with SharePoint data.
  1. Open SharePoint Workbench
    Go to the following URL: https://your-sharepoint-site/Shared%20Documents/workbench.aspx
    By default, your browser is configured not to load scripts from localhost. Workbench will notify you if that is the case.
  2. Configure the browser to load scripts, if prompted
    In order to execute local scripts, you will need to configure the browser to load scripts from unauthenticated sources. This is due to loading scripts over HTTP while connected to a page via HTTPS. Depending on the browser you use, the options to enable this may vary. For example, in the Chrome browser, click the grey shield in the right side of the address bar to load unsafe scripts.
    In the Chrome browser, click the grey shield in the right side of the address bar to load unsafe scripts.
    If you used the Chrome browser to load the local workbench, you may not be prompted to load unsafe scripts again.
  3. Add the hello world web part to the canvas
    After you enable loading scripts, you should see the workbench load. Add the hello world web part to the canvas.
    Notice that the SharePoint workbench now has the Office 365 Suite navigation bar.
  4. Reveal the toolbox
    Choose add icon in the canvas to reveal the toolbox.
    The toolbox now shows the web parts available on the site where the SharePoint workbench is hosted along with your HelloWorldWebPart.
  5. Add HelloWorldWebPart from the toolbox
    Add HelloWorldWebPart from the toolbox.
    Now you're running your web part in a page hosted in SharePoint!

    Because you are still developing and testing your web part, there is no need to package and deploy your web part to SharePoint.

Congratulations on getting your first Hello World web part running!

No comments: