johnllao

September 22, 2011

Javascript OOP Pattern Inspired By JQuery

Filed under: Uncategorized — johnllao @ 3:41 pm

I was looking at the JQuery and SignalIR sourcecode and I can say the I was intrigued by how they implemented a OOP Pattern. so I created my own simple object to show this

var Andromeda = (function() {
    // Factory method
    var Andromeda = function () {
        return new Andromeda.fn.init();
    }

    Andromeda.fn = {
        // Constructor
        init : function() {

        },

        property : 0,

        method : function() {
            var me = this;
            alert(me.property);
        }
    };

    Andromeda.fn.init.prototype = Andromeda.fn;

    return Andromeda;
}());

To call methods

 

var a = Andromeda();
a.property = 1;
a.method();

var b = Andromeda();
b.property = 2;
b.method();

Happy coding…

September 21, 2011

Registry Tricks

Filed under: Uncategorized — johnllao @ 2:42 pm

 

Enable / Disable Add Remove Windows Components

 

HKLM > Software > Microsoft > Windows > CurrentVersion > Policies > Uninstall

NoWindowsSetupPage = 0

Enable IE Advance Tab

HKCU > Software > Policies > Microsoft > Internet Explorer > Control Panel

August 9, 2011

Calling WCF Service using JQuery

Filed under: Uncategorized — johnllao @ 8:31 pm

In this post I will document a simple application to call a WCF service using JQuery. To make this happens I used the following definition in the .svc markup

<%@ ServiceHost Language="C#" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" Service="Guava.Server.Web.Services.GuavaService" %>

In the above code I used WebScriptServiceHostFactory, in this way it enables some configurations to allow the service to be called by AJAX. Alternative implementation is setting the configuration to enable web script behavior.

The following code defines my service

[ServiceContract(Namespace = "http://guava", Name = "GuavaService")]
public interface IGuavaService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
               BodyStyle = WebMessageBodyStyle.WrappedRequest,
               RequestFormat = WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json)]
    void Execute(string name);

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string Version(string name);
}

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class GuavaService : IGuavaService
{
    public void Execute(string name)
    {

    }

    public string Version(string name)
    {
        return "1.0";
    }
}

The AspNetCompatibilityRequirements attributes ensures compatibility with AJAX calls.

To allow GET methods define the method with the WebGet attribute.

To allow POST methos define the method with the following attribute

    [WebInvoke(Method = "POST",
               BodyStyle = WebMessageBodyStyle.WrappedRequest,
               RequestFormat = WebMessageFormat.Json,
               ResponseFormat = WebMessageFormat.Json)]

From the above code the BodyStyle must be defines as WrappedRequest

The following code shows my JQuery call

 

    function OnError(jqXHR, textStatus, errorThrown) {
        if (jqXHR.textStatus === 'error') {

        }
    }

    function OnVersionCompleted(data, textStatus, jqXHR) {
        alert(data.d);
    }

    function OnVersion() {
        $.getJSON('Services/GuavaService.svc/Version?name=John', {}, OnVersionCompleted);
    }

    function OnExecuteCompleted(data, textStatus, jqXHR) {
        alert('OnExecuteCompleted');
    }

    function OnExecute() {
        $.ajax({
            url: 'Services/GuavaService.svc/Execute',
            type: 'POST',
            data: '{ "name" : "John" }',
            dataType: 'json',
            contentType: 'application/json',
            success: OnExecuteCompleted,
            error: OnError
        });
    }

For the POST method it is important to express your data as Json string format.

May 24, 2011

Using Unity Dependency Injection in WebFormsMVP

Filed under: Uncategorized — johnllao @ 8:45 am

As I was preparing a POC for my new project, I stumble upon an idea of using dependency injection / IOC. This is to facilitate the property injection to my Repository or Service classes. Here is the snapshot of the code

Global.asax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Monday.Data;
using Monday.Data.Repositories;
using WebFormsMvp.Binder;
using WebFormsMvp.Unity;

namespace Monday
{
    public class Global : System.Web.HttpApplication
    {
        private readonly IUnityContainer _container;

        public Global()
            : base()
        {
            _container = new UnityContainer();
        }

        void Application_Start(object sender, EventArgs e)
        {
            _container.RegisterInstance<MondayEntities>(
                new MondayEntities(),
                new ContainerControlledLifetimeManager());

            _container.RegisterType<ICountryRepository, CountryRepository>(
                new ContainerControlledLifetimeManager());

            UnityServiceLocator locator = new UnityServiceLocator(_container);
            ServiceLocator.SetLocatorProvider(() => locator);

            PresenterBinder.Factory = new UnityPresenterFactory(_container);

        }

The implementation of the Unity is pretty normal except that I use the ServiceLocator to encapsulate calls to the UnityContainer. Developers may get instance using the following code.

ICountryRepository repo =
    ServiceLocator.Current.GetInstance<ICountryRepository>();

As for codes that want to utilize Property Injection they can implement it in the following way

public class CountryScriptPresenter : Presenter<ICountryScriptView>
{
    private ICountryScriptView _view;

    public CountryScriptPresenter(ICountryScriptView view)
        : base(view)
    {
        _view = view;
        _view.Load += new EventHandler(OnLoad);
    }

    [Dependency]
    public ICountryRepository CountrySource { get; set; }

    private void OnLoad(object sender, EventArgs e)
    {

        if (CountrySource == null)
            throw new ApplicationException("CountryRepository is null or not defined.");

        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);

        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(sw, CountrySource.GetList());

        _view.Model.List = sb.ToString(); ;
    }
}

The Dependency attribute will handle the injection of the object

May 9, 2011

Dynamic JavaScript in ASP.NET

Filed under: Uncategorized — johnllao @ 11:53 pm

As I was preparing some Proof-of-Concept for my new ASP.NET Webforms projects, I came across an idea of using a dynamic JavaScript. Here how it goes.

Let say I want to generate the following javascript dynamically

var currencyManager = function() {
    var _currencyManager = function() {
        this.list = [
            {cur:'EUR',rate:0.69996},
            {cur:'GBP',rate:0.61304},
            {cur:'AUD',rate:0.93141}];
    }

    _currencyManager.prototype = {
        getRate : function(currency) {
            var rate = 0;
            for (var i = 0; i < this.list.length; i++) {
                if (this.list[i].cur === currency) {
                    rate = this.list[i].rate;
                    break;
                }
            }
            return rate;
        }
    }

    return new _currencyManager();
}();

From the above code, I want the list of currencies to be dynamic as I want my users to get the latest rates from our database

To implement this I created a Generic Script Handler (.ashx). The code will be similar to this one

public class CurrencyScriptHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context == null)
            throw new NullReferenceException("context is null or not defined");

        if (context.Response == null)
            throw new NullReferenceException("context.Response is null or not defined");

        HttpResponse response = context.Response;

        StringBuilder stringBuilder = new StringBuilder();
        StringWriter textWriter = new StringWriter(stringBuilder);
        HtmlTextWriter htmlWriter = new HtmlTextWriter(textWriter);

        Page page = new Page();
        Control control = page.LoadControl("Scripts/CurrencyScriptControl.ascx");
        page.Controls.Add(control);
        HttpContext.Server.Execute(page, textWriter, false);

        response.ContentType = "text/javascript";
        response.Write(stringBuilder.ToString());
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

As you may notice I am just rendering a User Control and setting the ContentType to “text/javascript”. The Control CurrencyScriptControl.ascx will contain the code to generate this javascript.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CurrencyScriptControl.ascx.cs" Inherits="Monday.Scripts.CurrencyScriptControl" %>
var currencyManager = function() {
    var _currencyManager = function() {
        this.list = <%= CurrencyListJson %>;
    }

    _currencyManager.prototype = {
        getRate : function(currency) {
            var rate = 0;
            for (var i = 0; i < this.list.length; i++) {
                if (this.list[i].cur === currency) {
                    rate = this.list[i].rate;
                    break;
                }
            }
            return rate;
        }
    }

    return new _currencyManager();
}();

The CurrencyListJson can be a protected property of your ascx control

public partial class CurrencyScriptControl : System.Web.UI.UserControl
{
    protected string CurrencyListJson ;

    protected void Page_Load(object sender, EventArgs e)
    {
        CurrencyScriptControl = CurrencyListJson();
    }

    private string CurrencyListJson()
    {
        // Call you business objects here and JSON serilizer.
    }
}

We may now call this script into our page like this

<script type="text/javascript" src="Scripts/CurrencyScriptHandler.ashx"></script>

October 22, 2010

Manual NServiceBus Configuration

Filed under: Uncategorized — johnllao @ 5:12 pm

In my previous post I have shown a simple implementation of Publish / Subscribe messages using the NServiceBus. We may notice from the example provided that to run the Service Bus we executed configuration through a series of extesion methods supplied.

Bus = Configure.With().DefaultBuilder().BinarySerializer()
         .MsmqTransport().IsTransactional(true).PurgeOnStartup(false)
         .UnicastBus().ImpersonateSender(false).LoadMessageHandlers()
         .CreateBus()
         .Start();

I managed to explore more and look into how each extension methods are performing the configuration. Here is what I discovered.

Configure config = Configure.With();

// Setting the DefaultBuilder
IContainer container = new SpringObjectBuilder();
CommonObjectBuilder b = new CommonObjectBuilder { Container = container, Synchronized = SyncConfig.Synchronize };
config.Builder = b;
config.Configurer = b;
config.Configurer.ConfigureComponent<CommonObjectBuilder>(ComponentCallModelEnum.Singleton)
    .ConfigureProperty(c => c.Container, container);
SyncConfig.MarkConfigured();

// Setting the Serialization
config.Configurer.ConfigureComponent<SimpleMessageMapper>(ComponentCallModelEnum.Singleton);
config.Configurer.ConfigureComponent(typeof(MessageSerializer), ComponentCallModelEnum.Singleton);

// Setting MSMQ Transport
ConfigMsmqTransport transportCfg = new ConfigMsmqTransport();
transportCfg.Configure(config);
transportCfg.IsTransactional(true);
transportCfg.PurgeOnStartup(false);

// Setting the Unicast Bus
ConfigUnicastBus unicastCfg = new ConfigUnicastBus();
unicastCfg.Configure(config);
unicastCfg.ImpersonateSender(true);
unicastCfg.LoadMessageHandlers();

// Creating the Bus
IStartableBus startableBus = config.CreateBus();

// Staring the Bus
Bus = startableBus.Start();

Digging further into the details we can slice the MSMQ configuration using the following code.

IComponentConfig<MsmqTransport> transportCfg = config.Configurer.ConfigureComponent<MsmqTransport>(ComponentCallModelEnum.Singleton);
MsmqTransportConfig msmqTransportCfg = Configure.GetConfigSection<MsmqTransportConfig>();
if (msmqTransportCfg != null)
{
    transportCfg.ConfigureProperty(t => t.InputQueue, msmqTransportCfg.InputQueue);
    transportCfg.ConfigureProperty(t => t.NumberOfWorkerThreads, msmqTransportCfg.NumberOfWorkerThreads);
    transportCfg.ConfigureProperty(t => t.ErrorQueue, msmqTransportCfg.ErrorQueue);
    transportCfg.ConfigureProperty(t => t.MaxRetries, msmqTransportCfg.MaxRetries);
    transportCfg.ConfigureProperty(t => t.IsTransactional, true);
    transportCfg.ConfigureProperty(t => t.PurgeOnStartup, false);
}

The Unicast settings can be further broken into the following code

IComponentConfig<UnicastBus> unicastCfg = config.Configurer.ConfigureComponent<UnicastBus>(ComponentCallModelEnum.Singleton);
Type authType = Configure.TypesToScan.Where(t => typeof(IAuthorizeSubscriptions).IsAssignableFrom(t) && !t.IsInterface).FirstOrDefault();
if (authType != null)
    config.Configurer.ConfigureComponent(authType, ComponentCallModelEnum.Singleton);
Configure.TypesToScan.Where(t => typeof(IMessageModule).IsAssignableFrom(t) && !t.IsInterface).ToList().ForEach(
        type => config.Configurer.ConfigureComponent(type, ComponentCallModelEnum.Singleton)
    );
UnicastBusConfig unicastBusCfg = Configure.GetConfigSection<UnicastBusConfig>();
if (unicastBusCfg != null)
{
    Hashtable assembliesToEndpoints = new Hashtable();
    Configure.TypesToScan.Where(t => typeof(IMessage).IsAssignableFrom(t)).ToList().ForEach(
            t => assembliesToEndpoints[t.Assembly.GetName().Name] = string.Empty
        );

    foreach (MessageEndpointMapping mapping in unicastBusCfg.MessageEndpointMappings)
        assembliesToEndpoints[mapping.Messages] = mapping.Endpoint;

    unicastCfg.ConfigureProperty(ub => ub.DistributorControlAddress, unicastBusCfg.DistributorControlAddress);
    unicastCfg.ConfigureProperty(ub => ub.DistributorDataAddress, unicastBusCfg.DistributorDataAddress);
    unicastCfg.ConfigureProperty(ub => ub.ForwardReceivedMessagesTo, unicastBusCfg.ForwardReceivedMessagesTo);
    unicastCfg.ConfigureProperty(ub => ub.MessageOwners, assembliesToEndpoints);
    unicastCfg.ConfigureProperty(ub => ub.ImpersonateSender, true);

    List<Type> handlers = new List<Type>();

    foreach (Type t in Configure.TypesToScan)
        if (IsMessageHandler(t))
        {
            config.Configurer.ConfigureComponent(t, ComponentCallModelEnum.Singlecall);
            handlers.Add(t);
        }

    unicastCfg.ConfigureProperty(ub => ub.MessageHandlerTypes, handlers);
}

Helper methods I used in this example

/// <summary>
/// Returns true if the given type is a message handler.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static bool IsMessageHandler(Type t)
{
    if (t.IsAbstract)
        return false;

    if (typeof(ISaga).IsAssignableFrom(t))
        return false;

    foreach (Type interfaceType in t.GetInterfaces())
    {
        Type messageType = GetMessageTypeFromMessageHandler(interfaceType);
        if (messageType != null)
            return true;
    }

    return false;
}

/// <summary>
/// Returns the message type handled by the given message handler type.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static Type GetMessageTypeFromMessageHandler(Type t)
{
    if (t.IsGenericType)
    {
        Type[] args = t.GetGenericArguments();
        if (args.Length != 1)
            return null;

        if (!typeof(IMessage).IsAssignableFrom(args[0]))
            return null;

        Type handlerType = typeof(IMessageHandler<>).MakeGenericType(args[0]);
        if (handlerType.IsAssignableFrom(t))
            return args[0];
    }

    return null;
}

October 15, 2010

Simple MassTransit ServiceBus Sample

Filed under: Uncategorized — johnllao @ 1:28 pm

Following my post on NServiceBus, here I will show you how to get up to speed with MassTransit. Using a similar scenario with NServiceBus.

One thisng I observed withe MassTransit is it is the initialization of the service is dependent on the Dependency Injection framework. when you download the library it provides you with several choice like using Castle, Unity, Ninject, StructureMap. In this sample I will be using the StructureMap.

To begin, we need to create a class that inherits from MassTransitRegistryBase, this is only applicable if you are using StructureMap and your DI. This class contains the necessary initialization of your MassTransitService.

using MassTransit.Configuration;
using MassTransit.Services.Routing.Configuration;
using MassTransit.StructureMapIntegration;
using MassTransit.Transports.Msmq;

namespace Relativity
{
    /// <summary>
    /// 
    /// </summary>
    public class ServiceBusRegistry : MassTransitRegistryBase
    {
        /// <summary>
        /// 
        /// </summary>
        public const string MQPATH = "msmq://localhost/relativity";

        /// <summary>
        /// 
        /// </summary>
        public ServiceBusRegistry()
            : base(typeof(MsmqEndpoint))
        {
            RegisterServiceBus(MQPATH, ConfigHandler);

            MsmqEndpointConfigurator.Defaults(config => { config.CreateMissingQueues = true; });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        private void ConfigHandler(IServiceBusConfigurator e)
        {
            //e.ConfigureService<RoutingConfigurator>(rs => rs.Route<RelativityMessage>().To(MQPATH));
            //e.ConfigureService<RoutingConfigurator>(rs => rs.Route<RelativityResponseMessage>().To(MQPATH));
        }
    }
}

After this has been defined, you may now get the instance of the Bus using the MassTransit Container.

using MassTransit;
using StructureMap;
using System;
using System.Linq;
using System.Windows;

namespace Relativity
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private Container _container;
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IServiceBus GetServiceBus()
        {
            if (_container == null)
                throw new NullReferenceException("Service has not properly initialized");
            return _container.GetInstance<IServiceBus>();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            _container = new Container(ConfigHandler);

            IServiceBus bus = GetServiceBus();
            bus.Subscribe<RelativityMessage>(RelativityMessageConsumer);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        private void ConfigHandler(ConfigurationExpression e)
        {
            e.AddRegistry(new ServiceBusRegistry());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        public static void RelativityMessageConsumer(RelativityMessage message)
        {
            //System.Threading.Thread.Sleep(3000);
            App app = Application.Current as App;
            if (app == null)
                throw new NullReferenceException("Service has not properly initialized");

            IServiceBus bus = app.GetServiceBus();
            bus.Publish<RelativityResponseMessage>(new RelativityResponseMessage() { Text = message.Text + " Acknowledged!" });
        }
    }
}

To publish / subscribe messages

using MassTransit;
using System;
using System.Windows;

namespace Relativity
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            App app = Application.Current as App;
            if (app == null)
                throw new NullReferenceException("Service has not properly initialized");

