jump to navigation

Javascript For Creating Client Requests in ASP.NET April 5, 2012

Posted by jinzaistudio in ASP.NET 3.5, Javascript, jinzai-studio.net, Michael T. Blake, programming.
add a comment

Here is the client side Javascript that runs in the client’s browser. ASP.NET stands for Active Server Pages, which are naturally server side entities. Most of the interactive part of a web page starts with the user doing something in their browser….that is, on the client side. As I have stated before, the interaction creates an action back to the server and a response to the client. In order to avoid too much of that, there is an ability on the client side to handle some things within the browser. Since this is not a consistent paradigm, a platform independent way to code is necessary. Javascript to the rescue. The interaction between Javascript running on the client and .NET code running on the server presents many challenges to the programmer, not the least of which is security. Its a fairly large hole in the system which is in constant need of plugging up. Here is some basic Javascript code for creating a BOSH session request, which is the first step of many in this project. I will not bore you with it much longer here…it will be available to use and examine on the website once I get the core functionality working to my satisfaction.

I should note that the code to instantiate the clientRequest was found using a Google search. I was willing to just support the current XMLHttpRequest in IE8 and above, but I do like backward compatibility.

    
        var clientRequest;

        function readyStateChangeHandler() {
            if (clientRequest.readyState == 4) {
                if (clientRequest.status == 200) {
//                    alert(clientRequest.responseText);
                    document.getElementById("divResponse").innerHTML += 
clientRequest.responseText;
                }
            }
        }

        function StartSession() {
            clientRequest = new ajaxRequest();
            if (clientRequest != null) {
                var fromText = document.getElementById("idFrom").value;
                var holdText = document.getElementById("idHold").value;
                var ridText = document.getElementById("idRid").value;
                var toText = document.getElementById("idTo").value;
                var routeText = document.getElementById("idRoute").value;
                var verText = document.getElementById("idVer").value;
                var waitText = document.getElementById("idWait").value;

                if (fromText.length > 0 &&
                    holdText.length > 0 &&
                    ridText.length > 0 &&
                    toText.length > 0 &&
                    routeText.length > 0 &&
                    verText.length > 0 &&
                    waitText.length > 0) {
                    
                    var theSessionrequest = "";
                    alert(theSessionrequest);
                    clientRequest.open("POST", 
"http://localhost:4491/jinzai-studio.net/ChatterBox.aspx", 
true);
                    clientRequest.setRequestHeader("Content-Type",
 "text/xml; 
 charset=utf-8")
                    clientRequest.onreadystatechange = readyStateChangeHandler;
                    //                    clientRequest.send("");
                    clientRequest.send(theSessionrequest);
                }
            }
        }

        function ajaxRequest() {
            var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];

            if (window.ActiveXObject) {
                for (var i = 0; i < activexmodes.length; i++) {
                    try {
                        return new ActiveXObject(activexmodes[i]);
                    }
                    catch (e) {
                        //suppress error
                    }
                }
            }
            else if (window.XMLHttpRequest) {
                return new XMLHttpRequest();
            }
            else {
                return false;
            }
        }

        function SetHiddenFieldValue(theField, theValue) {
            document.getElementById(theField).value = theValue;
        }

        function Send(theText) {
            alert(theText);
        }
    

VB.NET Code Behind For XMPP Project April 5, 2012

Posted by jinzaistudio in ASP.NET 3.5, jinzai-studio.net, Michael T. Blake, programming, Uncategorized, Visual Basic.
add a comment

This blog post will show the VisualBasic code behind that I use to pass information to the client side Javascript that produces the client’s requests. ASPX itself is a server side paradigm and script is the client’s way of passing information back to the server. The mechanism for this is a postback, which involves a roundtrip and the usual response to that is a complete reload of the page and loss of information. The mechanism that is ordinarily used to persist information is either one of the server side entities, such as the Session object or Viewstate, or the HTML mechanism known as hidden fields. All of these accompany the page itself and are available to different extents to the programmer. The method I chose was hidden fields and the server fills the fields by calling client side Javascript to pass variables to the code that are used to piece together the client’s request. It is not an elegant solution, but I have created a nice implementation of it, at least. (Or so I tell myself…..) Here is the page’s code behind:

Imports System.Xml
Imports System.IO

