Introduction

 

People often ask me if I use MVC or WebForms for my Microsoft ASP.NET projects.  I always tell them MVC, but I don’t use it in the classic way that most others do.  That is to say, I emit no html from my views, and for that matter really don’t even use views (with the exception of one view which is essentially my entire app.   People often refer to this as a SPA or Single-Page-Application. What this basically means is that my entire view is built with JavaScript (in my case Sencha’s ExtJS) and the only interaction with the server is to simply bring down Json results.

In this post, I’m going to build a simple app following this principle. It’s purpose will be to take a big pile of text, chop it up into words, then output it in some c# friendly manner.  My motivation for doing this is I happen to need that functionality right now and instead of creating a little awk script to do it, I’m going to right a web site!

 

So, Here is what we will build.  A handy formatter! (and you can run it at:   http://reformatter.peterkellner.net/ )

 

image

image

 

 

Part I, The Visual Studio Project

 

Let’s first create the Visual Studio project.  My development these days is actually using the latest Windows 8 Consumer build with the beta of Visual Studio 2011 running on it.  The nice thing about this is because Microsoft added “Round Tripping” to VS2011, I can now use VS2011 to create the project and you, my happy readers, can download the project and open it in Visual Studio 2010.  This has been long in coming and Microsoft has finally done it for the newest version of Visual Studio.  Thank you Microsoft!

 

image

 

And with an Internet Application with Razor (though I really don’t need all that extra stuff, it does not hurt)

 

image

 

The structure created is as as shown below with a Controller and Views folder and all the proper routing setup.

 

image

 

Because I want to make a very simple MVC app that only emits Json, Let’s create our own empty controller called ReformatterController.  We do that by right clicking on the Controller folder and pressing “Add Controller”, then “Add Empty Controller”.

image

 

Now, let’s create a very very simple controller with just one method that returns a JSON Result.  I’m returning the data in a friendly format to  Sencha’s ExtJS (or SenchaTouch for that matter).  JQuery would be similar.  Here is our new controller class (I’m sure my little tokenizer, line maker could be improved, but I’m just doing this to show some real work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MvcLiteApp.Controllers
{
    public class ReformatterController : Controller
    {

        public JsonResult ConvertTextToFriendlyText(string inputText)
        {
            const int maxCharactersInLine = 30;
            bool success;
            string messageReturn;
            var outputDataList = new List<string>();

            try
            {
                var words = inputText.Split(' ').ToList();
                var newLine = new StringBuilder();
                foreach (var word in words)
                {
                    if (newLine.Length + word.Length < maxCharactersInLine &&
                        word.Length < maxCharactersInLine)
                    {
                        newLine.Append(" ");
                        newLine.Append(word);
                    }
                    else
                    {
                        outputDataList.Add(newLine.ToString().Trim());
                        newLine = new StringBuilder();
                        newLine.Append(word);
                    }
                }
                success = true;
                messageReturn = "";
            }
            catch (Exception e)
            {
                messageReturn = e.ToString();
                success = false;
            }

            return Json(new
            {
                Success = success,
                Data = outputDataList,
                message = messageReturn
            }, JsonRequestBehavior.AllowGet);
        }

    }
}

Now, let’s feed it a URL and see what happens.  Here is a sample URL:

http://localhost:3600/Reformatter/ConvertTextToFriendlyText?inputText=Romeo%20Montague%20and%20Juliet%20Capulet%20meet%20and%20fall%20in%20love%20in%20Shakespeare’s%20lyrical%20tale%20of%20%22star-cross’d%22%20lovers.

I actually pasted the sentence in to the the browser’s URL line and it added the nice encoded spaces for me.  The output is as follows:

{"Success":true,"Data":["Romeo Montague and Juliet","Capulet meet and fall in love","in Shakespeare\u0027s lyrical tale"],"message":""}

Notice that it created the nice lines formatted as a JavaScript array!

Next step, let’s make a real JavaScript program out of this.

 

Part 2, Our SPA (Single Page App) That Does Real Work

 

I’m only going to explain here the part of the Sencha Program that actually consumes the data but first, let’s add a little “properness” to our controller so it responds only to POST.  That is, we add an attribute to the top of the method and we change the behavior attribute on the bottom to say to not allow get.

        [HttpPost]
        public JsonResult ConvertTextToFriendlyText(string inputText)
        {
            .......
            return Json(new
            {
                Success = success,
                Data = outputDataList,
                message = messageReturn
            }, JsonRequestBehavior.DenyGet);
        }

And, the JavaScript in the SPA is very straight forward and is here:

var beforeTextAreaComponent = Ext.getCmp('BeforeFormatTextAreaId');
textBefore = beforeTextAreaComponent.getValue();

// how to not pollute global name space here?
var stringbuildervalue = Ext.getCmp('stringbuilderid').getValue();
var javascriptarrayvalue = Ext.getCmp('javascriptarrayid').getValue();
var noformattingvalue = Ext.getCmp('noformattingid').getValue();
var outputwidthvalue = Ext.getCmp('outputwidthid').getValue();

Ext.Ajax.request({
    url: 'ReFormatter/ConvertTextToFriendlyText',
    params: {
        inputText: textBefore,
        stringbuilder: stringbuildervalue,
        javascriptarray: javascriptarrayvalue,
        noformatting: noformattingvalue,
        outputwidth: outputwidthvalue
    },
    success: function(response){
        var localData = Ext.JSON.decode(response.responseText).Data;
        var numberRows = localData.length;
        var newData = '';
        for (var i=0;i<numberRows;i++) {
            newData += localData[i] + '\n';
        }

        var afterTextAreaComponent = Ext.getCmp('AfterFormatTextAreaId');
        afterTextAreaComponent.setValue(newData);

    },
    failure: function(error) {
        alert('error');
    }

});

Now, in reality, I’ve added some useful stuff to the controller (and put the project here for your review, comments and suggestions).

Visual Studio Project TextReformatter.zip

Introduction

The goal is to create a simple Service in Windows 7 (or other similar OS’s) with Visual Studio 2010 that simply starts, sleeps for 15 seconds, then stops.  I realize this is not that useful, but basically, it covers the case of building a service that actually does something and when finished stops.  In my personal case, my thread has a while(true) loop which keeps looking for new work and only completes when certain conditions are met (like a fatal error that is non recoverable).

Microsoft has given us a pretty good set of docs and walk through.  You can find them all here:  http://msdn.microsoft.com/en-us/library/y817hyb6.aspx

 

The Steps

Create a new Visual Studio Project of type “Windows Service”

 

image

Once the project is created, make sure you have the design surface up for Service1 [Design] and right click on it and say “Add Installer”.

image

Now, you’ll get to “gear” icons that you can set properties for.  They are “serviceProcessInstaller1” and “serviceInstaller1” as follows:

image

Select “serviceProcessInstaller1” and in it’s properties window change the account to “LocalSystem”.  You should have a screen that looks like the following:

image

Then, on the other gear “serviceInstaller”, change the nanes as follows.  I’m naming my service “MyDoNothingService”.

image

Now, rebuild your project and you’ll get an exe file in your /bin/Debug folder.  Open that folder with the Visual Studio Command Prompt (elevated as admin).  To install the service, enter the command:

InstallUtil WindowsServiceCreateSample.exe

 

image

You should get some messages that end with “The Commit phase completed successfully”, then “The Transaction install has completed”.

Now, you should see that you have the service in your services panel (you can get there by going to control panel / Administrative / Services or simple run “services” from your start button.

image

(sorry for the rename here to MyServiceTest, but I got distracted and had to come back and rename the project)

So, now we want to add something to this project.  Let’s just add to the OnStart event of Service1.cs something that starts a thread that sleeps for 15 seconds, then stops the thread.  Very simple code as follows:

  protected override void OnStart(string[] args)
        {
            new Thread(()
                      =>
            {
                Thread.Sleep(15000); // sleep 15 seconds
                this.Stop();
            }).Start();
        }

Now, before we can install the service, we first need to uninstall it.  Very easy, just add a /u to the end of your install command.

InstallUtil WindowsServiceCreateSample.exe /u

You should be greeted with “The uninstall has completed.”.

Now, when you try and reinstall, sadly, you might get this error: “Error 1001. The specified service has been marked for deletion”.  If you do, thanks to a post by Mr. Laxdel, all you have to do is exit your services dialog and restart the service.

Assuming you left the default autoLog set to true as follows:

image

In your event viewer, you should see you service starting and stopping as follows:

image

 

 

Conclusions

That was pretty straight forward.  Hopefully, you can follow along and generate the same thing yourself.  Here is the source code attached for a visual studio 2010 project if for some reason you have trouble recreating it yourself.  HTH’s!

Visual Studio 2010 Project Project


© 2012 PeterKellner.net. All Rights Reserved
Follow

Get every new post delivered to your Inbox

Join other followers: