Interprocess Communication via Self Hosted WCF

Lately I was asked if there is a way to allow 2 apps to communicate even if they are belonging to 2 different exe’s . Fortunately for me I have the source code of both 2 apps. The main reason why instead of merging the projects, we went to IPC or interprocess communication is because, I belong to a team that maintains the other windows forms app and the other project or exe belongs to another team that has their own deliverables. And another thing is, we want to deploy the IPC functionality the soonest. It means it is badly needed.

The way to do it is have a listener in the second app and let the first app talk to the second app with the same url.

Oh, first lets create something (object) that can be shared between the 2 apps. When you communicate, you transfer knowledge, words, etc. In our case lets transfer some data to the other app.

The Data

[DataContract]
[Serializable()]
public class UserInformation
{
[DataMember]
public string Name { get; set; }

[DataMember]
public DateTime BirthDate { get; set; }

[DataMember]
public string Address { get; set; }
}

The Service Contract

This will be self hosting service which will be hosted in the listener app.

[ServiceContract(Namespace = “https://www.francorobles.com”)]
public interface IUserServiceContract
{
[OperationContract]
int UpdateUserInformation(UserInformation userInformation);

}

The Service Implementation

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class UserService : IUserServiceContract
{
public int UpdateUserInformation(UserInformation userInformation)
{
return 1;
}
}

Starting the listener

This code block will be in the listener app. What it does is we instantiated a wcf service inside our windows app via named pipe.

Dim address As String = String.Concat(“net.pipe://localhost/user/userservice”, Environment.UserName)
Dim _userService As UserService = New UserService()
Dim serviceHost As New ServiceHost(_userService e)
Dim binding As New NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
serviceHost.AddServiceEndpoint(GetType(IUserServiceContract), binding, address)
serviceHost.Open()

Calling the listener

Here we called the listener via the same url that was instantiated in the listener app. Then we created a UserInformation object and passed it like we do in a normal wcf service.

Dim address As String = String.Concat(“net.pipe://localhost/user/userservice”, Environment.UserName)
Dim binding As New NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
Dim ep As New EndpointAddress(address)
Dim channel As IUserServiceContract = ChannelFactory(Of IUserServiceContract).CreateChannel(binding, ep)

Dim _userInformation as new UserInformation()
_userInformation.Name = “Franco Robles”
_userInformation.BirthDate = DateTime.Parse(“1985-10-08”)
_userInformation.Address = “Makati, Philippines”
channel.UpdateInformation(_userInformation)

 

And thats pretty much about it. There are many types of IPC (Inter Process Communication), WCF via named pipe just suits my needs. Maybe you encounter the same scenario sooner or later and hopefully this post will be a starting point for you.

Happy Coding!!!

 

 

 

 

 

Advertisements

Real Time Web with SignalR and ASP.NET MVC

This afternoon I was thinking about an app where users will be notified in real time. Some suggestions were raised but at the moment I think only Node.JS and SignalR are the most viable candidate for this scenario. For this post, since I am going to use ASP.NET MVC, I will use SignalR which is native to .NET.

Okay, for those who are not familiar yet with SignalR. According to its site, it is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. For me, basically, it is the most convenient way in notifying the client that something happened from the server in real time. No need for work around or any sort.

Now, time for the development.

1. First we need to get a reference of SignalR from Nuget. You can also get it from Github. Or download it as zip and add it as reference. But if you are new, I would suggest using nuget.

– Install-Package Microsoft.AspNet.SignalR

SignalR_Nuget

2. Once you have it installed. Let’s create  a Hub. A SignalR Hub enables you to make remote procedure calls (RPCs) from a server to connected clients and from clients to the server.

– First we need to add a folder to our web project called Hubs.

– Then create a class called CustomerHub. Below is how it should look like. I intentionally made it empty since it just acts like a fake hub. All the crud operation happens in the actionresult and you will find out how i called the client method from the actionresult once you finished reading this post.

using Microsoft.AspNet.SignalR;

namespace CustomerSite.Hubs
{
    public class CustomerHub : Hub
    {
        
    }
}

– Then another important part is to add the startup class which does all the mapping.

using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(CustomerSite.Hubs.Startup))]
namespace CustomerSite.Hubs
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

3. Now lets get back to our view.

– Add a reference to SignalRJS.

<script src=”~/Scripts/jquery.signalR-2.1.2.js”></script>

– Set a reference to the available hubs that we created, in this case the CustomerHub that we created as shown below.

<script src=”/signalr/hubs”></script>

– This is how my Layout looks like.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Realtime Web with SignalR</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    @RenderSection("styles", false)
</head>
<body>
    <div class="container body-content">
        @RenderBody()
    </div>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/Scripts/knockout.js"></script>
    <script src="~/Scripts/jquery.signalR-2.1.2.js"></script>
    <script src="/signalr/hubs"></script>
    @RenderSection("scripts", false)
</body>
</html>

4. The client side SignalR registration with knockout.
-> self.hub = $.connection.customerHub; //tells the hub object to point to customerhub on the server.
-> self.hub.client.getCustomers = function () { //is a method that will be called from the server.
self.loadCustomers();
}
-> $.connection.hub.start(); // the client side listener

function AppViewModel() {
    var self = this;

    self.hub = $.connection.customerHub;

    self.hub.client.getCustomers = function () {
        self.loadCustomers();
    }

    $.connection.hub.start();
    
    ... //Code removed here just for this post.

    //A function for loading the customer view via ajax.
    self.loadCustomers = function () {
        $.ajax({
            url: '/Home/CustomerList',
            success: function (data) {
                $("#customerlist").html(data);
            }
        });
    };

    //The function for updating and adding a customer.
    self.submitForm = function () {
        var url = '/Home/SaveCustomer';
        if (self.isEdit()) {
            url = '/Home/UpdateCustomer';
        } 
        $.ajax({
            url: url,
            data: {
                firstName: self.firstName(),
                lastName: self.lastName(),
                address: self.address(),
                phone: self.phone(),
                creditLimit: self.creditLimit(),
                customerSince: self.customerSince(),
                id: self.customerId()
            },
            success: function (data) {
                if (String(data.saved) == 'true') {
                    self.formVisible(false);
                    //self.loadCustomers();
                }
            }
        });
    };
}
ko.applyBindings(new AppViewModel());

5. For the server side to client interaction via ActionResult.

public ActionResult SaveCustomer([Bind(Exclude = "Id")]CustomerViewModel customer)
        {
            provider = new CustomerProvider();
            bool saved = provider.AddCustomer(customer);
            IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext();
            hubContext.Clients.All.getCustomers();
            return Json(new { saved = saved }, JsonRequestBehavior.AllowGet);
        }

The most important part here are these 2 lines. Basically, what this does is it gets the CustomerHub context and call the getCustomers method that we declared on the client.

IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<CustomerHub>();
hubContext.Clients.All.getCustomers();

This is the screen capture of the app running side by side updating each other. We’re done.

AppRunning

By the way, I will post a followup blog on DependencyInjection with SignalR.

Dependency Injection with StructureMap and ASP.NET MVC

According to this article, DI or Dependency Injection is a software design pattern, a particular case of the Inversion of Control pattern, in which one or more dependencies are injected into dependent objects. The pattern is used to create program designs that are loosely coupled and testable.

For me, what matters is the last 2 terms “loosely coupled” and “testable”. But with the number of DI tools out there which would you choose? Well, this article has the best comparison so far. And I have decided to use structuremap because its actively maintained, plenty of new features which I am going to explore later on on the next blog.  But overall? Structuremap is highly configurable.

So, let’s start.

1. Get structuremap via nuget.

nuget

 

 

2. For this article lets resolved the dependencies in our Global.asax file.

– In the below snippet on Application_Start method, Structuremap basically has an ObjectFactory class that let’s you configure your dependency resolutions. On the below snippet, I am telling structuremap to grab the concrete class CustomerProvider for my ICustomerProvider interface.

ObjectFactory.Initialize(x =>
{
     x.For<ICustomerProvider>().Use<CustomerProvider>();
});

 

3. Now time for the real use of DI.
– In the below snippet is what is called Constructor Injection. There is another way too called Property Injection. Basically, what it does is to simply remove the concrete class from being assigned to ICustomerProvider. So that later on, I can modify the concrete class’s implementation without modifying my controller.

public class HomeController : Controller
{
        ICustomerProvider provider;

        public HomeController(ICustomerProvider provider) {
            this.provider = provider;
        }

        public ActionResult CustomerList()
        {
            return PartialView(provider.GetCustomers());
        }
}

 

4. If we run the program and we encounter a parameterless constructor issue. The solution to that is override the defaultcontrollerfactory and let Structuremap instantiate the controllers.

public class StructureMapControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
                return base.GetControllerInstance(requestContext, controllerType);

            return ObjectFactory.GetInstance(controllerType) as Controller;
        }
    }