            IServiceBus bus = app.GetServiceBus();
            bus.Subscribe<RelativityResponseMessage>(RelativityResponseMessageConsumer);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Send(object sender, RoutedEventArgs e)
        {
            App app = Application.Current as App;
            if (app == null)
                throw new NullReferenceException("Service has not properly initialized");

            IServiceBus bus = app.GetServiceBus();
            bus.Publish<RelativityMessage>(new RelativityMessage() { Text = "Hello world!" });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        private void RelativityResponseMessageConsumer(RelativityResponseMessage message)
        {
            MessageBox.Show(message.Text);
        }
    }
}

That’s it

Simple NServiceBus Sample

Filed under: Uncategorized — johnllao @ 12:57 pm

I have been exploring Service Bus in the past few days as I am very well impressed how reliable messaging is being handled. the first challenge that I encounter is being able to create a simple application that demontrate how it works.

I have seen the NServiceBus and MassTransit examples from their respective sites however I find the sample pretty difficult to digest. So after few hours of exploring I came up wih a simple example to make things work.

In this post I will show how a simple Publish and Subscribe messages work with NServiceBus. I have created a simple WPF window application that hosts the NServiceBus service in itself.

First let us start with the configuration.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
    <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
  </configSections>

  <!-- in order to configure remote endpoints use the format:
       "queue@machine" 
  -->

  <MsmqTransportConfig
    InputQueue="IonInputQueue"
    ErrorQueue="IonErrorQueue"
    NumberOfWorkerThreads="5"
    MaxRetries="5"
  />

  <UnicastBusConfig>
    <MessageEndpointMappings>
      <add Messages="IonMessages" Endpoint="IonInputQueue" />
    </MessageEndpointMappings>
  </UnicastBusConfig>

</configuration>

The MsmqTransportConfig tells the name of the queue (e.g. MSMQ) that NServiceBus will use to publish and subscribe.

The UnicastBusConfig tells about the message endpoints you will be used to send messages. So what does that mean? It simple tells what type of Messages you want to send. Messages in NServiceBus are simply classes you create. The Messages attribute in the config tells the Assembly where you can find the Messages class.

So how do we create a Message, in NServiceBus you simply create a class that implements the IMessage interface. Here are the examples.

using NServiceBus;
using System;

namespace Ion.Messages
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class RequestMessage : IMessage
    {
        public Guid MessageId;
        public string Name;
    }
}

using NServiceBus;
using System;

namespace Ion.Messages
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class ResponseMessage : IMessage
    {
        public Guid MessageId;
        public Guid RequestMessageId;
        public string Status;
    }
}

Now we have the messages classes, next I will show you how to Publish and Subscribe to these messages. but before we go into that, we need to make the NServiceBus running, meaning listening and executing the messages that arrives in our queue. Here is the code that do that.

using Ion.Messages;
using NServiceBus;
using NServiceBus.Config;
using System;
using System.Windows;

namespace Ion.Windows.UI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static IBus Bus;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Bus = Configure.With().DefaultBuilder().BinarySerializer()
                .MsmqTransport().IsTransactional(true).PurgeOnStartup(false)
                //.MsmqSubscriptionStorage()
                .UnicastBus().ImpersonateSender(false).LoadMessageHandlers()
                .CreateBus()
                .Start();
        }
    }
}

The following code shows how to publish / subscribe to a message.

using Ion.Messages;
using NServiceBus;
using System;
using System.Windows;

