How To Unit Test A LINQPad Code Snippet

Writing code is a programmers life; sometimes it becomes necessary to write pieces of code that you can conveniently run and evaluate  without spinning up a full fledged IDE. For those tasks there is a tool called LINQPad. LINQPad allows you to write/run snippets in C#, SQL and a few other languages. In oder to run the example in this tutorial you will need to download LINQPad and NUnit Lite.

After installing LINQPad and NUnit Lite open an instance of LINQPad and change the language to C# Program.

linkp

Next hit the F4 key on you keyboard to bring up the additional references dialog and browse to the location where you installed NUnit Lite. You will need to add NUnit Lite as a reference.

addref

Copy preceding code into the LINQPad edit window then hit the run button, the results of the test will be displayed in the console window, enjoy :-)

void Main()
{
	new NUnitLite.Runner.TextUI().Execute(new[]{"-noheader"});
}


public class Dog
{	
	public string Howl()
	{		
		return "awhooo!";			
	}
	
	public string Growl() {return "Gerrrr!";}
}

[NUnit.Framework.TestFixture]
public class DogTest
{
	Dog fido;

	[NUnit.Framework.SetUp]
	public void init()
	{
		fido = new Dog();
	}
	
	[NUnit.Framework.Test]
	public void Howl()
	{
		NUnit.Framework.Assert.AreEqual(fido.Howl(), "awhooo!", ":-(");
	}
	
	[NUnit.Framework.TearDown]
	public void done()
	{
		fido = null;
	}
}

2013 in review

The WordPress.com stats helper monkeys prepared a 2013 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 37,000 times in 2013. If it were a concert at Sydney Opera House, it would take about 14 sold-out performances for that many people to see it.

Click here to see the complete report.

Cisco WebEx API v5.9 C# Integration Class

Example code for integrating with Cisco WebEx Meeting API, provided without warranty :)

using System;
using System.Data;
using System.Net.Mime;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;


public class ConnectWBX
{
    protected string _baseUrl;
    protected string _login;
    protected string _password;

    public enum Role
    {
        HOST,
        ATTENDEE,
        OTHER
    };

    public enum Type
    {
        MEMBER,
        VISITOR,
        PANELIST
    };

    public enum Active
    {
        ACTIVATED,
        REQUEST_TO_ACTIVATE,
        DEACTIVATED
    }

    public ConnectWBX(string baseUrl, string login, string password)
    {
        _baseUrl = baseUrl;
        _login = login;
        _password = password;
    }

