Thursday, October 30, 2014

SignalR - C# Client

Intro

In Part 1 of this duet of posts I gave a brief overview of WebSockets, creating a basic SignalR server, and a JavaScript/html SignalR client. Here in the 2nd part we'll see how to create a C# client of SignalR. For the example we'll be using a WinForms project, but you could easily adapt this to a console program, windows service, WPF, DLL, or whatever you desire in C#. On to the code!


Code Sample

First, here's where we left off with our code last week. Download it and open it up in VS 2013. Review Part 1 if you're fuzzy on how some of this stuff works then come on back.

We'llstart today's coding by creating a new WinForms application in VS Express 2013. Go ahead and create yours. I've named mine BlogSignalRClient. Open up Form1 in designer view and add a textbox. Make it MultiLine and give it both scroll bars.

Now add the Microsoft.AspNet.SignalR.Client NuGet package to the new project. Open up the Form1.cs file in code view and paste in the following code:

using Microsoft.AspNet.SignalR.Client;
using System;
using System.Windows.Forms;

namespace BlogSignalRClient
{
    public partial class Form1 : Form
    {
        public IHubProxy HubProxy { get; set; }
        public const string ServerUrl = "http://localhost:61376/";
        public HubConnection Connection { get; set; }

        public async void Connect()
        {
            Connection = new HubConnection(ServerUrl);
            HubProxy = Connection.CreateHubProxy("NotificationHub");
            await Connection.Start();
            HubProxy.On("BroadcastMessage", (message) =>
                this.Invoke((Action)(() =>
                    textBox1.AppendText(String.Format("{0}" + Environment.NewLine, message))
                ))
            );
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Connect();
        }

    }
}


You'll notice that in the Load event we're calling our Connect method. This creates a connection to the SignalR Hub named "NotificationHub" that we created last week. It then creates an instance of HubProxy that will mirror the methods from our SignalR hub. It then opens up the connection, and finally creates an event on the proxy such that when a message is broadcast via the BroadcastMessage method, we will respond in the app by adding the message to our textbox.

Let's test this sucker. If you haven't already, open up last week's project in Visual Studio 2013 and run it. Navigate to the admin.html page as it's where we send messages. Take note of the port you have in your browser window, and modify the code from above appropriately. Now launch the new WinForms app. Click back on your browser window again and type something into the box, then click the Disseminate button.


Click back on your WinForms app again and voila! You should see the message displayed in your textbox.



What's Next?

That's about it for my foray into SignalR. I suggest you experiment with it on your own, see what apps you can think of that would benefit from a real-time 2-way conversation and make them.

Resources

Using SignalR in WinForms and WPF
My WinForms SignalR Code

Wednesday, October 22, 2014

Regular Expressions in C#: A Beginners Guide

Introduction:

Enjoy validating data within your code?  Want an extra super peachy keen neato way of validating data that works?  Have no fear (well, some), regular expressions are here!

Pre-Code Explanation:

Creating a validation string isn't as imposing as some of the sites you might have googled prior to this tutorial.  For easing into creating your own validation string(s):

The \d tag matches any decimal digit.
The \D tag matches any non-decimal digit.
The ^ tag (carat) requires the string to match at the beginning of the compare string.
The {n} phrase matches n number of characters in a pattern.
The $ tag requires the match to occur at the end of a string.

So something like ^\\D{4}-\\d{3}$ could validate the string dude-123 and invalidate 1234-123

