Cloud development - All about M365, .NET, SharePoint and more…
About Me
Contact Me
  • About Me
  • Contact Me
Cloud development - All about M365, .NET, SharePoint and more…
Development, SharePoint

Creating a Custom SharePoint Online Webpart to Display Contact Details with Photos

One of the powerful capabilities of SharePoint Online is its ability to create and utilize custom web parts. These web parts can help to extend the platform’s functionalities to meet specific organizational needs. In this tutorial, we will walk you through the process of creating a custom web part that displays user contact details along with their photos.

Our web part will be created using the SharePoint Framework (SPFx), which is a page and web part model for SharePoint Online. We’ll use TypeScript for the back-end, and ReactJS for the front-end. The entire process involves the following steps:

  1. Setting up the Development Environment
  2. Creating a New SharePoint Framework Solution
  3. Developing the Web Part
  4. Deploying and Testing the Web Part

Please make sure you have administrative access to the SharePoint Online and Office 365 environment. Let’s get started.

Step 1: Setting up the Development Environment

To set up your SharePoint Framework development environment, you will need Node.js, Yeoman, and the SharePoint client-side solution generator, and Gulp. Open a command prompt and run the following commands to install these dependencies:

npm install -g yo gulp
npm install -g @microsoft/generator-sharepoint

Step 2: Creating a New SharePoint Framework Solution

Now, let’s create a new SharePoint Framework solution.

Navigate to the folder where you want to create the solution, and run the following command:

yo @microsoft/sharepoint

The Yeoman SharePoint generator will start prompting you for the following information:

  • What is your solution name?
  • Where do you want to place the files?
  • Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without running any feature deployment or adding apps in sites?
  • Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant?
  • Which type of client-side component to create?

For this example, choose the following:

  • Solution Name: UserContactWebPart
  • Baseline packages: Use the current folder
  • Deployment option: Select Y (Yes)
  • Permissions: N (No)
  • Component Type: WebPart
  • Web part name: UserContact
  • Description: A web part that displays user contact details
  • Framework: React

Step 3: Developing the Web Part

Navigate into the solution folder, and open the file src/webparts/userContact/components/UserContact.tsx

This file represents the frontend of your webpart.

You need to install the Microsoft Graph client library. To do this, run the following command:

npm install @microsoft/microsoft-graph-client

Now, let’s edit our UserContact.tsx file:

 --
import * as React from 'react';
import styles from './UserContact.module.scss';
import { IUserContactProps } from './IUserContactProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { MSGraphClient } from '@microsoft/sp-http';
export interface IUserContactState {
  users: any[];
}
export default class UserContact extends React.Component<IUserContactProps, IUserContactState> {
  constructor(props: IUserContactProps) {
    super(props);
    this.state = {
      users: []
    };
  }
  public componentDidMount() {
    this.props.context.msGraphClientFactory
      .getClient()
      .then((client: MSGraphClient): void => {
        // get users and their photos from Microsoft Graph
        client
          .api('/users')
          .version('v1.0')
          .get((err, res) => {
            if (err) {
              console.error(err);
              return;
            }
            this.setState({ users: res.value });
          });
      });
  }
  public render(): React.ReactElement<IUserContactProps> {
    return (
      <div className={styles.userContact}>
        {this.state.users.map((user, key) => {
          return (
            <div key={key}>
              <h2>{user.displayName}</h2>
              <p>{user.mail}</p>
              <img src={`/_layouts/15/userphoto.aspx?size=L&username=${user.mail}`} alt="User photo" />
            </div>
          );
        })}
      </div>
    );
  }
}

Step 4: Deploying and Testing the Web Part

Now that our web part is developed, let’s deploy and test it.

To build and bundle your web part, run the following command in your command prompt:

gulp bundle --ship

And to package the solution, use the following command:

gulp package-solution --ship

These commands create a .sppkg package in the sharepoint/solution folder. You can upload this package to the SharePoint App Catalog in your SharePoint Online site. After uploading, you can add your web part to a page by editing the page and clicking the ‘+’ button to add a new web part. Note you’ll need to have specific permissions assigned to query Graph API.