    public void CreateUser(string firstName,
                        string lastName,
                        string webExId,
                        string email,
                        string password)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding.user.CreateUser\">")
            .AppendLine("<firstName>" + firstName + "</firstName>")
            .AppendLine("<lastName>" + lastName + "</lastName>")
            .AppendLine("<webExId>" + webExId + "</webExId>")
            .AppendLine("<email>" + email + "</email>")
            .AppendLine("<password>" + password + "</password>")
            .AppendLine("<privilege>")
            .AppendLine("<host>true</host>")
            .AppendLine("</privilege>")
            .AppendLine("<active>ACTIVATED</active>")
            .AppendLine("<sessionOptions>")
            .AppendLine("<autoDeleteAfterMeetingEnd>false</autoDeleteAfterMeetingEnd>")
            .AppendLine("</sessionOptions>")
            .AppendLine("</bodyContent>");

        Request(xmlAuthBodyContent);
    }

    public void SetUser(string firstName,
                       string lastName,
                       string webExId,
                       string email,
                       string password,
                       string host,
                       Active active,
                       string autoDelete)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding.user.SetUser\">")
            .AppendLine("<firstName>" + firstName + "</firstName>")
            .AppendLine("<lastName>" + lastName + "</lastName>")
            .AppendLine("<webExId>" + webExId + "</webExId>")
            .AppendLine("<email>" + email + "</email>")
            .AppendLine("<password>" + password + "</password>")
            .AppendLine("<privilege>")
            .AppendLine("<host>" + host + "</host>")
            .AppendLine("</privilege>")
            .AppendLine("<active>" + active.ToString() + "</active>")
            .AppendLine("<sessionOptions>")
            .AppendLine("<autoDeleteAfterMeetingEnd>" + autoDelete + "</autoDeleteAfterMeetingEnd>")
            .AppendLine("</sessionOptions>")
            .AppendLine("</bodyContent>");

        Request(xmlAuthBodyContent);
    }

    public void AuthenticateUser(string webExId)
    {
        var xmlAuthBodyContent = new StringBuilder()
                .AppendLine("<bodyContent ")
                .AppendLine("xsi:type=\"java:com.webex.service.binding.user.AuthenticateUser\">")
            //.AppendLine("<samlResponse><saml:Assertion>uid=" + webExId + "</saml:Assertion></samlResponse>")
                .AppendLine("</bodyContent>");

        Request(xmlAuthBodyContent);
    }

    
    public void DeleteUser(string webExId)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding.user.DelUser\">")
            .AppendLine("<webExId>" + webExId + "</webExId>")
            .AppendLine("<syncWebOffice>true</syncWebOffice>")
            .AppendLine("</bodyContent>");

        Request(xmlAuthBodyContent);
    }

  
    public string CreateMeeting(string name,
                            string password,
                            string start,
                            string duration)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding.meeting.CreateMeeting\">")
            .AppendLine("<accessControl>")
            .AppendLine("<meetingPassword>" + password + "</meetingPassword>")
            .AppendLine("</accessControl>")
            .AppendLine("<metaData>")
            .AppendLine("<confName>" + name + "</confName>")
            .AppendLine("<agenda>" + name + "</agenda>")
            .AppendLine("</metaData>")
            .AppendLine("<attendeeOptions>")
            .AppendLine("<emailInvitations>true</emailInvitations>")
            .AppendLine("<registration>true</registration>")
            .AppendLine("</attendeeOptions>")
            .AppendLine("<participants>")
            .AppendLine("<maxUserNumber>20</maxUserNumber>")
            .AppendLine("</participants>")
            .AppendLine("<enableOptions>")
            .AppendLine("<chat>true</chat>")
            .AppendLine("<poll>true</poll>")
            .AppendLine("<audioVideo>true</audioVideo>")
            .AppendLine("</enableOptions>")
            .AppendLine("<schedule>")
            .AppendLine("<startDate>" + start + "</startDate>")
            .AppendLine("<openTime>0</openTime>")
            .AppendLine("<joinTeleconfBeforeHost>FALSE</joinTeleconfBeforeHost>")
            .AppendLine("<duration>" + duration + "</duration>")
            .AppendLine("<timeZoneID>4</timeZoneID>")
            .AppendLine("</schedule>")
            .AppendLine("</bodyContent>");

       return Request(xmlAuthBodyContent).SelectSingleNode("//*[local-name()='meetingkey']").FirstChild.InnerText;
    }

    public void SetMeeting(string name,
                        string password,
                        string start,
                        string duration,
                        string meetingKey)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding.meeting.SetMeeting\">")
            .AppendLine("<accessControl>")
            .AppendLine("<meetingPassword>" + password + "</meetingPassword>")
            .AppendLine("</accessControl>")
            .AppendLine("<metaData>")
            .AppendLine("<confName>" + name + "</confName>")
            .AppendLine("<agenda>" + name + "</agenda>")
            .AppendLine("</metaData>")
            .AppendLine("<schedule>")
            .AppendLine("<startDate>" + start + "</startDate>")
            .AppendLine("<openTime>0</openTime>")
            .AppendLine("<joinTeleconfBeforeHost>FALSE</joinTeleconfBeforeHost>")
            .AppendLine("<duration>" + duration + "</duration>")
            .AppendLine("<timeZoneID>4</timeZoneID>")
            .AppendLine("</schedule>")
            .AppendLine("<meetingkey>" + meetingKey + "</meetingkey>")
            .AppendLine("</bodyContent>");

        Request(xmlAuthBodyContent);
    }

    public void DelMeeting(string meetingKey)
    {
        var xmlAuthBodyContent = new StringBuilder()
                .AppendLine("<bodyContent ")
                .AppendLine("xsi:type=\"java:com.webex.service.binding.meeting.DelMeeting\">")
                .AppendLine("<meetingKey>" + meetingKey + "</meetingKey>")
                .AppendLine("</bodyContent>");

        Request(xmlAuthBodyContent);
    }

    public void DelMeetingAttendee(string attendeeID)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding.attendee.DelMeetingAttendee\">")
            .AppendLine("<attendeeID>" + attendeeID + "</attendeeID>")
            .AppendLine("</bodyContent>");

        Request(xmlAuthBodyContent);
    }

    public void CreateMeetingAttendee(string alias,
                                    string email,
                                    Type type,
                                    Role role,
                                    string sessionKey)
    {
        var xmlAuthBodyContent = new StringBuilder()
                .AppendLine("<bodyContent ")
                .AppendLine("xsi:type=\"java:com.webex.service.binding.attendee.CreateMeetingAttendee\">")
                .AppendLine("<person>")
                .AppendLine("<name>" + alias + "</name>")
                .AppendLine("<email>" + email + "</email>")
                .AppendLine("<type>" + type.ToString() + "</type>")
                .AppendLine("</person>")
                .AppendLine("<role>" + role.ToString() + "</role>")
                .AppendLine("<sessionKey>" + sessionKey + "</sessionKey>")
                .AppendLine("</bodyContent>");

        Request(xmlAuthBodyContent);

    }

    public void RegisterMeetingAttendee(string name,
                                        string title,
                                        string email,
                                        Type type,
                                        Role role,
                                        string sessionKey)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding.attendee.RegisterMeetingAttendee\">")
            .AppendLine("<attendees>")
            .AppendLine("<person>")
            .AppendLine("<name>" + name + "</name>")
            .AppendLine("<title>" + title + "</title>")
            .AppendLine("<email>" + email + "</email>")
            .AppendLine("<type>" + type.ToString() + "</type>")
            .AppendLine("</person>")
            .AppendLine("<joinStatus>ACCEPT</joinStatus>")
            .AppendLine("<role>" + role.ToString() + "</role>")
            .AppendLine("<emailInvitations>TRUE</emailInvitations>")
            .AppendLine("<sessionKey>" + sessionKey + "</sessionKey>")
            .AppendLine("</attendees>")
            .AppendLine("</bodyContent>");

        Request(xmlAuthBodyContent);
    }

    public string GetjoinurlMeeting(string sessionKey, string alias)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding.meeting.GetjoinurlMeeting\">")
            .AppendLine("<sessionKey>" + sessionKey + "</sessionKey>")
            .AppendLine("<attendeeName>" + alias + "</attendeeName>")
            .AppendLine("</bodyContent>");

        return Request(xmlAuthBodyContent).
            SelectSingleNode("//*[local-name()='joinMeetingURL']").LastChild.Value;
    }

    public string GethosturlMeeting(string sessionKey)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding..meeting.GethosturlMeeting\">")
            .AppendLine("<sessionKey>" + sessionKey + "</sessionKey>")
            .AppendLine("</bodyContent>");

        return Request(xmlAuthBodyContent).
            SelectSingleNode("//*[local-name()='hostMeetingURL']").LastChild.Value;
    }

    /// <summary>
    /// Get meeting information
    /// </summary>
    /// <returns>meeting information</returns>
    public DataSet GetMeeting(string meetingKey)
    {
        var xmlAuthBodyContent = new StringBuilder()
            .AppendLine("<bodyContent ")
            .AppendLine("xsi:type=\"java:com.webex.service.binding.meeting.GetMeeting\">")
            .AppendLine("<meetingKey>" + meetingKey + "</meetingKey>")
            .AppendLine("</bodyContent>");

        DataSet dataSet = new DataSet();
        DataTable dataTable = new DataTable("meeting");

        var xmlSR = new StringReader(Request(xmlAuthBodyContent).SelectNodes("//*[local-name()='body']")[0].InnerXml);
        dataSet.ReadXml(xmlSR, XmlReadMode.InferSchema);

        return dataSet;
    }

    /// <summary>
    /// Return all meetings on server.
    /// </summary>
    /// <returns>List of meetings</returns>
    public DataSet GetAllMeetings()
    {
        var xmlAuthBodyContent = new StringBuilder()
                .AppendLine("<bodyContent ")
                .AppendLine("xsi:type=\"java:com.webex.service.binding.meeting.LstsummaryMeeting\">")
                .AppendLine("<listControl>")
                .AppendLine("<startFrom>1</startFrom>")
                .AppendLine("<maximumNum>10</maximumNum>")
                .AppendLine("<listMethod>OR</listMethod>")
                .AppendLine("</listControl>")
                .AppendLine("<order>")
                .AppendLine("<orderBy>HOSTWEBEXID</orderBy>")
                .AppendLine("<orderAD>ASC</orderAD>")
                .AppendLine("<orderBy>CONFNAME</orderBy>")
                .AppendLine("<orderAD>ASC</orderAD>")
                .AppendLine("<orderBy>STARTTIME</orderBy>")
                .AppendLine("<orderAD>ASC</orderAD>")
                .AppendLine("</order>")
                .AppendLine("</bodyContent>");

        var dataSet = new DataSet();
        
        var xmlSR = new StringReader(Request(xmlAuthBodyContent).SelectNodes("//*[local-name()='body']")[0].InnerXml);
        dataSet.ReadXml(xmlSR, XmlReadMode.InferSchema);

        return dataSet;
    }

    /// <summary>
    /// Build and run WebEx server requests.
    /// </summary>
    /// <param name="action"></param>
    /// <returns></returns>
    protected XmlElement Request(StringBuilder action)
    {
        var conn = WebRequest.Create(_baseUrl);
        conn.Method = "POST";

        conn.ContentType = "text/xml; charset=utf-8";

        byte[] byteArray = Encoding.UTF8.GetBytes(BuildRequestXML(action));
        conn.ContentLength = byteArray.Length;

        conn.GetRequestStream().Write(byteArray, 0, byteArray.Length);

        var resp = conn.GetResponse();

        var resultStream = resp.GetResponseStream();

        var doc = new XmlDocument();
        if (resultStream != null) doc.Load(resultStream);

        doc.DocumentElement.InnerXml = doc.InnerXml.Replace("<serv:header xmlns:serv=\"http://www.webex.com/schemas/2002/06/service\">", "").Trim();

        GetStatus(doc.DocumentElement);

        return doc.DocumentElement;
    }


    /// <summary>
    /// Build request url
    /// </summary>
    /// <param name="action"></param>
    /// <returns></returns>
    protected String BuildRequestXML(StringBuilder action)
    {
        Func<StringBuilder, StringBuilder> webExXML =
        bodySB => new StringBuilder(1024) 
            .AppendLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>")
            .Append("<serv:message xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"")
            .Append(" xmlns:serv=\"http://www.webex.com/schemas/2002/06/service\"")
            .Append(" xsi:schemaLocation=\"http://www.webex.com/schemas/2002/06/service")
            .Append(" http://www.webex.com/schemas/2002/06/service/service.xsd\">")
            .AppendLine("<header>")
            .AppendLine("<securityContext>")
            .AppendLine("<siteName>sitename</siteName>")
            .AppendLine("<siteID>554589</siteID>")
            .AppendLine("<webExID>" + _login + "</webExID>")
            .AppendLine("<password>" + _password + "</password>")
            .AppendLine("<partnerID>78dfrt</partnerID>")
            .AppendLine("</securityContext>")
            .AppendLine("</header>")
            .AppendLine()
            .AppendLine("<body>")
            .Append(bodySB)
            .AppendLine()
            .AppendLine("</body>")
            .AppendLine("</serv:message>");

        return webExXML(action).ToString();
    }

    private void GetStatus(XmlElement response)
    {
        var code = response.SelectNodes("//*[local-name()='result']").Item(0).InnerText;
        if (code != "SUCCESS")
        {
            var subcode = response.SelectNodes("//*[local-name()='reason']").Item(0).InnerText;
            throw new Exception("request: " + code + " -> reason: " + subcode);
        }
    }
}

