Learning ReactJS – Environment set up using Webpack

Tags

, , , , ,


Its been a while I blogged about my learnings. Recently, I started learning ReactJS. I like to learn any programming language by writing code, that helps to remember the syntax as well. First step is to set up an environment. Along the process, I used many frameworks for setting up an environment.

  • NodeJS – as a web server
  • Want to write code in ES6, so I used BabelJS to transpile the code to JavaScript (ES2015)
  • Webpack – bundling tool, used for building the client app
  • Webpack-dev-server: local server app that serves the client application
  • npm – package manager

There are lot of documentation on internet that explains about these framework. I am going to leave the explanation about these and will jump onto our goal i.e. how to setup a developer environment for a ReactJS application.

Folder structure: maintaining code is one of favorite topic because its always hard to fix to a single pattern. Code folder structure is one important thing every developer needs to focus. For the purpose of this article I used below code structure.

img-1

'src': source code of the application (client app)
'dist': distribution\build version of the application
'.babelrc': configuring settings for babel transpiler
'package.json': npm scripts and also the dependent frameworks\libraries
'webpack.config.js': configuratoin setting for building the application

Prerequisites:

Step 1: Create a package.json under the root folder. You can create it manually but I suggest to use npm init script. Install the following dependencies.

npm install --save 'react' 'react-dom'

This is react framework, and the virtual dom that will be used for generating the DOM

Step 2: Let’s install Babel transpiler, since we are going to write code in ES6, we need code to be transpiled to ES2015. As of now, we do not require any polyfills, but if you are working on an old browser, please make sure you install the required polyfill.

npm install --save-dev 'babel-core' 'babel-loader' 'babel-preset-es2015' 'babel-preset-react'

Step 3: Installing webpack. As we need a bundling tool, and webpack is delivering many good features for bundling a client application.

npm install --save-dev 'webpack' 'webpack-dev-server'

At this point, we are all set to start configuring our application. These are the basic dependencies.

Step 4: Create a file .babelrc under root. we only installed two presets, so lets configure them. Use below code to configure the two presets.

{ "presets": ["es2015", "react"] }

Step 5: Create a webpack.config.js file. This is the configuration file for the webpack bundler.

var path = require('path');
var webpack = require('webpack');

var config = {
 entry: {
 app: "./src/main.js"
 },
 output: {
 path: path.join(__dirname, '/dist/'),
 filename: 'bundle.js',
 publicPath : '/dist'
 },
 devServer: {
 contentBase: '/dist',
 inline: true,
 port: 8082,
 hot: true,
 historyApiFallback: true
 },
 module: {
 loaders: [{
 test: /\.jsx?$/,
 exclude: /node_modules/,
 loader: 'babel',
 presets: ['es2015', 'react']
 }]
 }
};

module.exports = config;

In this configuration file, we tell the entry point of our application, the destination of the bundled files and the loaders required to transpile a code. Also, as we want to see the application in live, webpack dev server helps us to see the application in action. The local dev server configuration is also setup.

Step 6: create the entry of our application ‘main.js’ under the ‘src’ folder. In here, we prepare the app and will write it to the DOM. Find below the code:

import React from 'react';
import {render} from 'react-dom';
import App from './app/hello.jsx';

render(<App/>, document.getElementById('app'));

Step 7: Now, lets start preparing the application. Create a folder under ‘src’ and name it ‘app’. I like to keep all my application details under a folder. To start with, under ‘app’ folder create a file named ‘hello.jsx’. You can extend the application with many containers and components under the ‘app’ folder.

img-3

Step 8: Prepare an index.html under the dist folder. In my next article, I am going to put some notes around on how to build HTML template using webpack. Until then lets work on a basic way. Here is the initial HTML code. Make sure you add the bundle.js reference in the HTML.

img-2

Step 9: At this point, out basic ReactJS app is all configured. All you need to do is run the following script and you should be able to browse the application on http://localhost:8082

npm start

Here is a snapshot of the browser:

img-6

Please provide me your comments and feedback below. Hope this helps you to kick start your ReactJS learning.

Happy Coding!!!

Advertisements

Experience with Visual Studio Online

Tags

,


Today I opened my Visual Studio and saw a notification on the news feed of it. “VS 2013: Announcing Visual Studio Online”. Amazed by the idea and quickly searched for it and since MS has its own free trial packages for every product they release, I signed up for it. Here is my initial experience with Visual Studio Online:

  1. I am really impressed by Microsoft a lot these days. Their openness to the other technologies and integrating their products with other standard technologies. One such example is the use GIT in their online product. While creating a project VS online gave me an option to create a source control using the GIT.
  2. 1

  3. Once a test project is created the page is redirected to a team page wherein the VS team maintained its consistency of the process we use while creating the project. A quick preview of how to work with Code, Work, Build and Test tabs gives a complete reference guide on How to use the application
  4. 2

  5. Agile is completely available within the browser, that what I see:
    • Create a Product backlog
    • Create a Sprint backlog
    • Create a Bug, Feature, etc
    • 6

    • Pin your work items or the work items you want to track closely
    • Team members
    • Team rooms for discussions and announcements
    • Graphical overview of the progress of the product
    • Create your own custom filtered queries for the work items and check the collection
  6. A Sprint Overview of the project. Any stakeholder can easily get to know the status of a project and this is a way to capture risks and provide a resolutions
  7. 3

  8. Automating the build is one lovely thing for a developer and the administrators. That is how team server build always made it on the top thing for a project. And now its here in your browser
  9. 4

  10. A complete Test plan available.
  11. 9

  12. Coming to the CODE tab (my fav), it gave me an option to clone on my local before I get started
  13. 7

  14. Here is the explorer view of the solution that is being created. I say its kinda similar to Git but with the extensive VS features.
  15. 8

  16. I am unable to get a review of the IDE in browser though but there is based on the monaco with Windows Azure.

I hope this will be a rise of the VS platform. Lots of potentiality for the Projects and as a team.

Happy Coding!!!

[jQuery Plugin]: SharePoint 2013 client side people picker control

Tags

, ,


I am so much excited to share a plugin that I built and this is also my first step towards building a component and share it to the community. I will try to continue developing more utilities and share more information.

SharePoint 2013 has a changed the usability and functionality of a people picker. Also it enabled client side programming to search for users across Active Directory. More documentation on how to use a client side People Picker Control can be found here: How to: Use the client-side People Picker control in apps for SharePoint

Based on the documentation from MSDN I created a plugin to use it easily even in a content editor web part. Advantages of this plugin:

  1. Can be used everywhere – Content Editor Web part, Web Page, Custom Application page etc
  2. Easily configurable
  3. Open for customization

You can find the source code on github: Source Code

Here is a quick example of how to configure this in a content editor web part

  1. Download the sppeoplepicker.min.js from the above source code location and also the latest version of jQuery
  2. Upload the jQuery and sppeoplepicker.min.js to the Style Library
  3. Create a SharePoint Page and add a content editor web part.
  4. Edit the content editor web part and add the below references

    <script src="../Style Library//jquery.min.js"></script>
    <script src="../Style Library/sppeoplePicker.min.js"></script>
    
  5. Here is the html template for the demo
    
    <table class="spPeoplePickerTable" width="50%" cellpadding="10" cellspacing="1">
    	<tr>
    		<td>People Picker 1: </td>
    		<td><div id="peoplePickerDiv"></div></td>
    		<td><button id="pp1">Show</button></td>
    	</tr>
    	<tr>
    		<td>People Picker 2:</td>
    		<td><div id="anotherPeoplePickerDiv"></div></td>
    		<td><button id="pp2">Show</button></td>
    	</tr>
    
    </table>
    
    
    
  6. In the document.ready function register the people picker for the div elements
    <script type="text/javascript">
    	$(document).ready(function () {
    				$("#peoplePickerDiv").spPeoplePicker();
    				$("#anotherPeoplePickerDiv").spPeoplePicker();
    
    			
    			$("#pp1").click(function(){
    				alert($("#peoplePickerDiv").getUserInfo());
    				return false;
    			});
        		$("#pp2").click(function(){
    				alert($("#anotherPeoplePickerDiv").getUserInfo());
    				return false;
    			});
    
    	});
    	
    </script>
    
    
  7. To read the values from the control I also provided another method getUserInfo(). Applying this over the div element will read values from the control.
  8. Save the Content Editor web part and the page

Output:
User Selection
2

Get User Info on selected control
1

Hope this will help.

Happy Coding…!!!

Getting List Data in SharePoint 2013 using Rest api and Angular JS


In my previous post we are getting the list data and showing it in a Table. Even this post has the concept but I used services, and organised the code. Here is my script that gets the Employees list data into an Employees object.

In the view you can use the ng-repeat over these Employees and display employee information.

var employeesApp = angular.module('employeesApp', []);

employeesApp.factory('siteUrlBuilder', function($location){
return {
buildSiteUrl: function() {
var urlParts = $location.absUrl().split("/");
return urlParts[0] + "//" + urlParts[2] + "/" + urlParts[3] + "/" + urlParts[4];
}
}
}
);

