Michael OssouThe Web Tools 2012.2 update has been  released. You can download it here.

This update is related to the tooling only i.e. Visual Studio and has no impact on the ASP.NET runtime. In addition to some of the things that help you better use the framework such as SignalR and enhancements to WebAPI that include support for OData, significant updates have been made to Visual Studios’ editor with regards to CSS and Javascipt.

Two of the Three Scotts posted in depth about this update. “Serious Scott Guthrie” had this to say. While “Funny Scott Hanselman” wrote this.

Tagged with:  

HTML 5 WebCam Love

On February 14, 2013, in Internet, Technical, by Michael

Michael OssouLast week we covered doing time lapse photography with jQuery-WebCam. This time I want to highlight some stuff that’s built into HTML 5.

HTML 5 gives you built in access to devices. There were multiple ways of doing this but I think the world has pretty much settled on WebRTC. Microsoft may complicate this matter a little bit but that’s the actual purpose of IE – to complicate our lives – so we are used to it by now.

So lets take a look:

<video id="videoPlayer" autoplay></video>

    <script type="text/javascript">
        $(document).ready(function () {

            var vid = document.getElementById("videoPlayer");

            if(navigator.getUserMedia) { // Standard
                navigator.getUserMedia({ "video": true }, function(stream) {
                    vid.src = stream;
                    vid.play();
                }, errBack);
            } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
                navigator.webkitGetUserMedia({ "video": true }, function(stream){
                    vid.src = window.webkitURL.createObjectURL(stream);
                    vid.play();
                });
            }
        });
    </script>

The HTML 5 implementation is simple but it is also extremely powerful. To learn more, visit HTML5Rocks. To get straight to the fun, try this, this, or this. For those interested in really pushing things, you’ve gotta see this.

– Michael Ossou

Tagged with:  

jQuery + WebCam = Time Lapse

On February 7, 2013, in How-to, Technical, Video, by Michael

Michael OssouLet me start off by saying we wont be using this to create a Tom Lowe masterpiece. Nonetheless, TimeLapse photography is pretty cool.

For those not familiar with timelapse, video runs at 30 frames per second. This means there are 30 individual frames taken per second of video. With regard to timelapse, we introduce a delay after each image is taken, thus time seems to go by faster.

I had previously looked into finding software that would allow me to do some TimeLapse stuff using my webcam, but I primarily found commercial products and eventually just gave up. So when I saw Gunnar Piepman’s post regarding the use of a jQuery webcam plugin to snap a photo via webcam, I was pretty excited. With a few changes, we could use it to take a series of images and later convert those images into a movie using VirtualDub.

Here is my first test timelapse:

I have included the complete project here. But I wanted to highlight a few things.

  • Currently only Logitech HD Webcam C525 based webcams are supported.
  • If you plan on using VirtualDub there is a tutorial here on building the timelapse.
  • Keep in mind that VirtualDub requires the files to be numbered in sequential order. 

If you make a timelapse, we would love to see it!

Tagged with:  

Validating Your Users Email Addresses

On November 14, 2012, in How-to, Technical, by Michael

Michael OssouIt’s really simple. If you can’t contact your users, you have a problem. For better or worse, your primary way of staying in contact with your users is still an email address. So you want to make sure you have a valid email address for them that not only is good during signup, but long after. That means periodically you should check on your data.

The only way to be 100% certain the email address is valid would be to actually email the customer. We’ll get to that shortly, but first let’s look at another option.

How can we programmatically determine if an email address is valid with a reasonable amount of certainty? One option would be to test the email address using a library like ASPNETMX. ASPNETMX can test the validity of an email address by essentially doing four things for us:

  1. Check the Syntax of the email address.
  2. Make sure the domain has a valid MX record associated with it.
  3. Make sure the correct SMTP server exists by connecting to it.
  4. Verify the email address is valid by attempting to send a message and stopping at the last moment

It’s the last part that’s interesting. Let’s manually have an SMTP conversation using telnet and look at what’s going on:

telnet sm11.internetmailserver.net 25
Server: 220 sm11.internetmailserver.net
Me: HELO MyLocalComputerName
SERVER: 250 sm11.internetmailserver.net Hello
Me: MAIL FROM:thesender@michaelossou.com
Server: 250 OK < thesender @michaelossou.com> Sender ok
Me: RCPT TO:therecipient@michaelossou.com
Server: 250 OK < therecipient @michaelossou.com> Recipient ok

