Products

Solutions

Resources

Partners

Community

About

New Community Website

Ordinarily, you'd be at the right spot, but we've recently launched a brand new community website... For the community, by the community.

Yay... Take Me to the Community!

The Community Blog is a personal opinion of community members and by no means the official standpoint of DNN Corp or DNN Platform. This is a place to express personal thoughts about DNNPlatform, the community and its ecosystem. Do you have useful information that you would like to share with the DNN Community in a featured article or blog? If so, please contact .

The use of the Community Blog is covered by our Community Blog Guidelines - please read before commenting or posting.


Simple RESTful JSON web services with DotNetNuke

In case you missed it, there is a Hackathon that is going on right now (the submission deadline is tomorrow so you still have time to throw a quick mobile project together).

As part of the Hackathon event in St. Louis last week I gave a brief presentation on how to quickly and easily add a RESTful JSON webservice to your modules, or even create a simple module to do this yourself. I have the source code for this presentation on Codeplex under the dnnweb project, http://dnnweb.codeplex.com/

The idea behind this is that in order to create a mobile app that does something with DNN you likely need to expose some data, and why not do it in a very quick and easy way, with RESTFul implementations and JSON data that works very well with javascript. For an example project you should check out the DNN Pulse application that Joe blogged about earlier.

The code is in C#, but is really simple, you should be able to get it into a VB project fairly easily. In this post I’m going to talk about the code and what is going on.

One word of warning, this project that you can download an install is not using any type of authentication right now, you can add it to a site, and it someone calls svc/users they will get a list of all your users, it is just provided for sample purposes right now.

The first thing is a quick modification to your web.config file, if you’re using IIS7 you can easily setup an HTTPHandler that will allow your web service to respond to incoming requests, such as

http://PORTALALIAS/svc/users
http://PORTALALIAS/svc/roles
http://PORTALALIAS/svc/user/USERNAME

With DNN5 this becomes very easy to do in your module’s manifest file. With the project linked above I have already made this change for you, here’s the sample code for that configuration

   1:          <component type="Config">
   2:            <config>
   3:              <configFile>web.config</configFile>
   4:              <install>
   5:                <configuration>
   6:                  <nodes>
   7:                    <node path="/configuration/system.web/httpHandlers" action="update" key="path" collision="overwrite">
   8:                      <add verb="GET" path="svc/*" type="com.christoc.dnn.dnnwebservices.Services.GetHandler, dnnwebservices" />
   9:                    </node>
  10:                    <node path="/configuration/system.webServer/handlers" action="update" key="name" collision="overwrite">
  11:                      <add name="DnnWebServicesGetHandler" verb="GET" path="svc/*" type="com.christoc.dnn.dnnwebservices.Services.GetHandler, dnnwebservices" preCondition="integratedMode" />
  12:                    </node>
  13:                  </nodes>
  14:                </configuration>
  15:              </install>
  16:              <uninstall>
  17:                <configuration>
  18:                  <nodes />
  19:                </configuration>
  20:              </uninstall>
  21:            </config>
  22:          </component>

 