Normalizing Constraints For A Multi Objective Fitness Function

Most optimization problems involving genetic algorithms will contain multiple constraints; a useful way of handling these constraints, is by multiplying them by a factor which will scale the constraint to a predefined range. It is generally a good idea to have all constraints contributing equally to the final fitness value.

Example:

//calculate fitness
m_dFitness = distFit + 400*rotFit + 4*fitAirTime;

The factor been used in the above example is 400, distFit has a max of 400 therefore, rotFit which has a max of 1 is multiplied by 400 and fitAirTime which has a max of 100 is multiplied by 4.

If you wanted to normalize each constraint to a different range then you could use this formula to calculate the normalized value y = 1 + (x-A)*(r2-r1)/(B-A) where A,B is the original range and r1,r2 is the range that the value x should be normalized to.

Example:

//calculate fitness
var distFit = 1 + (x-0)*(10-1)/(50-0);
var rotFit  = 1 + (x-0)*(10-1)/(90-0);
var fitAirTime = 1 + (x-0)*(10-1)/(30-0);

m_dFitness = distFit + rotFit + fitAirTime;

This option is more feasible since it does not rely on any constraint value to derive a multiplication factor.

 

Mapping A Maze Using MATLAB Image Processing Toolbox

Recently I saw an article about mapping a maze and I thought to myself; how could this be achieved using my favorite tool MATLAB :-)? Well it turns out that its a pretty simple task. Some functions used in this post require that you have MATLAB 2012a or higher installed, so if u do not then go away and get it.