When sending a regular message, this conversation would continue. The subject, body, etc. of the message are defined and then the message is sent. ASPNETMX goes through only the above steps and disconnects from the server. It’s interested only in the response the server will issue for the recipients email address. If the server replies ‘Ok’, it considers the email address valid. If the response is not ‘Ok’, it will report that to us as well.

Let’s look at a simple example of a console application that takes an email address and uses ASPNETMX to validate the email address.

using aspNetMX;

namespace AspNetMxSingleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                MXValidate.LoadLicenseKey("1234-1234-1234-1234");
                MXValidate mx = new MXValidate();
                MXValidateLevel lvl = MXValidateLevel.NotValid;
                mx.CheckGreylisting = true;
                mx.CacheMXTimeOut = new TimeSpan(1, 0, 0);
                mx.LogInMemory = true;

                string emailAddress;
                Console.WriteLine("Enter Email Address:");
                emailAddress = Console.ReadLine();
                lvl = mx.Validate(emailAddress, MXValidateLevel.Mailbox);
                Console.WriteLine(lvl.ToString());
                Console.WriteLine(mx.GetLog());

            }

        }
    }
}

Now, let’s look at the results.

ASPNETMX Results

A more complete option would probably be to actually send an email. The idea being that when it’s time to send a newsletter or some other communication, we use the bounced messages to flag our bad email addresses.

Services like MailGun and SendGrid make this a pretty painless process as they offer APIs to deal with such events. SendGrid even has a Nuget Package to drop their bits into your Visual Studio project. These aren’t the cheapest options, but if you read our post regarding mass email last week, you will see a lot goes into the services they offer.

Tagged with:  

A Presidential WebSockets Project

On November 2, 2012, in Miscellaneous, by Michael

Michael OssouIf you are anything like me, watching the Presidential Debates was an exercise in not being distracted by the “dial-o-meter” at the bottom of the screen.

Since the two biggest features of HTML 5 are Canvas and WebSockets, I thought a Dial-o-Meter would lend itself well to a simple sample project that pretty much anybody could follow along with.

So in this post, we are going to build the “Dial” using Canvas and WebSockets. Maybe in a future post we will upgrade and complete the project, using SignalR.

First some prerequisites. Since we’ll be using the final release of ASP.NET 4.5, there is no need to use any Nuget package. We will be concentrating on the System.Web.WebSockets namespace.

WebSocket support is only available in ASP.NET 4.5. This means you will need to be on IIS 8. If you have not yet migrated, you will need to do so (In the Account Information section of Control Panel, look for “Server Type” and you can find an UPGRADE link there). If you are already on an IIS 8 account, we will need to make sure your account is ready for WebSockets. Contact support and they can make the necessary WebSockets configuration for you.

It’s also important to note that if you are running Visual Studio 2012 on Windows 7, the application will not run locally. You will need to work on the application, then upload it to the server to run it. This is because WebSockets will only run on Windows 8/Windows 2012. On the client side, you will need a browser that supports HTML 5.

So whats the point of all this? The short version is that the WebSocket protocol provides us with the plumbing to maintain a persistent, two-way, communications channel between the client and the server. This is ideal for applications that require real-time updating. The most common use cases described are things like chat or a stock related application. With the plumbing here however, it wont be long before people turn to WebSockets for a host of other things as well.

Using WebSockets is much faster than servicing HTTP requests. This means using WebSockets could be a better solution than AJAX for large dynamic applications. So how do WebSockets Actually Work? You can look here for the details, but essentially an HTTP request is made and that connection is upgraded to a WebSocket connection.

With all of that out of the way, let’s dive in and start with our HTML Page. There are two buttons to indicate Up/Down emotions that trigger messages to be sent to the server. There is also  a canvas that will visually display the data that is returned from the server. For this post/sample, all we are doing is making a round trip.

Screenshot of the WebSocket Dial we are building

Instead of the buttons affecting the canvas on the page directly, we will instead use WebSockets to send the data to the server, and have the server send the data back to the browser. Then, the canvas will be updated based on the server data. We do all this on the client side using JavaScript.

The entire project is included at the bottom of the post, but lets look at it section by section.

First the HTML controls. Nothing fancy here. The controls that we already talked about above and a place holder we will use to echo network communications.

<canvas id="myCanvas" width="800" height="400"></canvas>

 <input id="btnUp" value="Up" type="button" />
 <input id="btnDown" value="Down" type="button" /></pre>
