Thursday, 10 May 2012

Tibco Rendezvous (tibrv) C# .Net example

This is an example of broadcast messaging using TIBCO Rendezvous.

You can find more information about queue, dispatcher, transport and other rendezvous concepts in the TIBCO Rendezvous® Concepts pdf documentation.

Command Line:

Receiving messages

tibrvlisten –service <port> -network "<ip-address>" –daemon <port> "<subject>"
tibrvlisten –service <port> -network ";<multicast-ip-address>" –daemon <port> "<subject>"

tibrvlisten -service 7500 -network "192.168.xx.xxx" -daemon 7500 "ME.TEST"
tibrvlisten -service 7500 -network "192.168.xx.xxx" -daemon 7500 "ME.>"

Publishing messages

tibrvsend –service <port> -network "<ip-address>" –daemon <port> "<subject>" "<your-message>"

tibrvsend -service 7500 -network "192.168.xx.xxx" -daemon 7500 "ME.TEST" "Hello World"


Local Daemon Webpage

http://localhost:7580/


C# Example:

Add Reference to TIBCO.Rendezvous.dll

Receiver

class Receiver
{
    public void Run()
    {
        TIBCO.Rendezvous.Environment.Open();
        var subject = "ME.TEST";
        var network = "192.168.xx.xxx";
        var port = "7500";
        Transport transport = new NetTransport(port, network, port);
        Listener listener = new Listener(
                Queue.Default,
                transport,
                subject,
                new object()
                );
        listener.MessageReceived += new MessageReceivedEventHandler(listener_MessageReceived);
        var dispacher = new Dispatcher(listener.Queue);
        dispacher.Join();
        Console.WriteLine("Client running..");
        Console.ReadKey();
        TIBCO.Rendezvous.Environment.Close();
    }
    void listener_MessageReceived(object listener, MessageReceivedEventArgs messageReceivedEventArgs)
    {
        Console.WriteLine(messageReceivedEventArgs.Message.GetField("Test").Value);
    }
    static void Main(string[] args)
    {
        new Receiver().Run();
    }
}

Publisher

class Publisher
{
    public void Run()
    {
        TIBCO.Rendezvous.Environment.Open();
        var subject = "ME.TEST";
        var network = "192.168.xx.xxx";
        var port = "7500";
        var transport = new NetTransport(port, network, port);
        Console.WriteLine("Server running..");
        Console.WriteLine("Press x to exit or any other key to send message");
        while (true)
        {
            var m = new Message();
            m.SendSubject = subject;
            m.AddField("Test", "TestValue");
            transport.Send(m);
            var line = Console.ReadLine();
            if (line.ToUpper().Equals("X")) break;
        }
        TIBCO.Rendezvous.Environment.Close();
    }
    static void Main(string[] args)
    {
        new Publisher().Run();
    }
}

Wednesday, 2 May 2012

Using Task and WebRequest to asynchronously call RESTful service

Threading in C# is a good website describing Task Parallelism and other aspects of C# Threading.

[Test]
//For GET/POST/PUT/DELETE calls
public void TestWebRequest()
{
    Task<string> task = Task.Factory.StartNew<string>(() => // Begin task
    {
        var req = (HttpWebRequest)WebRequest.Create("http://localhost:52292/Api/Product/31a3653e-2db0-429e-8cfb-8842bd984b69");
        req.Method = "GET"; //POST/PUT/DELETE
        using (var response = (HttpWebResponse)req.GetResponse())
        {
            if (response.ContentLength > 0)
            {
                var reader = new StreamReader(response.GetResponseStream());
                return reader.ReadToEnd();
            }
        }
        return null;
    });
    Console.WriteLine("Do something else..");
    //wait for Task Result
    string result = task.Result;
    Console.WriteLine("Completed..");
    Console.WriteLine(result);
}
[Test]
//this is only for GET calls
public void TestWebClient()
{
    Task<string> task = Task.Factory.StartNew<string>(() => // Begin task
    {
        using (var wc = new WebClient())
            return
                wc.DownloadString("http://localhost:52292/Api/Product/31a3653e-2db0-429e-8cfb-8842bd984b69");
    });
    Console.WriteLine("Do something else..");
    //wait for Task Result
    string result = task.Result;
    Console.WriteLine("Completed..");
    Console.WriteLine(result);
}

C# reflection based simple ObjectMapper

public class ObjectMapper
{
    public static object Map(object from, Func<PropertyInfo, bool> ignore)
    {
        return Map(from, null, ignore);
    }
    public static object Map(object from, object to, Func<PropertyInfo, bool> ignore)
    {
        if(from==null) throw new ArgumentException("NULL value","from");
        if (to == null)
        {
            to = Activator.CreateInstance(from.GetType());
        }
        Type type = from.GetType();
        var properties = type.GetProperties();
        foreach (var property in properties)
        {
            if (ignore==null || !ignore(property))
            {
                if(property.GetSetMethod()!=null)
                    property.SetValue(to, property.GetValue(from, null), null);
            }
        }
        return to;
    }
}
And an example of ignore method implementation to not map properties annotated with Association attribute (from Linq2Sql)
public static bool IgnoreAssociations(PropertyInfo property)
{
    if (Attribute.GetCustomAttribute(property, typeof(AssociationAttribute)) != null)
    {
        return true;
    }
    return false;
}

C# JSON Serializer

Add Reference to System.Web.Extensions

[Test]
public void Test()
{
    var serializer = new JavaScriptSerializer();
    var input = new SerializationTest() { Id = 1 };
    var text = serializer.Serialize(input);
    Console.WriteLine(text);
    var output = serializer.Deserialize<SerializationTest>(text);
    Console.WriteLine("Id: {0}", output.Id);
}
class SerializationTest
{
    public int Id { get; set; }
}

Tuesday, 1 May 2012

C# Addin framework, MEF Example (Managed Extensibility Framework)

Example of using MEF to dynamically load calculator object.

Create .Net 4.0 solution with the following projects (MEFExample is Console others are Libraries)
Add Reference to System.ComponentModel.Composition to Library projects.

image

public interface ICalculator
{
    string Name { get; }
    int Calculate(int a, int b);
}
public class CalculatorManager
{
    [ImportMany(typeof(ICalculator))]
    private IEnumerable<ICalculator> _calculators;
    public IEnumerable<ICalculator> GetCalculators()
    {
        var catalog = new AggregateCatalog();            
        catalog.Catalogs.Add(new DirectoryCatalog(@".\extensions\"));
        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);
        Console.WriteLine("Found {0} Calculators", _calculators.Count());
        return _calculators;
    }
}
[Export(typeof(ICalculator))]
public class CalculatorAdd : ICalculator
{        
    public string Name
    {
        get { return "Mul a & b"; }
    }
    public int Calculate(int a, int b)
    {
        return a * b;
    }        
}
[Export(typeof(ICalculator))]
public class Calculator : ICalculator
{
    public string Name
    {
        get { return "Add a & b"; }
    }
    public int Calculate(int a, int b)
    {
        return a + b;
    }
}
public class MEFExample
{
    public static void Main(string[] args)
    {
        var calculators = new CalculatorManager().GetCalculators();
        foreach (var calculator in calculators)
        {
            Console.WriteLine("Calculator: {0}(1,2): {1}", calculator.Name, calculator.Calculate(1, 2));
        }
    }
}
To test the code copy the compiled dlls to new folder with extensions subfolder.
/extensions
/extensions/MEFLib1.dll
/extensions/MEFLib2.dll
/MEFExample.exe
/MEFLib.dll

and run MEFExample.exe

image