Wow you are back, ok so lets begin, first we will look at the code that was used and then further down we will look at individual functions and what they were used to do.

The maze:
maze

The code:

%% Map Maze
clear
im = imread('maze.png');
bw = im2bw(im(1:287, 1:400), 0.45);
cc = bwconncomp(bw, 8);
obj = false(size(bw));
obj(cc.PixelIdxList{13}) = true;
sln = bwmorph(bwmorph(obj,'thin',Inf),'spur', Inf);
figure, imshow(imfuse(im,sln,'blend','Scaling','joint'))

Explanation:
clear Clears all variables from the MATLAB workspace.
im = imread(‘maze.png’);
Reads the maze image and stores it.
bw = im2bw(im(1:287, 1:400), 0.45); Converts the image to binary, scales it and stores it.
cc = bwconncomp(bw, 8); Find connecting components within the image.
obj(cc.PixelIdxList{13}) = true; Find the largest component and select it.
sln = bwmorph(bwmorph(obj,’thin’,Inf),’spur’,Inf); Use Morphological functions to refine image.
figure, imshow(imfuse(im,sln,’blend’,’Scaling’,’joint’)); Overlay and display images

Result:

solved maze

The end :-)

Running Microsoft SQL Server From A VS2012 Command Prompt

Having a connection to Microsoft SQL Server in the command prompt provides you with an easily disposable window that you can use to query a database without resorting to the SQL Server Management Studio. Personally, I like to have it tucked into a little corner of my screen where It can be easily accessed; for tasks such as checking if i have a connection to the server,  listing tables in a database and running simple queries. Lets see how we can get a connection to SQL Server up and running in a VS2012 DOS Box.

Steps:

  1. Open a visual studio command prompt dos box.
    dosbox
  2. Type CD/ at the command prompt.
    promptcd
  3. At the command line enter sqlcmd -S [SERVERNAME|IP] -U [USERNAME] -P [PASSWORD]
    promptwithcmdsPreview

*NB: The parameters in [] should be replaced with the actual authentication details of the server that you want to connect to. Each command should be followed by the GO directive in order for them to be executed.

Here is an example of a connection to a server running on my machine using sqlcmd -S .
newconnection

That’s how its done, see you next time.