<div id="dvNetworkStatus"></div>
<pre>

Now for the Heart of the page, lets look at the JavaScript that ties into the browsers API’s and makes all this work for us. Again, one section at a time.

Here we are defining our WebSocket endpoint and tying up the websocket object that is exposed to us to some custom functions.  When the WebSocket connection is opened, closed, or we receive a message from the server, we want a specific function to be fired.

<script type="text/javascript">// <![CDATA[
              $(document).ready(function () {

                  var wsUri = "ws://iis8hosting.com/websocketblog/wshandler.ashx";
                  websocket = new WebSocket(wsUri);
                  websocket.onopen = function (evt) { onOpen(evt) };
                  websocket.onmessage = function (evt) { onMessage(evt) };
                  websocket.onclose = function (evt) { onClose(evt) };
                  websocket.onerror = function (evt) { onError(evt) };

With our WebSocket object setup, lets get the canvas ready. We setup the canvas object then initialize it. The reason we initialize it in its own function is because we will want to clear it out later again when it gets full. So we put that piece in its own function so we can just call it again later. The canvas works with an X/Y coordinate system so we want to initialize those values as our baseline as well.

                  var canvas = document.getElementById('myCanvas');
                  var context = canvas.getContext('2d');
                  var xCoordinate = 10;
                  var yCoordinate = 200;
                  initCanvas();

                  function initCanvas() {
                      canvas.width = canvas.width;
                      context.fillStyle = "#78829E";
                      context.fillRect(0, 0, 800, 400);
                      context.beginPath();
                      context.strokeStyle = 'white';
                      context.moveTo(0, 200);
                      context.lineTo(800, 200);
                      context.stroke();
                      xCoordinate = 10;
                      context.beginPath();
                      context.moveTo(xCoordinate, yCoordinate);
                      context.strokeStyle = 'black';
                  }

The next set of functions correspond to various states of our WebSocket connection as defined up top. Notice all we are doing with them now is updating our little status place holder. Also, notice the wsSend function. This is the function responsible for actually sending the data across the wire.  The onMessage function is fired when we receive a message from the server. Notice it calls the drawToCavas method to update the line on our canvas.

                  function onOpen(evt) {
                      $('#dvNetworkStatus').text("Server Status: Connected");
                  }

                  function onMessage(evt) {
                      $('#dvNetworkStatus').text("Message Recieved: " + evt.data);
                      drawToCanvas(evt.data);

                  }

                  function onClose(evt) {
                      $('#dvNetworkStatus').text("Server Status: Closed");

                  }

                  function onError(evt) {
                      $('#dvNetworkStatus').text("Server Status: Error Connecting USE FIDDLER TO DEBUG!!!!");

                  }

                  function wsSend(message) {
                      $('#dvNetworkStatus').text("Message Sent: " + message);
                      websocket.send(message);
                  }

Next up is our drawToCanvas function. We make sure our X/Y coordinates are within the bounds of our canvas, if they are not, we call the initCanvas function descibed above to give us a clean slate. Then we simply draw the line onto the canvas.

                  function drawToCanvas() {

                      // If we get close to the edge of the canvas, clear and start over.
                      xCoordinate = xCoordinate + 25;

                      if (xCoordinate > 740) {
                          initCanvas();
                      }

                      context.lineTo(xCoordinate, yCoordinate);
                      context.lineCap = 'round';
                      context.lineWidth = 6;
                      context.stroke();
                  }

Lastly, the two functions responsible for our button clicks. Now this could have been one function but lets keep things simple. The key thing to note here is that the clicks are calling the wsSend function mentioned above and passing the updated yCoordinate.

                  $('#btnUp').click(function () {
                      if (yCoordinate > 25) {
                          yCoordinate = yCoordinate - 25;
                      }

                      wsSend(yCoordinate);
                  });

                  $('#btnDown').click(function () {
                      if (yCoordinate < 375) {
                          yCoordinate = yCoordinate + 25;
                      }
                      wsSend(yCoordinate);
                  });

              });

// ]]></script>

That’s it for the client side. Now on to the server. We are going to create a generic handler and use Async & Await to service the requests. Again, step by step. First, we need to make sure that the request coming in is indeed a WebSocket request. If it is, our async task called MyWebSocketTask will service the request. This is where we accept/upgrade our connection request. If its not, throw an exception.

    public class wshandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
            {
                context.AcceptWebSocketRequest(MyWebSocketTask);
            }
            else
            {
                throw new HttpException("This isn't a WebSocket request!");
            }

        }

