Showing posts with label Advanced. Show all posts
Showing posts with label Advanced. Show all posts

Thursday, July 9, 2015

C# Anonymous Functions

Intro

Anonymous Functions: Things that activist hacker group does when they go into the potty room. Darn, I keep forgetting this is a programming blog! OK in this case an Anonymous Function is an "inline statement or expression that can be used wherever a delegate type is expected." (1). In layman's terms, rather than supplying a fully-defined function to a delegate, you can create an anonymous function within your normal code and use that. It's hard to explain, so let's see it in action.



Code Samples in VS2013, .Net 4.5.

Simple Use Case



using System;

namespace BlogAnonymousFunction
{
    public class Thingy
    {
        public string DoAThing(int val1, int val2, Func preProcessor = null)
        {
            int val3 = -1;
            if (preProcessor != null)
                val3 = preProcessor(val1, val2);
            return String.Format("val1:{0}, val2:{1}, val3: {2}", val1, val2, val3);
        }
    }
}


using System;

namespace BlogAnonymousFunction
{
    class Program
    {
        static void Main(string[] args)
        {
            var thingy = new Thingy();
            var result = thingy.DoAThing(24, 42, null);
            Console.WriteLine(result);
            result = thingy.DoAThing(24, 42, new Func((val1, val2) => val1 + val2));
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}



A simple example to be certain. Our class Thingy has a single method DoAThing that accepts a function as a parameter. If the user passes in a value for this nullable function we will call it and set it to our 3rd value.

In the Main method we call DoAThing twice. First we call it once passing in a null function parameter. In the second call we pass in an anonymous function that adds the first and 2nd parameter, returning the result. You can see the results of our two function calls in the output window screenshot below.


Cool huh? Simple too, but it does take a few repetitions to get used to the odd syntax. Enjoy!

What's Next?

You can also do generic methods (no return type), you can create variables that reference a generic function/method, and more! Search on teh webs, you'll find plenty.

Resources

(1) Anonymous Functions
The Generic Func Delegates

Thursday, April 23, 2015

Reflection in C#, Part 1

Intro

Reflection is a technology whereby you can view and modify the structure and behavior of a program at runtime. This general definition always seemed a bit vague to me, so picture this: You have a class, and for whatever reason you want the user to be able to select a property of your object from a dropdown, and type in a new value for the property in a textbox. You could manually populate your dropdown with the property names and have a big switch statement to set the value, but reflection would make this much easier by allowing you to, at runtime, discover the names of the properties and set their values. Nifty! I've personally used reflection for custom serialization (If you've heard of and used the TurboTags 2.0 format then you've used my reflection), and I've used it for a custom storage system that works a lot like Entity Framework. Well, now that I've tooted my own reflection horn let's get down to shiny and highly reflective brass tacks.


Note: Samples are VS2013 Community edition, .Net 4.5. Here is the sample project if you want to play along.

 

What can Reflection Do?

  • List Classes in Assembly - You can get a listing of the classes within an assembly.
  • Create Instance of Classes - You can create an instance of one of them thar classes that you found.
  • List Properties - Need a listing of the properties of the class? Reflection has you covered.
  • Get and set property value - Ooh, and you can modify those properties too!
  • List Methods - Once you've listed the properties of a class, it's easy to list the methods.
  • Execute Methods - Executing the methods with reflection is simple once you've found them.
  • And More! - Yay more! You can get attributes and other things too.
Let's dig into some specifics. I doubt we'll cover all of them this week, but let's give it the ol' college try.

List Classes in Assembly

I've created a Windows Forms app for demonstration purposes. Let's start by listing all the classes in an assembly. The first thing we need to do, after creating the solution of course, is add a reference to the System.Reflection assembly. This is where we get all the reflection junk. Now we're going to, in the Form_Load event handler, populate a dropdownlist with the classes of our current assembly:

        private void MainForm_Load(object sender, EventArgs e)
        {
            var a = Assembly.GetExecutingAssembly();
            ListClassesEntry.Items.AddRange(a.GetTypes());
        }


Getting a reference to the current assembly is easy with reflection. We accomplish the task above by calling Assembly.GetExecutingAssembly. The next line shows how to get all the classes contained within the assembly. In our case we come up with 4 distinct classes: BlogReflection.MainForm, BlogReflection.Program, BlogReflection.Properties.Resources, and BlogReflection.Properties.Settings. This is a nice, small, manageable list. Yay!

Create An Instance of a Class

Now that we have a list of classes within our assembly, let's create an instance of the selected class when the user selects a Type from the DropDownList:

        private void ListClassesEntry_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrWhiteSpace(ListClassesEntry.SelectedItem.ToString()))
            {
                var assembly = Assembly.GetExecutingAssembly();
                var formType = assembly.GetType(ListClassesEntry.SelectedItem.ToString());
                var constructor = formType.GetConstructor(new Type[] { });
                var instance = constructor.Invoke(new Object[] { });
            }
        }


Another pretty simple method. The key part here is the call to GetConstructor and then the call to Invoke. GetConstructor, in this form, will find the constructor that accepts parameters as specified by the Type[] type array parameter. In our case we passed in an  empty array of type Type, so we want a parameterless constructor. The next line, Invoke, calls the constructor method passing in another empty array of parameters. So in essence we first find the parameterless constructor of the selected type, and we then invoke the parameterless constructor of the type. Neato! Tip: This method bombs horribly if the type you select, with the DropDownList, doesn't have a parameterless constructor. Oh well, nothing's perfect. Figure out how to get around that on your own :)

We're Done!

Hey Pete, you didn't talk about all the other cool stuff Reflection can do! You're right, what can I say; I'm lazy. We'll cover some more parts of reflection next week.

What's Next?

Figure out how you can call a constructor that has parameters. If you'd like to, you can also skip ahead to next week's topic by figuring out how to find and execute methods as well as find and get/set property values.


Resources

C# Reflection

Thursday, March 19, 2015

.Net OData Services

Intro

I've talked about Web API in previous articles, and I think my overall opinion is pretty clear: I really like the direction MS has taken with internet-based services. I find Web API to be a big improvement over SOAP services and WCF. They're simpler and more flexible, and I find them to be just plain fun. However there is a more powerful alternative out there that is still quite simple: OData. OData is an "open protocol to allow the creation and consumption of queryable and interoperable RESTful APIs in a simple and standard way." For .Net, OData is supported in Web APIs with just a few minor tweaks to your code. So in essence you get queryable RESTful APIs with very little effort on your part. OK everybody, time to show me your OData face and let's get crackin!




Howdie Doodie