Partial Class ChatterBox
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) Handles Me.Load
        If Not (Page.IsPostBack) Then
            SetHiddenFieldValue("idFrom", "mtb@jinzai-studio.net")
            SetHiddenFieldValue("idHold", "1")
            SetHiddenFieldValue("idRid", "1573741820")
            SetHiddenFieldValue("idRoute", "xmpp:jinzai-studio.net:9999")
            SetHiddenFieldValue("idTo", "jinzai@jinzai-studio.net")
            SetHiddenFieldValue("idVer", "1.6")
            SetHiddenFieldValue("idWait", "60")
        End If
    End Sub

    Protected Sub btnSend_Click(ByVal sender As Object, _
                                ByVal e As System.EventArgs) _
                                Handles btnSend.Click
        Dim theScriptBuilder As New StringBuilder

        theScriptBuilder.Append("Send('")
        theScriptBuilder.Append(TextBox1.Text)
        theScriptBuilder.Append("');")

        ClientScript.RegisterStartupScript(Me.GetType(), _
                                           Guid.NewGuid().ToString(), _
                                           theScriptBuilder.ToString, _
                                           True)
    End Sub


    Private Sub SetHiddenFieldValue(ByVal theField As String, _
                                    ByVal theValue As String)
        Dim theScriptBuilder As New StringBuilder

        theScriptBuilder.Append("SetHiddenFieldValue('")
        theScriptBuilder.Append(theField)
        theScriptBuilder.Append("', '")
        theScriptBuilder.Append(theValue)
        theScriptBuilder.Append("');")

        ClientScript.RegisterStartupScript(Me.GetType(), _
                                           Guid.NewGuid().ToString(), _
                                           theScriptBuilder.ToString, _
                                           True)
    End Sub
End Class

Next up is the Javascript to create the client’s requests.

Developing an XMPP Library in ASP.NET April 5, 2012

Posted by jinzaistudio in ASP.NET 3.5, jinzai-studio.net, Michael T. Blake, programming, Uncategorized, Visual Basic, Visual C#.
3 comments

The next few blog entries are an attempt to supplement my resume with a more ‘hands-on’ look at my development process. Disinterested readers can consider themselves forewarned : this is not interesting to anyone that is not interested in the process of programming.

The project that the following entries are going to document is the addition of a real-time chat service to my website. The chat service will use the eXtensible Messaging and Presence Protocol, aka XMPP. XMPP is a ‘protocol’ that is smuggled through the HyperText Transport Protocol (HTTP) using another ‘pseudo-protocol’ called Bidirectional Streams Over Synchronous HTTP, or BOSH. I do not use the term protocol because both BOSH and XMPP are really hiding within HTTP. I do not intend to discuss the differences between binary and character based data, or what constitutes a de facto protocol, or even belabor the fact that the Internet consists of many such partially specified and inconsistently implemented protocols and services. Instead, I will demonstrate how I attempt to implement my own versions of communications, services and applications using Microsoft tools and also by heavy use/abuse of Google and other Internet resources, as well as the documentation that is provided with Microsoft tools, namely Visual Studio.

The project has no real specifications that lie outside the environment that I use to develop code. The website is written in ASP.NET 3.5 and I use VisualBasic exclusively for development of the code behind. However, this project is also being driven by a job listing that I am trying to apply for and that particular company wants C#. That does not confront me at all, since both VB and C# are equally capable of producing .NET code and I cut my eye teeth using x86 assembler, C and C++. I am not afraid of C# and I use VB.NET because that is what my last employer used. They were equally reticent about me saying that I preferred C++, but quickly changed their minds.

Okay, a few last items before I show you the three part framework that is needed to develop such a project. First of all….chat, XMPP and BOSH are add-ons to any website, so there is no baseline support for non ASP.NET componentry per se in .NET Microsoft is not a closed shop, so there are plenty of places where one can take control of things. In the ASP.NET data path, the very best place to start is either the IHttpModule, or the IHttpHandler interface. Since the IHttpModule interface ‘wraps’ the IHttpHandler one without interfering with normal ASPX interactions, that is where I started. N.B. I will likely write an HttpHandler (IHttpHandler) as well, but that is not where you should begin with this type of endeavor. BOSH implementation is a rather complex interaction and there are concerns about how to maintain connection from both the server and the client side. In the case of my website, I am hosted at a server that also hosts many other sites. It would not be a good idea to try to wrestle a lot of processor cycles from other sites. I also have a personal aversion to writing code that puts too much responsibility on the client, or that is otherwise invasive to their resources, or data. Am I jabbing at certain ‘free’ social networking sites? Oh, yeah…I’m doing that very thing right now.

Javascript is the main client side tool for developers that do not want resort to using lot of postbacks to make things interactive and interesting. My website has two very nice examples of ASP.NET User Controls that are implemented entirely in Javascript that require no postbacks whatsoever to play the games that they implement. So, in this project, Javascript is used to create the client side requests. This is a very clunky interaction with ASP.NET The server and client are logically, physically and theoretically separated for security reasons, among other things. The main burden for the developer is to be able to pass information between them in such a way that is does not disturb normal ASP.NET interaction.