employeesApp.factory('employeeListService', function($http, siteUrlBuilder){
return {
getEmployees : function(successcb, errorcb)
{
var getSiteUrl = siteUrlBuilder.buildSiteUrl();
$http(
{
method: "GET",
url: getSiteUrl + "/_api/web/lists/getByTitle('Employees')/items",
headers: { "Accept": "application/json;odata=verbose" }
}
).success(function (data, status, headers, config) {
successcb(data.d.results);
}).error(function (data, status, headers, config) {
errorcb(status);
});
}

}
}
);
employeesApp.controller('EmployeesController',
function($scope, $http, employeeListService) {
employeeListService.getEmployees(
function(data)
{
$scope.Employees = data
},
function()
{
alert('error');
}
);
}
);

Happy Coding…!!!

First step towards AngularJS with SharePoint 2013

Tags

, ,


Web Programming world is now shifting its gears towards scripting and there are many frameworks evolved recently all focused on the Model – View * pattern. Everything has got its own pros and cons.

Example:

  1. Knockout JS
  2. Angular JS
  3. Backbone JS
  4. Enber JS

All you need is to do some research and find out the best framework that is suitable for your developmental and business needs. After looking into the tutorials and demo I am much interested with the Angular JS as it is easily understood and got a good learning tutorials, help and support on the web. This is a small step towards learning Angular JS as well as integrating it with the SharePoint. (As SharePoint is my bread and butter 🙂 )

OK. Its time to begin the show now. (I’m so much excited about this stuff)

Goal: Show all the list items from a custom list on a SharePoint Page

I used REST API to talk to SharePoint and get the data from the list. I am not going to discuss much about the REST services as many folks has already done a great work on explaining about REST API service

I developed all these stuff using SharePoint Designer.

Upload the required files to the Style Library or any location where you want to store your script files. OR you can use the direct CDNs in your references

Build a view for displaying the data. Here is a sample for the Employee list

14_1

Build a controller file and reference it in the page

14_2

Once everything is set in place this will pull the data from the SharePoint list and show it in the template given in the view. I used a table as a template to show data.

Final result.

14_3

I am going to do more research with this new framework and will post you updates. Stay tuned and Happy Coding…!!!

Quick Tip: Get today’s date in SharePoint Designer Workflow


Sending emails whenever a SharePoint list item is created or modified is one of the regular requirement. The best scenario is to send approval notifications or status updates of the list items to different people as on when they are updated or created. I use SharePoint designer Workflows a lot for these kind of requirements. (however SPD workflows can really solve really complex problems)

Here is the scenario: Send an approval notice with today’s date in the email body. There is no direct or pre built component available to get the current date value in SharePoint designer workflows

  1. Create a Workflow variable with Date as the type.

1

  1. Set the Workflow variable before using it. When you try to set the variable SPD will provide you an option with setting its default value.

2

  1. Use the variable in the Email body

3

Happy Coding..!!!

[Issues] COPY & PASTE in SharePoint Designer


Few tips working with the SharePoint Designer:

I was recently working on a SharePoint Designer workflow. I had to create a workflow which has few similar steps from an existing workflow. Copy pasted all the actions that are required from the existing workflow. When checked for errors or warnings from the designer then everything is fine. Also, am able to save the workflow. But when we try to publish the workflow it ends up in an error something like this

(0, 0) Activity 'ID245' validation failed: Cannot resolve Activity 'ID232'.)
(0, 0) Activity 'ID355' validation failed: Cannot resolve Activity 'ID340'.)

Doing some research found out that COPY and PASTE in SPD workflows are selective. Actions like Update and Log are able to copy and paste but other logical conditions like IF, IF – ELSE doesn’t work when copied. Also, Copy and paste between workflows doesn’t always work and also sometimes crashes the SharePoint Designer.

Be careful while working with the SharePoint Designer 2013. Happy Coding…!!!

Get the control on page load on post back


I was in need of a function which gets the control name that has triggered a post back call on the page. Find below the code for getting it. I actually found this here:

Source: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx


private string getPostBackControlName()
{
            Control control = null;
            //first we will check the "__EVENTTARGET" because if post back made by       the controls
            //which used "_doPostBack" function also available in Request.Form collection.
            string ctrlname = Page.Request.Params["__EVENTTARGET"];
            if (ctrlname != null && ctrlname != String.Empty)
            {
                control = Page.FindControl(ctrlname);
            }
            // if __EVENTTARGET is null, the control is a button type and we need to
            // iterate over the form collection to find it
            else
            {
                string ctrlStr = String.Empty;
                Control c = null;
                foreach (string ctl in Page.Request.Form)
                {
                    //handle ImageButton they having an additional "quasi-property" in their Id which identifies
                    //mouse x and y coordinates
                    if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                    {
                        ctrlStr = ctl.Substring(0, ctl.Length - 2);
                        c = Page.FindControl(ctrlStr);
                    }
                    else
                    {
                        c = Page.FindControl(ctl);
                    }
                    if (c is System.Web.UI.WebControls.Button ||
                             c is System.Web.UI.WebControls.ImageButton)
                    {
                        control = c;
                        break;
                    }
                }
            }
            return control.ID;

        }

Happy Coding!!! 🙂

People picker dialogue window using JavaScript

Tags

, ,


Here is a alternative solution for getting the user details using people picker dialogue window without accessing the People Picker control. I got a scenario where in I need people picker control in Sandboxed Solution. It is a limitation that we cannot use SharePoint controls in sandboxed web parts. So I tried to get the people picker dialogue window using JavaScript. Find below the procedure

My solution will pick the user names from the dialogue window and will paste it into a text box

JavaScript: (used jQuery to talk to controls)

function PeoplePicker() {
var searchString = '';
var dialogOptions = 'resizable:yes; status:no; scroll:no; help:no; center:yes; dialogWidth :575px; dialogHeight :500px;';
var dialogURL = '/_layouts/picker.aspx';
dialogURL += '?MultiSelect=False';
dialogURL += '&CustomProperty=User,SecGroup,SPGroup;;15;;;False';
dialogURL += '&EntitySeparator=;';
dialogURL += '&DialogTitle=Select People and Groups';
dialogURL += '&DialogImage=/_layouts/images/ppeople.gif';
dialogURL += '&PickerDialogType=Microsoft.SharePoint.WebControls.PeoplePickerDialog, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c';
dialogURL += '&DefaultSearch=' + escapeProperly(searchString);

commonShowModalDialog(dialogURL, dialogOptions, DelegatePeoplePickerCallback);
}

function DelegatePeoplePickerCallback(searchResult) {

var xmlDoc = $.parseXML(searchResult);
var $xml = $(xmlDoc);
var fqn = $xml.find('Entity').attr('DisplayText');

if ($("txtPeoplePicker").val() != null) {
if ($("txtPeoplePicker").val() != '') {
var contactPerson = $("txtPeoplePicker").val();
$("txtPeoplePicker").val(contactPerson + "; " + fqn);
}
else {
$("txtPeoplePicker").val(fqn);
}
$("txtPeoplePicker").focus();
}

return;
}

Declare a text box and a button for calling the PeoplePicker() function.

On click of the button “Get People” then a dialogue window will be displayed. User can search user details accross the user Profiles and get the names. After adding the user, name of the user will be pasted to the text box.

Happy Coding 🙂

Get SP list items in a Data Table including attachments


To show SharePoint list items in a grid or any repeater control then you would have got the data into a DataTable object. Recently I observed that SharePoint object model has a method to get all the list items into a DataTable i.e.

    DataTable tempTbl = spList.GetItems(query).GetDataTable();

but unfortunately the above data table will not have the attachments information. Here is a workaround for getting even the attachment information into the data table.

Get all the data into the data table using the above code and then add a new column to store the attachment information. Also bind a hidden field of the repeater to the ID value of the data table.

    DataTable tempTbl = spList.GetItems(query).GetDataTable();
    tempTbl.Columns.Add("AttachmentsInfo");
    grdCDDocInfo.DataSource = tempTbl;
    grdCDDocInfo.DataBind();

In row data bound of the control update the new attachment information column. Find the code below to get attachments information.

    void grdCDDocInfo_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
          if (!String.IsNullOrEmpty(hdnCompanyID.Value))
          {
              SPList spList = oWeb.Lists.TryGetList("List Name");
              SPListItem item = spList.GetItemById(Convert.ToInt32((e.Row.FindControl("itemID") as HiddenField).Value));

              string attachmentInfo = String.Empty;
              foreach (string filename in item.Attachments)
              {
                  attachmentInfo += item.Attachments.UrlPrefix + filename + " " + filename
                  (e.Row.FindControl("ltAttachmentsInfo") as Literal).Text = attachmentInfo;
              }
          }
       }
   }

This will display all the list items in a grid with the attachments of the items.

Happy Coding 🙂