– Then we modify our initialization to this.

ObjectFactory.Initialize(x =>
{
     x.For<ICustomerProvider>().Use<CustomerProvider>();
});
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());

On the next blog, I will cover a deeper topic on this.

IEnumerable VS IQueryable

Lately I have been doing some performance improvements in one of the modules of our web application in the office. I am writing this to share my observation between the 2 important subjects.

1. IEnumerable

– Exposes an enumerator, which supports a simple iteration over a non-generic collection.

2. IQueryable

– Provides functionality to evaluate queries against a specific data source wherein the type of the data is not specified.

Okay let’s go to the real stuff. Lets say we have a collection from our EDMX. And we want to pick the top 100 last inserted records. So how do we do that?

1. IEnumerable

using (var context = new MyContext()) 
{
    IEnumerable<Employee> employees = context.Employees.OrderByDescending(e => e.EmployeeId);
    var latestEmployees = employees.Take(100);
}

1. IQueryable

using (var context = new MyContext()) 
{
    IQueryable<Employee> employees = context.Employees.OrderByDescending(e => e.EmployeeId);
    var latestEmployees = employees.Take(100);
}

Okay that was easy. Now let’s see how it is being interpreted by SQL Server.

1. Using IEnumerable – As you can see below it gets all the records without applying the top 100 filter which is really a bad idea if you have thousands of rows.

