The below JavaScript will change $http default headers to be JSON ready for SharePoint REST APIs. This is handy when sending GET/POST to SharePoint 2013 so we don’t need to repeat headers on each individual call. Enjoy!
//namespace
var namespace = namespace || {};
//NG-controller
namespace.myCtl = function ($scope, $mySvc) {
//viewmodel
var vm = $scope;
};
//NG-service
namespace.mySvc = function ($q, $http) {
$http.defaults.headers.common['Accept'] = 'application/json;odata=verbose';
//User Profile - me
this.getMe = function () {
return $http.get('/_api/SP.UserProfiles.PeopleManager/GetMyProperties');
};
//User Profile - users
this.getUser = function (login) {
var url = '/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=\'domain\\' + login + '\'';
return $http.get(url);
};
};
//NG-module
angular.module('myApp', [])
.controller('myCtl', namespace.myCtl)
.service('$mySvc', namespace.mySvc)
.run(function () {
//prepare GUI
});
With SharePoint 2013 and industry movement towards the cloud I’ve been exploring JavaScript as a primary way to develop rich applications.
One common challenge is data access.
With C# I have years of experience with [System.Data] and can perform CRUD against SQL relational databases in my sleep. Open connection, query, data adapter, fill DataTable, and voila! Muscle memory. Second nature. Tried and true methods. However, in the new client side JS world I had no clue where to begin.
People describe Breeze as “Entity Framework on the client in JavaScript” which sounds simple yet has profound implication for the developer. CRUD operations, LINQ style query, navigating primary/foreign keys, input validation, caching, batch updates, and more. That’s a lot to consider and new ideas take time to absorb. Breeze could potentially replace:
ASP.Net (ASPX) web forms
ASCX user controls
InfoPath forms
SharePoint web parts
WCF 5.6 data services
OData
Classic WebAPI
I set out to code an example with a few goals:
Create simple SQL schema (two tables – parent/child – one to many)
Execute CRUD operations in JS against SQL tables
Leverage JS plugins and NuGet “Install-Package” to load third party components
Install-Package breeze.webapi2.ef6
Install-Package breeze.angular
Install-Package angularjs.core
Little code as possible
The whole thing took less than 30 minutes and I edited video down to just 15. I was impressed by how straightforward and easy the process was. Breeze# in ASP.Net MVC for the back end WebAPI controller was nearly identical to the Breeze example code. Add one C# method per entity (SQL table) and Breeze does the rest. The JS front end took a little more time to understand but was also easy to apply. Connect Entity Manager to the Breeze URL and you’re ready for CRUD queries. Amazing! Given how easy Breeze is I would be hard pressed to use OData or manually created WebAPI controllers with C# code to query a database. If you can use Breeze, then use it! You’ll save lots of effort.
Please leave a comment if you found this helpful. Thank you!
I’ve been learning about OData and wanted to record a quick getting started video with how to create a new WebAPI project, add OData Controller, and send HTTP CRUD operations. Below is an example using Adventure Works Departments with sample code, screenshots, and a 10 minute video introduction. Please leave a comment if you found this helpful. Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.OData.Builder;
namespace MvcApplication1
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
ODataConventionModelBuilder build = new ODataConventionModelBuilder();
build.EntitySet("Departments");
config.Routes.MapODataRoute("odata", "odata", build.GetEdmModel());
config.EnableQuerySupport(new QueryableAttribute());
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}
}
}
[DepartmentsController.cs]
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.OData;
namespace MvcApplication1.Controllers
{
public class DepartmentsController : ODataController
{
private AdventureWorks2012Entities db = new AdventureWorks2012Entities();
// GET api/Default1
public IEnumerable GetDepartments()
{
return db.Departments.AsEnumerable();
}
// GET api/Default1/5
public Department GetDepartment(short key)
{
Department department = db.Departments.Find(key);
if (department == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return department;
}
// PUT api/Default1/5
public HttpResponseMessage PutDepartment(short key, Department department)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
if (key != department.DepartmentID)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
db.Entry(department).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
// POST api/Default1
public HttpResponseMessage PostDepartment(Department department)
{
if (ModelState.IsValid)
{
db.Departments.Add(department);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, department);
response.Headers.Location = new Uri(Url.Link("odata", new { key = department.DepartmentID }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
// DELETE api/Default1/5
public HttpResponseMessage DeleteDepartment(short key)
{
Department department = db.Departments.Find(key);
if (department == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Departments.Remove(department);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK, department);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
Microsoft announced InfoPath will go away in 2023. It makes sense and they have good reasons. However, form developers are confused about available options. I have an idea for the InfoPath Roadmap and would appreciate your feedback in the comments below or Twitter (@spjeff) please.
Why not use JavaScript to create similar XML documents?
When people say “InfoPath” they generally are referring to a three part system outlined below. InfoPath strictly speaking is the form input experience. Form Library holds the saved XML output. SharePoint Designer can then trigger email notifications based on status change.
InfoPath as a form input experience has many limitations based on the server postback and Dot Net architecture. Just try a large repeating table and watch the slow “Loading…” experience as users click and rules postback to the SharePoint IFS backend. HTML5 and JavaScript offer new options for client side validation, async loading, mobile touch input, responsive layout, and advanced rendering with framworks like JQueryUI / Bootstrap / Angular. That’s awesome form input technology! However, InfoPath is normally chosen for ease of use and “no code”. Let’s think about how that conversation might go …
Developer Conversation
DEV1 > “Hey did you hear Microsoft is retiring InfoPath in 2023?”
DEV2 > “Yeah, but it’s all we have today so I’ll keep using it. Not sure what else to use. Sure would be nice to have HTML5 and cooler input experience.”
DEV1 > “Definitely. Coding from scratch is a lot of work. I don’t really want to mess around with SPList REST connections for CRUD or make a SQL database with SVC/OData for simple forms. My head hurts.”
DEV2> “True, but I guess we’ll gave to make a schema first then form later.”
DEV1 > “InfoPath saved as XML. I like XML. It works well for import/export across all of our systems. Could we keep XML but ditch InfoPath?”
DEV2 > “Cool idea, but I’m not sure how.”
Why throw out the baby with the bathwater?
Can’t we make fantastic forms with HTML5/JS and then save back to a Form Library in order to leverage SharePoint for storage, views, and workflow? Right now this is just an idea. I don’t yet have a working prototype to show but think it would be straightforward to convert JSON to XML and upload. InfoPath would still be used but by developers for schema only (define XML structure). End users would never see it.
Please leave a comment below and let me know if you think this might be practical. Thanks!