And there you have it, a custom SharePoint Online web part that displays user contact details along with their photos. You can customize this web part further as per your needs. Happy coding!

June 3, 2023by Luke
Development, SharePoint

How to Create a Custom Wall Posts Webpart in SharePoint 2016

SharePoint is a versatile platform for building solutions that can fulfill various business needs. One such feature is the ability to create a custom webpart, a reusable component that can be included in SharePoint sites to provide specific functionality. Today, we’ll be discussing how to create a custom Wall Posts webpart for SharePoint 2016.

Before we begin, we should note that our custom wall posts webpart will be created using Visual Studio 2019, which supports development for SharePoint 2016. We will be writing in C# and using JavaScript and CSS for the front-end. Please ensure you have the necessary permissions to create and deploy custom webparts in your SharePoint environment.

Step 1: Create a New Project

Open Visual Studio 2019 and create a new project.

  • Select File … New … Project.
  • In the New Project dialog, choose Visual C# … Office/SharePoint … SharePoint Add-in. Click Next.
  • Enter a name and location for your project and click Create.
  • In the “What SharePoint site do you want to use for debugging?” box, enter the URL of the SharePoint site you’re developing against, and then choose “Deploy as a farm solution”. Click Finish.

Step 2: Add a New Web Part Item

Next, we’ll add a new web part to the project:

  • In Solution Explorer, right-click on the project, go to Add, then New Item.
  • In the Add New Item dialog, choose Visual C# … Office/SharePoint … Web Part.
  • Give it a name like “WallPostsWebPart” and click Add.

Step 3: Code Your Web Part

You will now hae a new file in your project named WallPostsWebPart. This is where you’ll write the backend code for your webpart.

using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
namespace WallPostsWebPart.WallPostsWebPart
{
    [ToolboxItemAttribute(false)]
    public class WallPostsWebPart : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/15/WallPostsWebPart/WallPostsWebPart/WallPostsWebPartUserControl.ascx";
        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);
        }
        
        // Fetching the wall posts
        public string GetWallPosts()
        {
            SPSite site = new SPSite("http://YourSharepointSite");
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Posts"]; // This should be the name of your wall posts list
            SPQuery query = new SPQuery();
            query.Query = "<OrderBy><FieldRef Name='Created' Ascending='FALSE'/></OrderBy>"; // This orders the posts by creation date, newest first
            SPListItemCollection items = list.GetItems(query);
            
            StringBuilder sb = new StringBuilder();
            foreach(SPListItem item in items)
            {
                sb.Append("<p>");
                sb.Append(item["Title"].ToString()); // Assuming "Title" field holds the post content
                sb.Append("</p>");
            }
            return sb.ToString();
        }
    }
}

Step 4: Create the Front-End

Now, we need to create a user control to represent the front-end of our webpart. This is done in the “WallPostsWebPartUserControl.ascx” file.

And that’s it! Now, you can deploy the solution to your SharePoint site and add the webpart to a page to test it.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WallPostsWebPartUserControl.ascx.cs" Inherits="WallPostsWebPart.WallPostsWebPart.WallPostsWebPartUserControl" %>
<div id="wallPostsContainer">
    <%: this.GetWallPosts() %> <!-- This calls the GetWallPosts method we wrote in the code-behind -->
</div>

Step 5: Deploy the Solution

To deploy your custom webpart, follow these steps:

  • In Visual Studio, on the menu, select Build … Deploy Solution.
  • After the solution has been deployed, go to your SharePoint site and open a page where you want to add the webpart.
  • Click on the Page tab and then Edit.
  • Click on the Insert tab and then Web Part.
  • In the Categories list, click Custom, find your “WallPostsWebPart”, and then click Add.

Your custom Wall Posts webpart should now be visible on the SharePoint page.

In conclusion, creating a custom webpart in SharePoint allows you to create custom functionality and provide solutions specific to your business needs. The example above showcases a simple implementation of pulling wall posts, but the possibilities are endless. You can always expand and improve the functionality based on your requirements. Happy SharePointing!

June 3, 2023by Luke
Development, SharePoint

Creating a Custom Events Calendar Webpart for SharePoint 2016