IEnumerable

 

2. Using IQueryable – Now with IQueryable, the query result is now different which is what we want. Apply the top 100 first before we execute the query.

IQueryable
As you can see from the above comparison, there is a very huge difference between the 2 when they are executed. I would suggest IEnumerable if you are dealing with in memory collections. If you want to deal with database collections I would suggest IQueryable.

 

I hope I had shared some helpful information to you regarding these topics which we use everyday and hopefully if you like my blog please also visit my site http://www.francorobles.com to know more about me.

Patching .net executables with Reflexil.

Lost the source code of a .net executable file? What will you do? Instead of searching for the missing piece which was not documented and not hosted in the version control, instead of searching for it in windows explorers for hours when you already know it cant be found, instead of blaming someone for not making a backup of it, go move and use a tool from red gate called the reflector and its add-in called reflexil.

My case was like the above, where someone forgot to make a backup of a running program, which will run forever. Its a windows application where members of a certain promotion are going to swipe their cards to the application and if they are entitled, the standalone application will print a voucher stating that they can claim these and those. The application needs to be updated by certain people monthly, and my boss asked me if there is a way to automate it? I said YES, but the problem is i dont have the source code, only the executable. I said, there has to be a way, and here is how I did it.

First, download these tools:
1. Reflector – http://www.red-gate.com/products/reflector/
2. Reflexil – http://sebastien.lebreton.free.fr/reflexil/

Lets setup reflector first.
1. Open reflector.

2. Add reflexil in the add-ins. Just go to View->AddIns and add Reflexil.Reflector.dll.

3.  Load the executable file that you need to patch.

4. Now select the function or method that you want to patch. Right-click on the reflexil pane and select Replace all with code.

5. Now lets make our changes.

Once you did the change, Right-click your loaded assembly and select save as from the context menu.

Now see the lesson? “Next time, host your code in your version control!.”

URL rewrite with encryption for security reasons.

Today I was asked by my friend on how to rewrite a url for security reasons. He added that a geeky person might attempt to do something on the web application. With that in hand, I said, maybe we can try encrypting the string (QueryString) that we append to our original url. And here is how i did it.

