C#

Monads And Their Applications in C#

Posted on Updated on

If you have ever written code in most modern programming languages and even languages that are not functional in nature there is a very high probability that you have used some form of monadic structure. A monad is a structure that represents computations defined as sequences of steps: a type with a monad structure defines what it means to chain operations, or nest functions of that type together. This allows the programmer to build pipelines that process data in steps, in which each action is decorated with additional processing rules provided by the monad. As such, monads have been described as “programmable semicolons”.

Monads allow you to do things like method chaining, and flattening null and exception checks in highly nested code blocks.

Monadic Rules:

1.  Left identity
Identity.Compose(f) = f

2.  Right identity
f.Compose(Identity) = f

3.  Associative
f.Compose(g.Compose(h)) = (f.Compose(g)).Compose(h)

Example: Very basic Monad to factor out division by zero check in BMI calculation.

Monads are awesome, and I still have a lot to learn about them, however I can already see them everywhere in C#: IEnumerable, JQuery: Ajax Requests and lots more.

Until next time keep learning 🙂

References:
blogs.msn.com
wikipedia.org

How To Unit Test A LINQPad Code Snippet

Posted on Updated on

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 🙂

Cisco WebEx API v5.9 C# Integration Class

Posted on Updated on

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);
        }
    }
}

Generating C# Classes from WebEx Request XML

Posted on Updated on

Just recently I worked on a project that required me to consume some WebEx services, after the first look at some sample code I  decided not to go the route of building XML strings whenever there was a need to communicate with the WebEx servers. I wanted the ability to serialize and deserialize xml requests and responses, so here is what I did to accomplish this in C# and xsd.exe.

Sample WebEx xml request: Authenticate user

<?xml version="1.0" encoding="ISO-8859-1"?>
<serv:message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:serv="http://www.webex.com/schemas/2002/06/service">
    <header>
    <securityContext>
        <siteName>ian0830</siteName>
        <webExID>siteadmin
        <password>pass</password>
        <partnerID>webexpartner
        <email>johnsmith@xyz.com</email>
    </securityContext>
    </header>
    <body>
        <bodyContent xsi:type="java:com.webex.service.binding.user.AuthenticateUser">
            <samlResponse>
                message will go here
            </samlResponse>
       </bodyContent>
    </body>
</serv:message>
  1. Copy the XML string to notepad and save as helper.xml
  2. At the developer command prompt type cd\ then press Enter\Return
  3. Type the path to helper.xml then press Enter\Return
  4. At the command prompt type xsd helper.xml then press Enter\Return [This will generate the helper.xsd file]
  5. Next type xsd helper.xsd /c /f then press Enter\Return  [Will generate C# classes based on the helper.xsd file]

Now lets see how we can manually load these generated classes then serialize them to XML for posting to the WebEx REST API Servers.


private void TestSerialization()
 {
 var msgSecurityContext = new messageHeaderSecurityContext()
 {
 email = "johnsmith@xyz.com",
 partnerID = "webexpartner",
 password = "pass",
 siteName = "ian0830",
 webExID = "siteadmin"
 };

var msgBodyContent = new messageBodyBodyContent() { samlResponse = "samlResponse message will go here" };

var header = new messageHeader() { securityContext = new messageHeaderSecurityContext[] { msgSecurityContext } };
var body = new messageBody() { bodyContent = new messageBodyBodyContent[] { msgBodyContent } };

var msg = new message() { Items = new object[] { header, body } };

var xmlns = new System.Xml.Serialization.XmlSerializerNamespaces();

xmlns.Add("serv", "http://www.webex.com/schemas/2002/06/service");
xmlns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

System.Xml.Serialization.XmlSerializer searializer = new System.Xml.Serialization.XmlSerializer(msg.GetType());

searializer.Serialize(Console.Out, msg, xmlns);
Console.WriteLine();
}

This produces an identical XML string as the one shown above.

Convert RGB To Integer In C#

Posted on Updated on

If you ever wanted to convert an RGB value to an integer value, this is how you do it.
First strip the leading pound sign(#) from the string using the Substring function.

   string val = "#060810";
   var    rgb = val.Substring(1, val.Length -1);

Next split the string into 3 different parts representing red, green, and blue

   var r = int.Parse(rgb.Substring(1, 2), NumberStyles.HexNumber);
   var g = int.Parse(rgb.Substring(3, 2), NumberStyles.HexNumber);
   var b = int.Parse(rgb.Substring(5, 2), NumberStyles.HexNumber);

*NB: The int.Parse function along with NumberStyle.HexNumber is used to convert each Hex number to its equivalent decimal representation, happy coding 🙂

C++ Linked List Implementation

Posted on Updated on

My Interpretation of a c++ Linked list enjoy!

list.cpp

#include "list.h"

void linkedlist::iniNode(struct Node *head, int n)
{
	head->data = n;
	head->next = NULL;
}

void linkedlist::addNode(struct Node *head, int n)
{
	Node *newNode = new Node();
	newNode->data = n;
	newNode->next = NULL;
	Node *cur = head;

	while(cur)
	{
		if(cur->next == NULL)
		{
			cur->next = newNode;
			return;
		}
		cur = cur->next;
	}	
}

struct Node *linkedlist::searchNode(struct Node *head, int n)
{
	Node *cur = head;
	while(cur)
	{
		if(cur->data == n)
			return cur;

		cur = cur->next;
	}
	return NULL;
}

bool linkedlist::delNode(struct Node **head, Node *delPtr)
{
	Node *cur = *head;
	if(delPtr == *head)
	{
		*head = cur->next;
		delete delPtr;
		return true;
	}

	while(cur)
	{
		if(cur->next == delPtr)
		{
			cur->next = delPtr->next;
			delete delPtr;
			return true;
		}
		cur = cur->next;
	}
	return false;
}

void linkedlist::printList(struct Node *head)
{
	Node *cur = head->next;
	while(cur)
	{
		cout << cur->data << '\n'; cur = cur->next;
	}
}

list.h

#include <Windows.h>
#include <iostream>


using namespace::std;


struct Node{
	int data;
	Node *next;
};

class linkedlist
{
	public:
		void iniNode(struct Node *, int);
		void addNode(struct Node *, int);	
		bool delNode(struct Node **, Node *);
		void printList(struct Node *);
		struct Node *searchNode(struct Node *, int n);
};

loader.cpp

#include "list.h"

int main()
{
	linkedlist list =  linkedlist();

	Node *head = new Node();

	list.addNode(head, 10);
	list.addNode(head, 20);

	list.printList(head);

	list.delNode(&head, list.searchNode(head,10));
	list.printList(head);

	return 0;
}

Example Adobe Connect 9 Adapter Class in C#

Posted on Updated on

Adobe Connect 9 adapter class, does not implement all functionality but this should give you a flying start.