The next thing you need to do is to setup the HTTPHandler itself, in the example code I setup the Get Handler which exists in Services/GetHandler.cs, you basically need to implement IHttpHandler on the class

   1:  public class GetHandler : IHttpHandler
   2:      {
   3:          #region IHttpHandler Members
   4:   
   5:          public bool IsReusable
   6:          {
   7:              get { return false; }
   8:          }
   9:   
  10:          public void ProcessRequest(HttpContext context)
  11:          {

 

In order to do the JSON side of things, which stands for JavaScript Object Notation, I pulled in an opensource library from codeplex, http://json.codeplex.com/ 

In the processing for the handler I setup some method calls, one for getting all users, get a specific user, and one for get all roles for a portal. These are pretty simple, here they are in the ProcessRequest implementation

   1:   
   2:          public void ProcessRequest(HttpContext context)
   3:          {
   4:              HttpResponse response = context.Response;
   5:              var written = false;
   6:   
   7:              //because we're coming into a URL that isn't being handled by DNN we need to figure out the PortalId
   8:              SetPortalId(context.Request);
   9:   
  10:              //get all roles for a portal
  11:              if(context.Request.Url.AbsolutePath.IndexOf("roles")>0 && written == false)
  12:              {
  13:                  response.Write(GetRolesJson(PortalId));
  14:                  written = true;
  15:              }
  16:   
  17:              //get back a listing of 
  18:              if (context.Request.Url.AbsolutePath.IndexOf("users") > 0 && written == false)
  19:              {
  20:                  response.Write(GetUsersJson(PortalId));
  21:                  written = true;
  22:              }
  23:   
  24:              //get back a single user
  25:              if (context.Request.Url.AbsolutePath.IndexOf("user") > 0 && written == false)
  26:              {
  27:                  //get the username to lookup 
  28:                  response.Write(GetUserJson(PortalId, context.Request));
  29:                  written = true;
  30:              }
  31:             
  32:          }

And the implementation of one of those calls, which goes through the DNN API

   1:          ///<summary>
   2:          /// Return all users for a portal in formatted json string
   3:          /// </summary>
   4:          /// <param name="portalId">portalid</param>
   5:          private static string GetUsersJson(int portalId)
   6:          {
   7:              //get a list of all roles and return it in json
   8:              var uc = new UserController();
   9:              var users = UserController.GetUsers(portalId);
  10:              var usersOutput = string.Empty;
  11:              foreach (var t in users)
  12:              {
  13:                  var output = JsonConvert.SerializeObject(t, Formatting.Indented);
  14:                  usersOutput += output;
  15:                  
  16:              }
  17:              return usersOutput;
  18:          }

 

And one last thing, in order to make the various calls, you also need to know how to get your PortalId based on the incoming URL.

   1:          ///<summary>
   2:          /// Set the portalid, taking the current request and locating which portal is being called based on this request.
   3:          /// </summary>
   4:          /// <param name="request">request</param>
   5:          private void SetPortalId(HttpRequest request)
   6:          {
   7:   
   8:              string domainName = DotNetNuke.Common.Globals.GetDomainName(request, true);
   9:   
  10:              string portalAlias = domainName.Substring(0,domainName.IndexOf("/svc"));
  11:              PortalAliasInfo pai = PortalSettings.GetPortalAliasInfo(portalAlias);
  12:              if (pai != null)
  13:                  PortalId = pai.PortalID;            
  14:          }
  15:   
  16:          public static int PortalId { get; set; }

 

The rest of the module project right now doesn’t do anything, eventually I will add authentication and some display functionality to the services and the module, but for now it’s just something quickly put out there. Download it, tear it apart, and start working on your own web services.

A reminder about the Hackathon, you don’t have to submit a fully flushed out 100% complete program for the contest, the idea is to do something quick and easy, and also innovative.

So get going, the Hackathon is in full swing!

Comments

There are currently no comments, be the first to post one.

Comment Form

Only registered users may post comments.

NewsArchives


Aderson Oliveira (22)
Alec Whittington (11)
Alessandra Daniels (3)
Alex Shirley (10)
Andrew Hoefling (3)
Andrew Nurse (30)
Andy Tryba (1)
Anthony Glenwright (5)
Antonio Chagoury (28)
Ash Prasad (37)
Ben Schmidt (1)
Benjamin Hermann (25)
Benoit Sarton (9)
Beth Firebaugh (12)
Bill Walker (36)
Bob Kruger (5)
Bogdan Litescu (1)
Brian Dukes (2)
Brice Snow (1)
Bruce Chapman (20)
Bryan Andrews (1)
cathal connolly (55)
Charles Nurse (163)
Chris Hammond (213)
Chris Paterra (55)
Clint Patterson (108)
Cuong Dang (21)
Daniel Bartholomew (2)
Daniel Mettler (181)
Daniel Valadas (48)
Dave Buckner (2)
David Poindexter (12)
David Rodriguez (3)
Dennis Shiao (1)
Doug Howell (11)
Erik van Ballegoij (30)
Ernst Peter Tamminga (80)
Francisco Perez Andres (17)
Geoff Barlow (12)
George Alatrash (12)
Gifford Watkins (3)
Gilles Le Pigocher (3)
Ian Robinson (7)
Israel Martinez (17)
Jan Blomquist (2)
Jan Jonas (3)
Jaspreet Bhatia (1)
Jenni Merrifield (6)
Joe Brinkman (274)
John Mitchell (1)
Jon Henning (14)
Jonathan Sheely (4)
Jordan Coopersmith (1)
Joseph Craig (2)
Kan Ma (1)
Keivan Beigi (3)
Kelly Ford (4)
Ken Grierson (10)
Kevin Schreiner (6)
Leigh Pointer (31)
Lorraine Young (60)
Malik Khan (1)
Matt Rutledge (2)
Matthias Schlomann (16)
Mauricio Márquez (5)
Michael Doxsey (7)
Michael Tobisch (3)
Michael Washington (202)
Miguel Gatmaytan (3)
Mike Horton (19)
Mitchel Sellers (40)
Nathan Rover (3)
Navin V Nagiah (14)
Néstor Sánchez (31)
Nik Kalyani (14)
Oliver Hine (1)
Patricio F. Salinas (1)
Patrick Ryan (1)
Peter Donker (54)
Philip Beadle (135)
Philipp Becker (4)
Richard Dumas (22)
Robert J Collins (5)
Roger Selwyn (8)
Ruben Lopez (1)
Ryan Martinez (1)
Sacha Trauwaen (1)
Salar Golestanian (4)
Sanjay Mehrotra (9)
Scott McCulloch (1)
Scott Schlesier (11)
Scott Wilkinson (3)
Scott Willhite (97)
Sebastian Leupold (80)
Shaun Walker (237)
Shawn Mehaffie (17)
Stefan Cullmann (12)
Stefan Kamphuis (12)
Steve Fabian (31)
Steven Fisher (1)
Tony Henrich (3)
Torsten Weggen (3)
Tycho de Waard (4)
Vicenç Masanas (27)
Vincent Nguyen (3)
Vitaly Kozadayev (6)
Will Morgenweck (40)
Will Strohl (180)
William Severance (5)
What is Liquid Content?
Find Out
What is Liquid Content?
Find Out
What is Liquid Content?
Find Out