namespace Ion.Windows.UI
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.Bus != null)
            {
                App.Bus.Subscribe<ResponseMessage>(MessageResponseHandler);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        private bool MessageResponseHandler(ResponseMessage m)
        {
            MessageBox.Show(m.Status + " - " + m.MessageId.ToString() + " - " + m.RequestMessageId);
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Send(object sender, RoutedEventArgs e)
        {
            if (App.Bus != null)
            {
                App.Bus.SendLocal<RequestMessage>(m =>
                {
                    m.MessageId = Guid.NewGuid();
                    m.Name = "John";
                });
            }
        }
    }
}

using Ion.Messages;
using NServiceBus;
using System;

namespace Ion.Windows.UI.MessageHandlers
{
    /// <summary>
    /// 
    /// </summary>
    public class RequestMessageHandler : IMessageHandler<RequestMessage>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        public void Handle(RequestMessage message)
        {
            if (App.Bus != null)
            {
                App.Bus.Reply<ResponseMessage>(m =>
                {
                    m.MessageId = Guid.NewGuid();
                    m.RequestMessageId = message.MessageId;
                    m.Status = "Completed";
                });
            }
        }
    }
}

You may notice that we created a class that implements the IMessageHandler, this class automatically handles the messages and implements action into it.

That’s it!

August 16, 2010

Using SQL string in Fluent NHibernate

Filed under: Uncategorized — johnllao @ 1:13 am

Sample code only shows how to execute a simple SQL string using Fluent NHibernate. Basically the method here will also work with Hibernate except that mapping will be on a .xml file.

First we have to create a the Entity and mapping class.

/// <summary>
/// 
/// </summary>
public class Planet
{
    private int _Id;
    /// <summary>
    /// 
    /// </summary>
    public virtual int Id
    {
        get { return _Id; }
        set { _Id = value; }
    }
    private string _Name;
    /// <summary>
    /// 
    /// </summary>
    public virtual string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
}

/// <summary>
/// 
/// </summary>
public class PlanetMap : ClassMap<Planet>
{
    /// <summary>
    /// 
    /// </summary>
    public PlanetMap()
    {
        Id(x => x.Id).Column("id");
        Map(x => x.Name).Column("name");
    }
}

Now lets go to the actual method.

/// <summary>
/// 
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
    ISessionFactory sessionFactory = Fluently
                .Configure()
                .Database(MySQLConfiguration.Standard.ConnectionString(GetConnectionString()))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
                .BuildSessionFactory();

    using (ISession session = sessionFactory.OpenSession())
    {
        // Executing sql string query
        ISQLQuery query = session.CreateSQLQuery("SELECT id, name FROM planet");

        // Getting result in a form of nested arrays
        Collection<Planet> planets = new Collection<Planet>();
        IList result = query.List();
        foreach(object[] item in result)
        {
            planets.Add(new Planet() { Id = (int) item[0], Name = (string) item[1] });
        }
    }

    Console.WriteLine("Press enter key to exit.");
    Console.ReadLine();
}

From the example above we used the ISQLQuery object to define and execute the query, please note that the result is in the form of a nested array of objects.

June 28, 2010

Simple Facebook WPF Application

Filed under: Uncategorized — johnllao @ 8:52 pm

On this blog I will show how to create a simple WPF application that connects to Facebook. In this sample it is assumed that you already acquired an Application ID from Facebook. If not please check this link http://developers.facebook.com/docs/.  The Application ID is one of the requirements to connect to Facebook.

To begin, download the Facebook toolkit from the this link http://facebooktoolkit.codeplex.com/ 

In you WPF application reference the following dlls:

  • Facebook.dll

Create the following class in your application:

/// <summary>
/// 
/// </summary>
public static class FacebookService
{
    private static DesktopSession _Session;
    /// <summary>
    /// 
    /// </summary>
    public static DesktopSession Session
    {
        get { return _Session; }
        set { _Session = value; }
    }
    private static BindingManager _Service;
    /// <summary>
    /// 
    /// </summary>
    public static BindingManager Service
    {
        get { return _Service; }
        set { _Service = value; }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="session"></param>
    public static void Init(DesktopSession session)
    {
        _Session = session;
        _Service = BindingManager.CreateInstance(_Session);
    }
}

The DesktopSession is a Facebook component from the toolkit that manage the connection and authentication to Facebook. To know more on how Facebook authenticates you application, check this link http://wiki.developers.facebook.com/index.php/How_Facebook_Authenticates_Your_Application

The BindingManager is another Facebook component that is reponsible retrieving friends list, photos and other information stored in a user’s profile.

To make this work, add the following code from the constructor of your WPF window:

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private FacebookModel _vm;
    /// <summary>
    /// 
    /// </summary>
    public MainWindow()
    {
        DesktopSession session = new DesktopSession("cd0ade267315e76b6e9d0b5855df7e98", true);
        session.Login();
        FacebookService.Init(session);

        InitializeComponent();

        _vm = new FacebookModel();
        Loaded += new RoutedEventHandler(MainWindow_Loaded);
        Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
    }

From the above code we use the DesktopSession to authenticate our applicatio to Facebook, when launching this application WPF will automatically redirects the application to a Facebook login page then returns back to our main window.

The following code shows the Facebook View Model that facilitates the retrieval of data from Facebook.

using Facebook.BindingHelper;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace MyFacebook.MainApplication.Model
{
    /// <summary>
    /// 
    /// </summary>
    public class FacebookModel : INotifyPropertyChanged
    {
        /// <summary>
        /// 
        /// </summary>
        public FacebookModel()
        {
            _Friends = FacebookService.Service.Friends;
            _Friends.DataRetrievalCompletedEvent += new System.EventHandler<DataRetrievalCompletedEventArgs>(Friends_DataRetrievalCompletedEvent);

            _Activities = FacebookService.Service.Stream;
            _Activities.DataRetrievalCompletedEvent += new System.EventHandler<DataRetrievalCompletedEventArgs>(Activities_DataRetrievalCompletedEvent);

            long user_id = FacebookService.Service.CurrentUserId;
            _CurrentUserList = FacebookService.Service.GetUsers(new long[] { user_id });
            _CurrentUserList.DataRetrievalCompletedEvent += new System.EventHandler<DataRetrievalCompletedEventArgs>(CurrentUser_DataRetrievalCompletedEvent);
        }

        #region Current User
        private FacebookContactCollection _CurrentUserList;
        private FacebookContact _CurrentUser;
        /// <summary>
        /// 
        /// </summary>
        public FacebookContact CurrentUser
        {
            get { return _CurrentUser; }
            set
            {
                if (_CurrentUser != value)
                {
                    _CurrentUser = value;
                    OnPropertyChanged("CurrentUser");
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CurrentUser_DataRetrievalCompletedEvent(object sender, DataRetrievalCompletedEventArgs e)
        {
            _CurrentUserList = sender as FacebookContactCollection;
            if (_CurrentUserList != null && _CurrentUserList.Count > 0)
            {
                CurrentUser = _CurrentUserList[0];
            }
        }
        #endregion

        #region Activities
        private ActivityPostCollection _Activities;
        /// <summary>
        /// 
        /// </summary>
        public ActivityPostCollection Activities
        {
            get { return _Activities; }
            set
            {
                if (_Activities != value)
                {
                    _Activities = value;
                    OnPropertyChanged("Activities");
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Activities_DataRetrievalCompletedEvent(object sender, DataRetrievalCompletedEventArgs e)
        {

        }
        #endregion

        #region Selected Friend
        private FacebookContact _SelectedFriend;
        /// <summary>
        /// 
        /// </summary>
        public FacebookContact SelectedFriend
        {
            get { return _SelectedFriend; }
            set
            {
                if (_SelectedFriend != value)
                {
                    _SelectedFriend = value;
                    SelectedFriendPhotos = _SelectedFriend.PhotosBy;
                    OnPropertyChanged("SelectedFriend");
                }
            }
        }

        private FacebookPhotoCollection _SelectedFriendPhotos;
        /// <summary>
        /// 
        /// </summary>
        public FacebookPhotoCollection SelectedFriendPhotos
        {
            get { return _SelectedFriendPhotos; }
            set
            {
                if (_SelectedFriendPhotos != value)
                {
                    _SelectedFriendPhotos = value;
                    OnPropertyChanged("SelectedFriendPhotos");
                }
            }
        }
        #endregion

        #region Friends
        private FacebookContactCollection _Friends;
        /// <summary>
        /// 
        /// </summary>
        public FacebookContactCollection Friends
        {
            get
            {
                return _Friends;
            }
            set
            {
                if (_Friends != value)
                {
                    _Friends = value;
                    OnPropertyChanged("Friends");
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Friends_DataRetrievalCompletedEvent(object sender, DataRetrievalCompletedEventArgs e)
        {

        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="propertyName"></param>
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

That’s it!

Older Posts »

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.