The first thing that I did was to create an IHttpModule project in C#, as per the requirement of the fictional client. Microsoft has an example that responds to the two events I am interested in for starting the project, BeginRequest and EndRequest. So, I started with skeleton code similar to that. Another bit of Microsoft example code that came in handy was their code to examine the content of a request.

I have left some of the initial code in there that saves the content to a local file on my computer. The very first goal I had was to be able to capture incoming requests. The module was tested after having been registered using the web.config file. At this point, I had the beginnings of an ASP.NET packet sniffer, although I never bothered with the headers, etc. because I have no interest in them. The module is only supposed to recognize what it suspects is a BOSH module at the time of this blog entry. (I have about 6-8 hours on this project, if such metrics are of interest to the reader.) Since BOSH and XMPP are smuggled in using XML and since XML is one of the most tedious and rigorous of all Internet languages, I simply use the exception mechanism and Microsoft’s XmlDocument class to determine how well formed the XML is and whether it contains a single node named ‘body’. I will do more qualification as the project develops, but I have not yet established a BOSH session, and I am currently writing both the client and the server. Soon, I will test both against other clients and servers and that will be the basis of further work on both sides. There is a more pressing need to get ‘something working’….then work on that.

Here is the code for the BoshModule, which is a DLL that I drop into the website’s bin folder:

using System;
using System.IO;
using System.Web;
using System.Xml;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace XMPP
{
    public class BoshModule : IHttpModule
    {
        private bool bRelevant = false;

        public BoshModule()
        {
            //
        }

        public String ModuleName
        {
            get { return "BoshModule"; }
        }

        public void Dispose()
        {
            //
        }

        public void Init(HttpApplication theContext)
        {
            theContext.BeginRequest +=
                new EventHandler(BoshModuleBeginRequest);
            theContext.EndRequest +=
                new EventHandler(BoshModuleEndRequest);
        }

        private void BoshModuleBeginRequest(object sender, EventArgs e)
        {
            bRelevant =
                IsBoshRequest(((HttpApplication)sender).Request.InputStream);

        }

        private void BoshModuleEndRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            string filePath = context.Request.FilePath;
            string fileExtension = VirtualPathUtility.GetExtension(filePath);

            if (fileExtension.Equals(".aspx") && bRelevant)
            {
                context.Response.Write("BoshModule: End of Request");
            }
        }

        private bool IsBoshRequest(Stream theRequestData)
        {
            bool bBoshRequest = false;

            try
            {
                XmlDocument theDocument = new XmlDocument();
                theDocument.Load(theRequestData);
                XmlNodeList theNodeList =
                    theDocument.GetElementsByTagName("body");

                // BOSH contains exactly one node that is named 'body'.

                if (theNodeList.Count == 1)
                {
                    // The number of attributes can be used to determine the
                    // nature of the request without having to traverse the
                    // child nodes. If the code has not already returned,
                    // then this module has some level of interest in this
                    // request. Now, it is time to find out what the nature
                    // of the request is.

                    int numAttributes = theNodeList[0].Attributes.Count;

                    if (numAttributes > 0)
                    {
                        bBoshRequest = true;
                    }
                }

            }

            catch (Exception e)
            {
                // The request does not contain well formed XML,
                // so it is not a BOSH packet, or it is not a well
                // formed BOSH packet. Either way, it is of no
                // interest to this module.

                string theExceptionText = e.Message;
                string theExceptionStackTrace = e.StackTrace;
            }

            //
            return bBoshRequest;
        }

        public void WriteToDiagnosticFile(string theData)
        {
            using (StreamWriter theWriter =
                   new StreamWriter(@"C:/Users/Michael/Documents/UserTemp/test.log",
                   true))
            {
                theWriter.WriteLine(DateTime.Now.ToString() + " - " + theData);
                theWriter.Close();
            }
        }

    }
}

The next blog entry will show the VB.NET code behind that is used to drive the client side.

Some Videos of My Projects March 5, 2012

Posted by jinzaistudio in jinzai-studio.net, Michael T. Blake, Parallax Propeller, personal, programming, Uncategorized.
add a comment

Binary Counter Running on a Parallax P8X32A Quickstart Board:

http://www.facebook.com/v/203853383055086

Beat Frequency Soundscape for relaxation/Meditation:

http://www.facebook.com/v/3215216420657

Powerpoint Presentation on Beat Frequencies:

http://www.facebook.com/v/3176160764290

Quick Experiment with H-Bridge Motor Control Using Parallax Propeller Microcontroller and DC Motor

PWM Experiment

NMEA Input Message 100 SetSerialPort March 5, 2012