Time to talk specifics. Pretend you have a list of animals. You want a RESTful service that allows the client to query your list of animals by name. OK cool, sounds easy enough. You might create a Web API that has a GET method with a single parameter, name. The user hits your api, maybe with the url /api/animals/timmy, and this would return Timmy the lion (we'll just assume all your animals have unique names). Now what if the client wants to retrieve a list of mammals? You could always create a new GET method in your API that has a single parameter for class and the client would hit /api/animals/mammal, but now you've got 2 conflicting API methods and they each need their own special path. Plus you're making some duplicated code here, as in essence you're still just querying your list of animals for specific animal(s). OData gives you an easier out. Let's create an OData service that allows querying as per the previous desires.

First, fire up Visual Studio. I'm using VS 2013 here. Create a new empty Web API project.


Now add a class to your Models folder. Name the class Animal.

Make your class look like this:

using System.ComponentModel.DataAnnotations;
namespace BlogOData.Models
{
    public class Animal
    {
        [Key]
        public string Name { get; set; }
        public string Type { get; set; }
        public string Class { get; set; }
        public int Height { get; set; }
        public int Weight { get; set; }
    }
}

Note: The Key attribute is merely used to identify which is the unique property of our class that identifies individual instances of an animal. In the real world names aren't unique, but this is a blog not the real world.

Now it's time for our OData controller. Go ahead and add one named Animals to your Controllers directory as per the following screenshots:



You've now got a rather large file named AnimalsController.cs in your Controllers folder. It has a lot of extra actions that we don't need since all we care about is retrieving an animal or list of animals based on criteria specified by the client. Replace the code of your new controller with the following:

using System.Collections.Generic;
using System.Linq;
using System.Web.Http.OData;
using BlogOData.Models;

namespace BlogOData.Controllers
{
    public class AnimalsController : ODataController
    {
        public List<Animal> Animals;

        public AnimalsController()
        {
            Animals = new List<Animal>();
            Animals.Add(new Animal() { Class = "mammal", Type = "lion", Name = "timmy", Height = 64, Weight = 495 });
            Animals.Add(new Animal() { Class = "reptile", Type = "box turtle", Name = "billy", Height = 4, Weight = 2 });
            Animals.Add(new Animal() { Class = "reptile", Type = "leopard gecko", Name = "marzipan", Height = 1, Weight = 1 });
            Animals.Add(new Animal() { Class = "invertebrate", Type = "worm", Name = "willy", Height = 1, Weight = 1 });
            Animals.Add(new Animal() { Class = "mammal", Type = "house cat", Name = "sushi", Height = 1, Weight = 12 });
        }

        [EnableQuery]
        public IQueryable<Animal> Get()
        {
            return Animals.AsQueryable();
        }
    }
}

The first thing that is noteworthy is your class declaration for AnimalsController. We're descending from ODataController. Next in line, our constructor. It's not really all that special, but you can see we're populating a list of animals. Lastly the method Get. This has a few interesting bits:
  1. The EnableQuery attribute. This tells the runtime that we are returning a result from this method that is queryable using OData. 
  2. The return type is IQueryable<Animal>. This lets the result set be queried automatically via the OData backend.
  3. Lastly, we return our list of Animals as a queryable object. 
With this incredibly small amount of code, we've now created an OData controller that lets clients tell the server to return only specific results.

And now is where I tell you there's one more piece left. As things stand at the moment, there is no route to your OData controller, which means clients can't actually call it. Open up your WebApiConfig.cs file in the App_Start folder. Looking at the below code sample, you'll need to add the 3 lines of code underneath the comment "//OData Routes":

using System.Web.Http;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
using BlogOData.Models;

namespace BlogOData
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //OData Routes
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Animal>("animals");
            config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());

        }
    }
}


These 3 lines tell the runtime that we wish people to access our OData controller via the url /odata/animals (case-sensitive). That's it. Run this little sucker! When your browser first comes up, you'll probably see a 403 forbidden error like the following:


Not to worry though; that's not really the url you want. If you're debugging in IE, go ahead and open up a firefox window. It's easier to demo Web API and OData functionality with than IE. Leave the IE debugging window open though. Navigate to your localhost url plus "/odata/animals". You should now see this:


Cool! This is the JSON response from our OData controller showing the full list of animals. I hope you're now thinking "Geez Peeticus, that's cool! But hey, didn't you say the client could tell the server, via a query of some sort, which animals to return?". Well yes I did, and yes we can. OData has it's own special syntax that we can use for filtering, delivered via the $filter querystring parameter. Let's go ahead and use a basic query now...add this on to the url you already have in FireFox: "?$filter=Name eq 'timmy'" (note these filters are also case-sensitive, as are string values contained therein). Here's what your result looks like:

Try a few more queries. Maybe we want to see all the mammals with "?$filter=Class eq 'mammal'".

Holy poo this is cool! We didn't have to write a bunch of switch statements with dynamic querying, LINQ statements, or anything of the sort. All this filtering is handled automagically!


What's Next?

You have a lot more query options with OData than what I've shown you here today. Play around, see what all else you can do, and check out the OData website for more information. It's powerful stuff. You might also try creating a C# client to consume your OData service. Info on how to do that can be found here.

Resources

OData Home
Create an OData v4 Endpoint Using ASP.Net Web API 2.2

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

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