Code Sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpConsoleAppRegularExpression
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] zipcodeValues = {
                                  "12345-6789",
                                  "12345-67890",
                                  "1234-56789"
                              };
            string regularExpressionPattern = "^\\d{5}-\\d{4}$";
            string[] phoneNumberValues = {
                                             "555-555-1234",
                                             "55-555-12345",
                                             "555-55-12345",
                                             "555-555-234A"
                                         };
            string phoneNumberValidationPattern = "^\\d{3}-\\d{3}-\\d{4}$";

            string[] genericStringArray = {
                                              "dude-123",
                                              "1234-123"
                                          };
            string genericStringValidationPattern = "^\\D{4}-\\d{3}$";

            System.Console.WriteLine("Validation section for zipcodes:");
            foreach (string value in zipcodeValues)
            {
                System.Console.Write("{0,14}", value);
                if (System.Text.RegularExpressions.Regex.IsMatch(value, regularExpressionPattern))
                    System.Console.WriteLine(" - valid expression");
                else
                    System.Console.WriteLine(" - invalid expression");
            }
            System.Console.WriteLine("Validation section for phone numbers:");
            foreach (string value in phoneNumberValues)
            {
                System.Console.Write("{0,14}", value);
                if (System.Text.RegularExpressions.Regex.IsMatch(value, phoneNumberValidationPattern))
                    System.Console.WriteLine(" - valid expression");
                else
                    System.Console.WriteLine(" - invalid expression");
            }
            System.Console.WriteLine("Validation section for generic string array");
            foreach (string value in genericStringArray)
            {
                System.Console.Write("{0,14}", value);
                if (System.Text.RegularExpressions.Regex.IsMatch(value, genericStringValidationPattern))
                    System.Console.WriteLine(" - valid expression");
                else
                    System.Console.WriteLine(" - invalid expression");
            }

            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

Output:















Prologue:

Regular expressions can be quite useful for validation.  Next week I'll discuss advanced techniques using regular expressions for data validation.

Source:

Thursday, October 16, 2014

SignalR and WebSockets

Intro

WebSocket is a new protocol, developed alongside HTML5, that allows a 2-way communication between client and server. With HTTP and your standard web browsers the communication is all 1-way; the client requests resources from the server and the server serves them. With WebSockets the server can send messages to the client without the client first requesting those resources. Messages can be passed from client to server and from server to client, keeping the socket connection open. Not all the grass is green in this land of Eden though; because this is a newer technology, not all browsers support WebSockets just yet.

This is where SignalR comes in. SignalR is an ASP.Net library that simplifies 2-way communication between the server and the client. It's an implemention of WebSockets, but it's not just that. It will use WebSockets when both the server and client support it, but when one or both does not support WebSockets it will fall back to other technologies that accomplish the same goal in similar ways. Simply put, SignalR allows you to use 2-way communication between client and server using whatever is the best way you are capable of using. Plus, the fallback mechanism happens behind the scenes. This means that you the coder code a single codebase for communication and SignalR makes the choice of which method to use for you. And, one extra bit of info...SignalR allows you to call client-side JavaScript functions from the server. That's some cool stuff!

To the Code!

Create yourself a new Asp.Net web application. Mine's named BlogSignalR1.


Make it an Empty web app with no folders, no core references, and no authentication.

Now add the NuGet package named SignalR.



Now add a class to your project named NotificationHub. Our app will have a single page where we, on the server, can notify our users of things that are about to happen on the website in real-time. This new class is what we'll use on the server-side to send those messages.

Here is the content you'll want for your new class:

using Microsoft.AspNet.SignalR;

namespace BlogSignalR1
{
    public class NotificationHub : Hub
    {
        public void Send(string message)
        {
            Clients.All.broadcastMessage(message);
        }
    }
}


Go ahead and create another new class in your website named Startup. This class will tell Asp.Net to fire up/initialize SignalR. Here's the code for it:

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(BlogSignalR1.Startup))]
namespace BlogSignalR1
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}


Now it's time to work in client-side code a little. First create a new html page in the project. Name the file default.html. Here's the content of that one:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SignalR Basic User Page</title>
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
</head>
<body>
    Hi user!
    <div id="notificationArea">

    </div>
    <!--Script references. -->
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var notification = $.connection.notificationHub;
            // Create a function that the hub can call to broadcast messages.
            notification.client.broadcastMessage = function (message) {
                // Html encode display name and message.
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#notificationArea').text(encodedMsg);
            };

            //create a connection to the hub
            $.connection.hub.start().done(function () {
                //sometimes you might need to do something after creating the connection to your hub; for this example, we do not
                });
        });
    </script>