Posted by jinzaistudio in ASP.NET 3.5, jinzai-studio.net, Michael T. Blake, Parallax Propeller, programming, rocketry, Uncategorized, Visual Basic.
add a comment

This post relates to the National Marine Electronics Association (NMEA) Standard 0183 v2.2. Specifically, it addresses Input Message 100, SetSerialPort, which is used to alter the communications rate of Global Positioning System (GPS) devices. The device used to generate this document is a SiRF PMB-688 and it is connected to a Parallax Quickstart P8X32A Development Board. These are available from Radio-Shack for $39 at the time of this writing, or from Parallax directly. The PMB-688 is likewise available from Parallax. The two links will take you to the product pages for the devices.

Changing the speed is a simple process. The PMB-688 is typical of GPS receivers in its class in that it defaults to 4800bps, 8 data bits, 1 stop bit and no parity. The speed can be changed by sending an ASCII text string with the properly formatted message, checksum and a terminating carriage return/line feed pair. The only real task is generating the checksum, which while not at all difficult, is poorly and often incorrectly documented which leads to many applications suffering from a severe underflow of GPS data. Below is a list of complete strings for accomplishing the change, followed by the VisualBasic.NET routine for calculating a checksum and adding it to the message text that was used to generate the list.

NMEA Mode:

  • $PSRF100,1,4800,8,1,0*0E
  • $PSRF100,1,9600,8,1,0*0D
  • $PSRF100,1,19200,8,1,0*38
  • $PSRF100,1,38400,8,1,0*3D
  • $PSRF100,1,57600,8,1,0*36
  • $PSRF100,1,115200,8,1,0*05

SiRF Binary Mode:

  • $PSRF100,0,4800,8,1,0*0F
  • $PSRF100,0,9600,8,1,0*0C
  • $PSRF100,0,19200,8,1,0*15
  • $PSRF100,0,19200,8,1,0*39
  • $PSRF100,0,57600,8,1,0*37
  • $PSRF100,0,115200,8,1,0*04

* The string must be followed by a terminating carriage return/line feed pair.

VisualBasic.NET listing for calculating the checksum and adding to the command string:

PublicFunction CalculateNMEAChecksum(ByVal theCommandString AsString) AsString

    Dim theList AsNew List(OfByte)

    Dim theChecksum AsByte = 0

    For x AsInteger = 0 To theCommandString.Length – 1

        If theCommandString(x) <> “*”AndAlso theCommandString(x) <> “$”Then

theList.Add(Convert.ToByte(Asc(theCommandString.Substring(x, 1))))

        EndIf

    Next

    Dim theBytes() AsByte = theList.ToArray

    For i AsInteger = 0 To theBytes.Length – 1

theChecksum = theChecksum Xor theBytes(i)

    Next

    Return theCommandString & theChecksum.ToString(“X”)

EndFunction

Welcome To My Blog March 1, 2012

Posted by jinzaistudio in Aerotech Initiator, ASP.NET 3.5, astronomy, jinzai-studio.net, Michael T. Blake, Parallax Propeller, personal, printed circuit board, programming, rocketry, Uncategorized, Visual Basic.
add a comment
jinzai studio icon

jinzai-studio.net

My name is Michael T. Blake. Welcome to my blog. Here you will find much of the same material that I have been posting to my Facebook accounts as well as material that I will post to my website. This blog is part of getting my brand out into the Internet and also, it gives me the opportunity to share things I am learning with many people. I like that very much.

The image to the left is my new jinzai-studio.net logo, in work. I have been quite busy developing the site and code for image processing and also for making printed circuit boards to further some other projects that I have going on right now. Let me tell you about some of them.      I am a software developer. I write code in Microsoft Windows, mostly. I prefer C++, but unmanaged code is becoming rare and VisualBasic is a great managed code language, so I have been using that for the last 5 years, or so. I also use DarkBasic Professional for DirectX programming and I also use Parallax Propeller microcontrollers on many of my projects.      My website, jinzai-studio.net also documents some of my work and I develop it myself using VB.NET (ASP.NET 3.5) and SQL Server 2008. I am using some old school DB access methods, but LINQ to SQL is what I use most of the time.      I also enjoy rocketry and astronomy, as well as the Earth sciences, like geology and meteorology. I just built an Aerotech Initiator which will fly in the G class. Next, I am going to shoot for my High Power Level 1 certification. I would really like to see one of my projects ‘slip the surly bonds’ and enter into space.      The first few items in this feed will relate to the rocket, the site and my printed circuit board system and projects related to those things. I also intend to demonstrate some useful code examples and hopefully explain it so that you can take the knowledge and use it to your advantage. I can tell you right now that if you can wrap your head around the .NET Graphics class and Bitmaps, you can easily write your own image processing and image manipulation/generation software.