Sunday, July 14, 2013

PetaPoco as it's meant to be; with repository and fluent mappings

When your domain objects get decorated with DataLayer column mappings, you create an unwanted dependency with your DayaLayer. To prevent this, you can create a mapping. This blog describes how I've done it. Comments are always welcome in the comment section below.

In the recently updated PetaPoco for Informix, I've created a FluentMapper. With this you can create a mapping of your domain object, without decorating them.

Here's how you can also benefit from this seperation. First create the domain object (DO):
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Revenue { get;set; }
}
Followed by the mapper of the DO
public class CustomerMapper : FluentMapper<Customer>
{
    public CustomerMapper() : base("tblCustomer", "CustomerId")
    {
        this.Property(a=>a.Id, "CustomerId")
            .Property(a=>a.Name, "CustomerName")
            .Property(a=>a.Revenue, "Revenue", fromDbValue=>(int)fromDbValue / 10d, toDbValue => (int)((double)toDbValue * 10));
    }
}
Once the mapper is in place, we want to make sure we hook it up every time. This is why I make a DataContext class (which is used in the repository):
public class MyDataContext : Database
{
    //Because the PetaPoco.Mappers is static, we also hook up our mappers static
    static MyDataContext()
    {
        PetaPoco.Mappers.Register(typeof(Customer), new CustomerMapper());
    }
    public MyDataContext()
        : base(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
    {
        
    }
}
Now we can create the repository for the customer related DataLayer functions (CRUD operations):
public class CustomerRepository
{
    private MyDataContext _dataContext
    public CustomerRepository(MyDataContext dataConext)
    {
        _dataContext = dataConext;
    }

    public Customer GetById(int customerId)
    {
        _dataContext.Get<Customer>(customerId);
    }

    public void Update(Customer customer)
    {
        _dataContext.Update(customer);
    }

    // etc
}
We can use it all together in the following way:
using(var dataContext = new MyDataContext())
{
    var customerRepository = new CustomerRepository(dataContext);
    var customer = customerRepository.GetById(1234);
}
As you can see the usage of the repository is super clean. Nobody knows where the data comes from, and nobody cares.

Let me know what you think of this solution!

Cheers,
Luuk

Friday, July 12, 2013

Introducing PetaPoco for Informix

I've created a fork of PetaPoco, with support for Informix and named parameters. I've also added multiple key support.

The code is available on GitHub.

An example:
[TableName("ship")]
public class Ship
{
    [PrimaryKey]
    [Column("shipid")]
    public int Id { get; set; }

    [Column("name")]
    public string Name { get; set; }
}

[TableName("positionlog")]
public class PositionLog
{
    [PrimaryKey]
    [Column("shipid")]
    public int ShipId { get; set; }

    [PrimaryKey]
    [Column("epochdate")]
    public int EpochDate { get; set; }

    [Column("lat")]
    public int Latitude {get;set;}

    [Column("lon")]
    public int Longitude {get;set;}
}

var db = new Database(new IfxConnection("<ConnectionString>");
int shipId = 1234;
var ship = db.Query<Ship>("select first 1 * from ship where shipid = @id", new { id = shipId }).FirstOrDefault();

ship.Name = "Submarine";

db.Update(ship);

The code will be updated with support of more features as we move along with our project (which uses Informix).

Cheers,
Luuk

Monday, July 1, 2013

Looping through your e-mails with outlook interop with c#

Last week we needed a small tool that checked the body of an e-mail. I found out that it only takes a couple of lines using Outlook Interop to do so. Super fast, super easy:
using System;
using Microsoft.Office.Interop.Outlook;

namespace OutlookReader
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Office.Interop.Outlook.Application app = null;
            Microsoft.Office.Interop.Outlook._NameSpace ns = null;
            Microsoft.Office.Interop.Outlook.MailItem item = null;
            Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
            Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;

            try
            {
                app = new Application();
                ns = app.GetNamespace("MAPI");
                ns.Logon(null, null, false, false);

                inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
                subFolder = inboxFolder; // or use folder.Folders["Folder Name"];

                Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name, subFolder.EntryID);
                Console.WriteLine("Num Items: {0}", subFolder.Items.Count.ToString());

                for (int i = 1; i <= subFolder.Items.Count; i++)
                {
                    item = (MailItem)subFolder.Items[i];
                    Console.WriteLine("Subject: {0}", item.Subject);
                }
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                ns = null;
                app = null;
                inboxFolder = null;
            }
        }
    }
}
This only works with outlook installed, so if you want to use it on your server, you'll have to install outlook. Does anybody know any other good way to access mail without the native MAPI32?

Cheers,
Luuk

Tuesday, June 4, 2013

Beyond Compare is Beyond Awesome with Source Control Integration