SharePoint 2016, a platform developed by Microsoft, it provides robust capabilities for collaboration and document management. This blog post will guide you through the process of creating a custom events calendar webpart for SharePoint 2016, a feature that can help manage and display various organisational events. We’ll use JavaScript, SharePoint’s Client-Side Object Model (CSOM), and SharePoint’s REST API for this task.

Prerequisites:

Before we start, you will need:

  1. Access to a SharePoint 2016 site collection.
  2. Familiarity with JavaScript, HTML, and CSS.
  3. SharePoint Designer 2013 (It’s compatible with SharePoint 2016).
  4. Basic understanding of SharePoint’s REST API and CSOM.

Step 1: Set up the Calendar List

First, we need a Calendar List. If you already have one, you can skip this step. To create a Calendar List:

  1. On your SharePoint site, click on Site Contents … Add an App.
  2. Click on the Calendar tile and give it a name then hit Create.

Step 2: Create the WebPart

Now, let’s create the custom webpart. Follow these steps:

  1. Open SharePoint Designer and connect to your site.
  2. Go to File … New … WebPart and create a new web part.
  3. Paste the following base code into the .webpart file:
<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="Title" type="string">Custom Calendar WebPart</property>
        <property name="Description" type="string">This WebPart displays a custom events calendar.</property>
      </properties>
    </data>
  </webPart>
</webParts>

Step 3: Fetching Calendar Data with REST API

Next, we’ll use SharePoint’s REST API to fetch the calendar data. We’ll add the JavaScript code within the CDATA tags of the webpart file.

<![CDATA[
<script type="text/javascript">
  document.addEventListener('DOMContentLoaded', function(){
    var calendarListUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Calendar')/items?$select=Title,EventDate,EndDate";
    fetch(calendarListUrl, {
      headers: {
        "accept": "application/json;odata=verbose"
      }
    })
    .then(response => response.json())
    .then(data => renderEvents(data.d.results))
    .catch(error => console.error('Error:', error));
  });
  function renderEvents(events){
    // Rendering code goes here
  }
</script>
]]>

This script runs when the DOM is fully loaded. It fetches calendar events and calls a function renderEvents with the events data.

Step 4: Rendering the Events

The renderEvents function will be responsible for rendering events data. We’ll use a simple HTML structure for this example, but you could use any UI library or framework. Script refused to post as text, I believe WordPress uses some of the same internal function names and tried to run it as an actual script, you’ll need to retype this!

function renderEvents(events){
  var eventsHTML = events.map(event => `
    <div class="event">
      <h3>${event.Title}</h3>
      <p>Start: ${new Date(event.EventDate).toLocaleString()}</p>
      <p>End: ${new Date(event.EndDate).toLocaleString()}</p>
    </div>
  `).join('');
  
  var calendarElement = document.getElementById('calendar');
  if (calendarElement) {
    calendarElement.innerHTML = eventsHTML;
  }
}

Step 5: Adding WebPart to a SharePoint Page

Finally, let’s add the custom webpart to a SharePoint page.

  1. Navigate to your SharePoint page and click Edit.
  2. Click on Insert … WebPart … Custom and select your custom webpart.
  3. Click on Add and your custom events calendar webpart should now appear on your page.

That’s it! You have successfully created a custom events calendar webpart for SharePoint 2016. Please note that the calendar’s appearance can be customised using CSS, and you can expand the script to include more features like event filtering, sorting, or pagination.

June 3, 2023by Luke

Recent Posts

  • Mastering SharePoint Online REST APIs A Step-by-Step Guide
  • Building SharePoint Online Remote Event Receivers for Document Review Flows
  • Working with SharePoint Online REST Search API 101
  • Using the SPO Search REST API to create a Webpart showing Recently Modified Documents containing specific keywords
  • Creating a Custom SharePoint Online Webpart to Display Contact Details with Photos

Categories

  • Development
  • Latest
  • Patching
  • SharePoint
  • Testing
  • Tools

“I believe in doing what you enjoy, what drives you, what keeps you coming back for more. Code is life! Well it at least it pays the bills and lets me blog about it in my spare time!”

© 2019 copyright lukeosborne.dev // All rights reserved // Privacy Policy