Here is our brain. We are going to wait for a message, then simply echo that message back to the client.

        public async Task MyWebSocketTask(AspNetWebSocketContext context)
        {
            WebSocket socket = context.WebSocket;

            while (true)
            {
                ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);

 // Asynchronously wait for a message to arrive from a client
 WebSocketReceiveResult result =
 await socket.ReceiveAsync(buffer, CancellationToken.None);

 // If the socket is still open, echo the message back to the client
 if (socket.State == WebSocketState.Open)
 {

 string userMessage = Encoding.UTF8.GetString(buffer.Array, 0,
 result.Count);

 buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));

 // Asynchronously send a message to the client
 await socket.SendAsync(buffer, WebSocketMessageType.Text,
 true, CancellationToken.None);
 }

 else
 {
 break;
 }
 }
 }

That’s all there is to it. I hope this gave you an idea of where you can go with WebSockets. Maybe all the way to 1600 Pennsylvania Avenue…

Download the entire project here.

 

Michael OssouTeam Foundation Server 2012 and Visual Studio 2012 have been released, so I thought it was time for a new “getting started” video.

We support TFS 2012 in both our shared and managed TFS hosting platforms.

If you’re new to TFS, or new to using TFS at DiscountASP.NET, take a few minutes to watch the video. It will answer some of your questions and save you some time.

 

ASP.NET 4.5 beta is finally here!

On February 29, 2012, in Announcements, Technical, by Michael

Michael OssouThis is the blog post you have been waiting for. Well, maybe not, but its the blog post I look forward to writing. If you are an ASP.NET developer, this is an exciting time, because we get the new version of the framework that we will be working with for the next X number of years. You can look at the complete ASP.NET 4.5  features and updates list for yourself. This post is about some of the features I think our hosting customers will be happy to hear about.

First off there are a number of performance improvements specifically related to ASP.NET hosting. So out of the box, this version of the runtime should provide performance improvements. Thats always good news. One of the primary improvements is the introduction of Multi-Core JIT compilation. This means an uncompiled application will spool up much faster the first time it is run. With that out the way, lets look at some specific features and why we like them.

Asynchronous Improvements

We can now asychronously Read and Write HTTP Requests and Responses. HttpRequest.GetBufferlessInputStream now has BeginRead and EndRead methods. Conversely, HttpResponse now has BeginFlush and EndFlush Methods. Additionally, there is now support for await and Task-Based Asynchronous Modules and Handlers.

Request Validation

Out of the box, the popular AntiXSS library is included. We also gain support for “lazy” validation. Previously when request validation was invoked, everything in the collection was validated. With “lazy” validation, only the item specified will be validated.

WebSocket Support

With all the buzz regarding HTML 5 lately, one of the most talked about features is WebSockets. ASP.NET 4.5 includes the System.Web.WebSockets namespace that will allow for asynchronous communication with WebSocket objects.

Bundling & Minifiaction

Bundling allows you to point to a folder and “bundle” a group of files. This is useful for javascript and CSS files. Additionally, Minification is the process of condensing CSS and javascript files into smaller versions. This is done by removing white space and refactoring the code. For example, it is common to use variable names that we can read and understand. However computers, dont need such descriptive names. Minification would condense the the variable name down to a single character.

What features are you looking forward to in the ASP.NET 4.5 release?

Tagged with:  

Redirecting HTTP requests to HTTPS

On February 10, 2012, in How-to, Technical, by Michael

Michael OssouA common question that is often asked is how to auto-magically redirect HTTP requests for your web sites to HTTPS. Simply put, if someone types “http://www.yoursite.com” how can you redirect that request to “https://www.yoursite.com”?

This post is the simple answer to that question. IIS’s URL rewrite module can help us accomplish this as well as other rewrite tasks. For a complete look at how URL Rewriting works, take a look at the following MSDN article on URL Rewrite. Then look at the following as an example of what to add to your web.config:

      <rewrite>
        <rules>
          <rule name="Redirect to HTTPS" stopProcessing="true">
            <match url="(.*)" />
            <conditions>
              <add input="{HTTPS}" pattern="^OFF$" />
            </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
          </rule>
        </rules>
      </rewrite>
Tagged with:  
iBlog by PageLines