Just found out the Source Control Integration with Beyond Compare Pro, this is awesome! First install the TFS  SCC provider and click on Tools -> Source Controls Integration.


Now see a window where you can add the same folders as your mapped TFS workspaces. But when you now start to compare, merge or edit a file which is checked in, you get the following popup:


Nice, isn't it? So now you don't have to go to VS to checkout the item manually and this works a lot faster!

Cheers,
Luuk

Tuesday, May 28, 2013

Manager for the Service Bus for Windows Server

I'm currently working on a manager for the Service Bus for Windows Server.

The purpose of the manager is that you can simply view which queues are currently available on the server and which users have access rights on them. Because I don't want to do this in the workers who are actually using the service bus. It is build in VS2012 with the help of caliburn micro and mahapps for the nice metro look.

Things that need to be done include the update of currently running queues and peek into messages from the queue. The source code is fully available on GitHub and here is what it currently looks like:



There are currently no good managers for the service bus so I have the inspiration to make this one the starting point for managing and understanding the service bus.

When there are any updates on this I'll let you know.

Cheers,

Luuk

Saturday, May 11, 2013

Monitor your Server IP with Python and Pushover

Since I'm running my own web / plex server, I want to be notified when my public IP changes. This is super-easy using python and pushover.

The base of the application is really simple; fetch the IP from http://checkip.dyndns.org/ and check if it's the same as the last time you've runned. If it has changed, send a message with pushover to your mobile phone.

I use crontab every 5 minutes to validate the IP.


Here's the script:

import re
import os
import uuid
import json
import socket
import urllib, urllib2
import time

def get_current_ip():
    req = urllib2.Request('http://checkip.dyndns.org/')
    response = urllib2.urlopen(req)
    the_page = response.read()

    p = re.compile(r'(?P >ip<(?:[0-9]{1,3}\.){3}[0-9]{1,3})')
    m = p.search(the_page)
    return m.group('ip')

# load settings
current_ip = get_current_ip()
uid = ''
computer_name = ''
last_ip = ''

if(os.path.exists('/srv/crontab/oswos.settings')):
    with open('/srv/crontab/oswos.settings', 'r') as f:
        content = f.read()
        decoded = json.loads(content)
        uid = decoded.get('guid')
        computer_name = decoded.get('computer_name')
        last_ip = decoded.get('last_ip')
else:
    uid = str(uuid.uuid1())
    computer_name = socket.gethostname()

data = { 'guid': uid, 'computer_name': computer_name, 'last_ip': current_ip }
with open('/srv/crontab/oswos.settings', 'w') as f:
    json.dump(data, f)

print 'uid          : {0}'.format(uid)
print 'computer_name: {0}'.format(computer_name)
print 'last_ip      : {0}'.format(last_ip)
print 'current ip   : {0}'.format(current_ip)

if(current_ip != last_ip):
    API_URL = "https://api.pushover.net/1/messages.json"
    API_KEY = "api-key-here"
    curUrl = API_URL

    data = urllib.urlencode({
        'token': API_KEY,
        'title': 'Oswos Notification',
        'user': 'user-key-here',
        'message': 'IP Changed from {0} to {1}'.format(last_ip,current_ip).encode('utf-8'),
        'timestamp': int(time.time())
            })

    req = urllib2.Request(curUrl)
    handle = urllib2.urlopen(req, data)
    handle.close()

You see how easy it is to connect to Pushover? Building your own good working Android application is hard, so why not use the tools which are already there!

Just let me know if you have any tips / suggestions to extend this further.

Luuk

Monday, April 29, 2013

Installing the magic 4; Debian, Transmission, SickBeard, and Plex (part 3)

This serie of blog posts will cover the installation of Debian, Transmission, Sickbeard and Plex.

Part 1: Installation of Debian and Transmission
Part 2: Installation of Sickbeard and Plex
Part 3: Configuration

The final step is to configure it all. Transmission was already configured with the settings file, but Sickbeard and Plex need to be configured on their web-portal.

But first we need to determine where to store our library. In our case we'll store it under /var/lib/sickbeard:
$ sudo mkdir /var/lib/sickbeard
$ sudo chmod 666 /var/lib/sickbeard
Now we can setup sickbeard to automatically download the shows we add later. Enabled the Torrent Search in the Search Settings:


Select EZBB in the Search Providers:

 And Scan and process in the Post Processing settings:

Now we're ready to add shows. Just follow the wizard and make sure the root directory is /var/lib/sickbeard.

At last but not least add the TV-shows directory to Plex and let sickbeard connect to plex when a download is finished:


Now install Plex clients on all possible devices you have laying around and starts streaming like a maniac!

Please let me know in the comments if you have encounter any problems or if you need help with the setup.

Cheers,
Luuk