First – Create the class that encrypts and decrypts our string.

using System.Text;
using System.Security.Cryptography;

namespace SC.Utility {
     public class Security {

     public static string Encrypt(string toEncrypt, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            System.Configuration.AppSettingsReader settingsReader =
                                                new AppSettingsReader();
            // Get the key from config file

            string key = (string)settingsReader.GetValue("SecurityKey",
                                                             typeof(String));
            //System.Windows.Forms.MessageBox.Show(key);
            //If hashing use get hashcode regards to your key
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                //Always release the resources and flush data
                // of the Cryptographic service provide. Best Practice

                hashmd5.Clear();
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            //set the secret key for the tripleDES algorithm
            tdes.Key = keyArray;
            //mode of operation. there are other 4 modes.
            //We choose ECB(Electronic code Book)
            tdes.Mode = CipherMode.ECB;
            //padding mode(if any extra byte added)

            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            //transform the specified region of bytes array to resultArray
            byte[] resultArray =
              cTransform.TransformFinalBlock(toEncryptArray, 0,
              toEncryptArray.Length);
            //Release resources held by TripleDes Encryptor
            tdes.Clear();
            //Return the encrypted data into unreadable string format
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

     public static string Decrypt(string cipherString, bool useHashing)
        {
            byte[] keyArray;
            //get the byte code of the string

            byte[] toEncryptArray = Convert.FromBase64String(cipherString);

            System.Configuration.AppSettingsReader settingsReader =
                                                new AppSettingsReader();
            //Get your key from config file to open the lock!
            string key = (string)settingsReader.GetValue("SecurityKey",
                                                         typeof(String));

            if (useHashing)
            {
                //if hashing was used get the hash code with regards to your key
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                //release any resource held by the MD5CryptoServiceProvider

                hashmd5.Clear();
            }
            else
            {
                //if hashing was not implemented get the byte code of the key
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            //set the secret key for the tripleDES algorithm
            tdes.Key = keyArray;
            //mode of operation. there are other 4 modes. 
            //We choose ECB(Electronic code Book)

            tdes.Mode = CipherMode.ECB;
            //padding mode(if any extra byte added)
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(
                                 toEncryptArray, 0, toEncryptArray.Length);
            //Release resources held by TripleDes Encryptor                
            tdes.Clear();
            //return the Clear decrypted TEXT
            return UTF8Encoding.UTF8.GetString(resultArray);
        }


       }
}

Then we have to add this security key in our web.config in appSettings section. This can be any key that is referenced by our encrypt and decrypt function.

<appSettings>
    <add key ="SecurityKey" value ="1001101011000011" />
  </appSettings>

And here is how we use it in our page. We first add a reference to our SC.Utility namespace.

using SC.Utilit;

Then on the page where we append our query string, we can do the below code.

Response.Redirect("Products.aspx/" + Security.Encrypt("category=books,sender=franco.robles,subcategoryid=horror,pricerange=100-1000", true));

And on our destination page, we can do the below code.

Response.Write(Security.Decrypt(Request.PathInfo.Substring(1), true));

Here is how it looks like on the browser after the request.

Not quite elegant solution but we did it.

The Project Tracker

It’s been a long time since I havent created a blog about silverlight. Ill make this short since I have lots of things to do, not just silverlight. Today, I am going to show my latest addition to my projects “The Project Tracker”. This will show that silverlight is not just for media.

First Screen
The home screen. This window will list all the current user’s projects with Active Directory authentication.

Second Screen
The project creation screen. This window is where you save your current projects for tracking.

Third Screen
The project attachment screen. This window is where you attach supporting documents for your project.

Fourth Screen
The query screen. This window is where you will find the projects by you and your teammate and can be filtered via there status.

Fifth Screen
The history window. This window is where you will keep track of who commented or did something to your posted project.




Sixth Screen
The notification module. The highlighted object will slide up and stays for 5 seconds which acts like other notifications in the taskbar.

Now who said that silverlight is just for animations and other things. Lets make it simple and straight. If you want a rich interactive web application for your audience use Silverlight.