</body>
</html>


This is a very simple page whose sole purpose is to display notifications from a site admin within the div named notificationArea.

Note: there is a possibility your version of either SignalR or JQuery may be different than mine. If so, please modify the script references as necessary to reflect the version you have in your Scripts folder.

The above html file implies we need one more file, this one for admins to create notifications for users. Go ahead and create a new html file called admin.html. Here's the content:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SignalR Basic Admin Page</title>
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
</head>
<body>
    Hi Admin!
    <label for="message">Message:</label><input type="text" id="message" />
    <button id="disseminate">Disseminate</button>

    <!--Script references. -->
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var notification = $.connection.notificationHub;
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#disseminate').click(function () {
                    // Call the Send method on the hub.
                    notification.server.send($('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>



Another simple page; one entry where you enter text, one button that you click to get it to push out a notification to clients. Let's try it out!

Go ahead and run the solution, navigate to default.html. Open up a 2nd tab in your browser and navigate to admin.html. Type some text into the entry on the admin page and click the Disseminate button.


Now go back over to the other tab containing default.html and your text is there!

Yes that's right folks, with a little bit of server-side code and a little bit of client-side code, you can create a basic site that allows real-time 2-way communication using SignalR. This is some wonderful technology that has tons of potential uses (chat is the most oft-talked-about usage for SignalR and WebSocket technology). If you want to make sure I'm not fooling you, just drop a breakpoint in your server-side and client-side methods and you'll see the trip from admin.html client, to server-side NotificationHub class, back down to default.html. It's mesmerizing!

What's Next?

Play around with the code and see if you can figure out what all of that JavaScript is doing. I find the best way to dig through stuff is to set breakpoints and trace into it and I'm sure you'll have luck with that method too. You can also dig around in the SignalR documentation and tutorials, as I've provided a link to such beasts down in the Resources section.

Resources

SignalR
WebSocket
My Code

Thursday, October 9, 2014

Logging for .Net: ELMAH

Intro

For those of you who work with me or know about the place where I work, we take logging seriously. It's almost a combination of science, art, and religion. We log all kinds of things, some might even say we log too much data. When you log this much data, there are 3 key things you have to do to stay sane: 1) Make the logging of the data easier. 2) Make managing that much data easier. 3) Make it easy to turn the data into useful information.

I won't speak about items 2 and 3, at least not right now. This blog post is all about a library for making it easier to log data in .Net. This library is called ELMAH, or Error Logging Modules and Handlers. It allows you to automatically log unhandled exceptions (this is extremely important for any web site/service), manually log exceptions, and creates a web page for you to view the exceptions that it has logged. All this for free and with a minimal amount of work compared to what it would take to create this functionality yourself!



Example - Logging Unhandled Exceptions


Start by firing up Visual Studio 2013 and create a new ASP.Net Web Application. I've named mine BlogElmah but name yours whatever you like.


Choose "Web Forms" and change the authentication scheme to "No Authentication".


After a little bit of a wait (decently long wait for me, my computer is slow) you'll have a brand new Asp.Net webforms project. Now let's add some ELMAH to it! You'll be happy to know that ELMAH is a NuGet package which makes it easier to plug into your projects. Right-click on the new solution in the Solution Explorer window in Visual Studio and select "Manage NuGet Packages for Solution...".


Locate and install the package named ELMAH.


Your setup is complete. ELMAH by default logs errors to memory which isn't necessarily a good long-term choice, but it'll do for our testing purposes. Just keep in mind that you'll want to move this into a database at some point, or failing that at least some XML files for basic persistence. Anyways, onwards...

Let's throw an exception in code so you can see what the ELMAH do. Open up your default.aspx and toss in a button. Here's mine:

 Now give it an OnClick event that throws an exception, like this:

using System;
using System.Web.UI;

namespace BlogElmah1
{
    public partial class _Default : Page
    {
        protected void ExceptionButton_Click(object sender, EventArgs e)
        {
            throw new Exception("hey, an exception!");
        }
    }
}


Causing an error is probably the easiest part of the process! Run the site and click your brand new button there on the default page. You should end up with an unhandled exception page like this:

Ahh, the dreaded Yellow Page of Death. But hey, that's what we wanted right?

Example - Viewing the Log

Now that we've thrown an exception, let's view the log. This part is super-simple. You still have your browser open from the last step right? Change the destination url to http://localhost:[port]/elmah.axd, where [port] is the port your development server is running on. You're now looking at the elmah exception log which should look like this:




Play around with the links in there, this log is pretty nice. Specifically try out the Details link...yay stack trace! This handling and log make troubleshooting a site much easier with very little work involved.

Example - Manually Logging Exceptions

OK that's all fine and dandy, but you might now say "Hey, we're professionals right? We handle our exceptions already so that we can display a nice message to the user, or decide which programmer needs a flogging, or whatever. We just want to add the ability to log the exceptions we're already handling!". Well ELMAH won't disappoint. Let's see how to do that with a little bit of code...open back up your Default.aspx.cs file and modify the button click event slightly as per the following:

using Elmah;
using System;
using System.Web.UI;

namespace BlogElmah1
{
    public partial class _Default : Page
    {
        protected void ExceptionButton_Click(object sender, EventArgs e)
        {
            try
            {
                throw new Exception("hey, an exception!");
            }
            catch (Exception ex)
            {
                //...do some stuff that's business related...
                //log exception
                ErrorSignal.FromCurrentContext().Raise(ex);
            }
        }
    }
}


First, add a using statement for Elmah. You need to use stuff from that namespace. The next key part is down in the catch statement, ErrorSignal.FromCurrentContext().Raise(ex). This tells ELMAH to log the exception ex. Run the project and click the exception throwing button again. You'll notice no YPOD this time around since we're handling the exception. Point your browser at the local project elmah.axd again and you'll still see your newly thrown exception in the log. Huzza!


What's Next?

Well, them's the key points of ELMAH. There is still a whole lot more you can do though and I encourage you to explore. Here is some of what you can do to enhance your ELMAH experience:
  • Log exceptions to sql or some other backend store
  • Setup an RSS feed of exceptions
  • Get email notifications of exceptions
  • Play with user rights and the exception log viewer web page
  • Allow viewing of exceptions remotely
  • Filter out exceptions you don't want to log
  • Browse the ELMAH website (link below)

Resources

elmah home page

JSON vs XML

Introduction:

First off, definitions for those unfamiliar with JSON and XML.  JSON stands for JavaScript Object Notation.  XML stands for eXtensible Markup Language.  Both are used for data interchange that's somewhat easy to read that contain data-value pairs for server and web applications.

Pros and Cons:

JSON is not quite human friendly but the data is stored in arrays so that has its advantages.  JSON is more compact in terms of data transport as well as differentiating between data types (i.e.: 1 and "1").  JSON is also easily consumed by javascript as well as representing a null value.  JSON doesn't require ending tags for each tag (less characters = faster internet transport) but it's a bit more difficult to determine attribute versus values.

XML is more human reader friendly but requires ending tags for each tag generated.  XML data is stored in trees versus using arrays like JSON.  XML has wider support than JSON in terms of languages and frameworks.  It also can adhere to a very specific declared schema which when it validates correctly you can start parsing data.  XML is older than JSON so it has more of a reach in the coding community than JSON.

Onto some coding samples:

Yep I'm still a fan of RPGs :).  Here is a sample of JSON and XML for a generic Shadowrun type character, just the basics but enough to get the gist of coding differences.

JSON:


XML:

Addendum:

Why yes I did put in some funky characters into the sample (double quotes).  JSON does account for special characters in a very similar manner you use with C# string manipulation.  A semi-comprehensive list of special characters and how to deal with them for JSON can be found here.

Source:

http://stackoverflow.com/questions/5615352/xml-and-json-advantages-and-disadvantages
http://www.programmableweb.com/news/xml-vs.-json-primer/how-to/2013/11/07

Thursday, October 2, 2014

HTML4 Versus HTML5: Coding Examples

Introduction:

Last time I'd mentioned new changes for HTML 5 compared to HTML 4, let's write a bit of code for each to compare/contrast using some of the new features.

Coding Samples:

HTML4 sample:

HTML5 sample:

Comparing The Code:

As you can see with the <embed> tag being used the width and height attributes (within reason) have to be set.  Testing the code in Chrome has the autostart tag rendered useless, IE works as expected with the video file albeit in Windows 7 there was blocked content that had to be unblocked to play it.  IE wouldn't play the audio file at all, directly calling the .wav file played the file in the default media player unlike chrome which used an embedded player.

The video file worked as expected (after unblocking the content), the <video> tag made auto-sizing the control on the page easier (did some tinkering with the height/width on the <embed> tag).

Results:

HTML 4:



HTML 5:

Conclusions:

I have high hopes for the HTML 5 standards, hopefully they'll get the last of the kinks out so we can enjoy the new properties available to us.

Source:



ASP.Net Web Service Debugging Tip

Intro

I'm a big fan of Web API in .Net, as they're simple to write and a good standard way to get things done. However we can't always get what we want, and there are many old-school web services still in place at work. I frequently have to troubleshoot these things to find root causes of errors, and proper logging is key in these situations. Having an exception log with a stack trace is a good first step, but I've found something I like just as much: Logging the complete request from the client.

Solution

If we start with a standard exception log, we can hopefully find the right chunk of code when a customer has an issue. We should have date/time, possibly the caller, the type of exception, and if we're lucky a full stack trace. Sometimes however we need more, as we don't know the data that was passed in which caused the service to 'splode. To that end, I've written and succesfully used a method that will read the full SOAP request so that you can log it somewhere. Here's the beast:

    private string GetRawSoapRequest()
    {
      string soapRequest = "";
      try
      {
        // Get raw request body
        if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.InputStream != null)
        {
          using (Stream receiveStream = HttpContext.Current.Request.InputStream)
          {
            // Move to begining of input stream and read
            receiveStream.Position = 0;
            using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
              soapRequest = readStream.ReadToEnd();
          }
        }
      }
      catch { /*eat it*/ }
      return soapRequest;
    }


It's quite simple. All we do is get a stream reference to the current request inputstream, read it into a string, and return the string. Note that if we throw any kind of exception in the method we just eat it. After all, we don't want to interrupt normal processing because we failed to retrieve some logging information.

How would one use this method in a web service? This is also simple, and here's an example:

    [WebMethod]
    public void AWebMethod(string someString)
    {
      try
      {
        DoSomething(someString);
      }
      catch (Exception ex)
      {
        LogException(ex, GetRawSoapRequest());
        throw;
      }
    }



Our sample WebMethod AWebMethod does a little bit of work and catches any exceptions that may be thrown. In the catch block we log the exception, calling our new GetRawSoapRequest method, and voila! We've now logged the exception and the full SOAP request. This makes tracking down web service exceptions much easier.

What's Next?

  • Security: Your service may accept personal or sensitive information. If so, be careful what you do with the raw request as you might end up storing data in an unencrypted format unintentionally.
  • Compression: Depending on how much stuff you're sending up to the web service, the raw SOAP request can get pretty large. You might want to compress this value before storing it.