Fun Quiz with C#

I have not written code in C# in a long time lately I have been consumed with Java, SpingBoot and Scala, when I found this a fun quiz I decided to code it in C#. The Quiz states the following given a list of line as follows

H1 Header 1

H2 Header 2

H3 Header 3

H4 header 4

H3 Header 3

H3 Header 3

H4 Header 4

H5 header 5

H2 Header 2

H2 Header 2

H1 Header 1

H2 Header 2

H2 Header 2

H3 header 3

We want to emit HTML that would represent the above as bolts as follows:

  • H1 Header 1
    • H2 Header 2
      • H3 Header 3
        • H4 header 4
      • H3 Header 3
      • H3 Header 3
        • H4 Header 4
          • H5 header 5
    • H2 Header 2
    • H2 Header 2
  • H1 Header 1
    • H2 Header 2
    • H2 Header 2
      • H3 header 3

The list can contain more nested levels than 5.

Solution Algorithm

Provided we took care of the converting the strings into a list of classes Heading . containing the weight (1 -,2,3 ..) and text. The problem becomes going through the list one by one and creating a list of subtrees. The imaginary item with H0 is the root of the tree. All H1 nodes are subtrees of the main tree.

The alogrithm goes like this

  • For each item in the Headings list if the next item in the list has a weight higher than the current item
    • Add the next item, and its children as children of the current node.

The code in C# below shows the solution heart for this Quiz.


private
static Node toOutline(List<Heading> headings)

{


// if No headings


if (headings.Count <= 0) return
null;

Node currentNode = null;

Node root = new Node(new Heading(0, “”));

currentNode = root;


int currentWeight = 0;


for (int i = 0; i < headings.Count;)

{


var heading = headings[i++];

Debug.WriteLine(heading.ToString());

currentNode = new Node(heading);

root.Children.Add(currentNode);


if (i >= headings.Count) break;

     /// check if the next heading


if (currentWeight < headings[i].Weight)

{

Debug.WriteLine(heading.ToString()+” got children”);

currentNode.Children.AddRange(createChildren(currentNode, headings, ref i));

}

}


return root;

}


private
static IEnumerable<Node> createChildren(Node currentNode, List<Heading> headings, ref
int i)

{

List<Node> result = new List<Node>();


if (headings.Count <= 0) return result;


while (i+1 < headings.Count && headings[i].Weight > currentNode.Heading.Weight )

{

Heading currentHeading = headings[i++];

Node node = new Node(currentHeading);

result.Add(node);


if (headings[i].Weight > node.Heading.Weight)

{

node.Children.AddRange(createChildren(node, headings, ref i));

}

}


return result;

}

Complete Code

Below is the complete code, the test class checks two cases on header and one with multiple cases :

[TestClass]


public
class
UnitTest1

{

[TestMethod]


public
void TestOutlineSingle()

{


string[] lines = {“H1 header 1”};

Debug.WriteLine( nodes.Solution.Driver(lines));

}

[TestMethod]


public
void TestOutlineMultiple()

{


string[] lines = {“H1 header 1”,


“H2 header 2”,


“H2 header 2”,


“H3 header 3”,


“H3 header 3”,


“H4 header 4”,


“H5 header 5”,


“H4 header 4”,


“H3 header 1”,


“H2 header 2”,


“H3 header 3”,


“H3 header 3”,


“H1 header 1”,


“H2 header 2”,


“H3 header 3”,


“H3 header 3”,


“H4 header 4”,


“H5 header 5”,


“H3 header 3”,


“H2 header 2”

};

Debug.WriteLine(nodes.Solution.Driver(lines));

}


}

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Linq;

using System.Text;

namespace nodes

{


class
Heading

{


int weight;

String text;


public
int Weight

{


get { return weight; }

}


public String Text

{


get { return text; }

}


public Heading(int weight, String text)

{


this.weight = weight;


this.text = text;

}


public
override
string ToString()

{


return
string.Format(“Heading {0} {1}”, weight, text);

;

}

}


class
Node

{

Heading heading;

List<Node> children;


public Heading Heading

{


get { return heading; }

}


public List<Node> Children

{


get { return children; }

}


public Node(Heading heading)

{


this.heading = heading;


this.children = new List<Node>();

}

}


public
class
Solution

{


public
static
string Driver(string[] lines)

{


var headings = new List<Heading>();


foreach (var line in lines)

{

headings.Add(parse(line));

}


var outline = toOutline(headings);


var html = toHtml(outline);


return html;

}


private
static Node toOutline(List<Heading> headings)

{


// if No headings


if (headings.Count <= 0) return
null;

Node currentNode = null;

Node root = new Node(new Heading(0, “”));

currentNode = root;


int currentWeight = 0;


for (int i = 0; i < headings.Count;)

{


var heading = headings[i++];

Debug.WriteLine(heading.ToString());

currentNode = new Node(heading);

root.Children.Add(currentNode);


if (i >= headings.Count) break; ;


if (currentWeight < headings[i].Weight)

{

Debug.WriteLine(heading.ToString()+” got children”);

currentNode.Children.AddRange(createChildren(currentNode, headings, ref i));

}

}


return root;

}


private
static IEnumerable<Node> createChildren(Node currentNode, List<Heading> headings, ref
int i)

{

List<Node> result = new List<Node>();


if (headings.Count <= 0) return result;


while (i+1 < headings.Count && headings[i].Weight > currentNode.Heading.Weight )

{

Heading currentHeading = headings[i++];

Node node = new Node(currentHeading);

result.Add(node);


if (headings[i].Weight > node.Heading.Weight)

{

node.Children.AddRange(createChildren(node, headings, ref i));

}

}


return result;

}


/** Parses a line of input.


This implementation is correct for all predefined test cases. */


private
static Heading parse(String record)

{

String[] parts = record.Split(” “.ToCharArray(), 2);


int weight = Int32.Parse(parts[0].Substring(1));

Heading heading = new Heading(weight, parts[1].Trim());


return heading;

}


/** Converts a node to HTML.


This implementation is correct for all predefined test cases. */


private
static String toHtml(Node node)

{

StringBuilder buf = new StringBuilder();


if (node.Heading.Text != “”)

{

buf.Append(node.Heading.Text);

buf.Append(“\n”);

}


if (node.Children.Count > 0)

{

buf.Append(“<ol>”);


var childStrings = node.Children.Select(child =>


“<li>” + toHtml(child) + “</li>”

);

buf.Append(String.Join(“\n”, childStrings));

buf.Append(“</ol>”);

}


return buf.ToString();

}

}

}

Advertisements

Scala: Introductory Study Notes

I usually write notes when I am studying or learning new skills, when I was in University my classmates copied my notes to help them with their learning. That is why I am sharing my notes maybe it will help you.

Scala Basics

Scala “scalable language” runs on the Java VM and interoperates with all Java libraries. You can use Scala for writing scripts or for building large systems and frameworks. Scala is a blend of object orient and functional programming concepts. Scala’s functional programming constructs make it easy to build logic quickly from simple parts while its object-oriented constructs make it easy to structure large system and adapt them to new requirements.

Functional programming is guided by two main ideas:

  1. Functions are first class values. This means a function is a value same as integer or string. A function can passed as an argument to another function, returned as a result from a function.
  2. Operations of should map input values to output values rather than change data in place. This means methods should not have side effects. All data types and objects should be immutable.

Setting Up Scala Development Environment


Figure 1: Where to download scala

Best way to learn is by writing some code. In this section, we will go through a quick tutorial of Scala basics. To run the code samples, you should have standard Scala installation. You can get it from http://www.scala-lang.org. You can also use a Scala plug-in for Eclipse, IntelliJ or NetBeans.

Scala Interpreter


Figure 2: Scala Shell Interpreter

Scala comes with an interactive “shell” for writing Scala expressions and programs. The interpreter will evaluate expression you type and print the resulting value.

scala> 567*8+20

res0: Int = 4556

Scala Variables

Scala has two kinds of variables:

  1. val: is similar to final variable in Java or readonly in C#. once initialized it can never be reassigned.

scala> val str = “This is a book about Scala”

str: String = This is a book about Scala

scala> str = “change this string”

<console>:12: error: reassignment to val

str = “change this string”

  1. var: is similar to a non-final or non readonly variable in Java and C# respectively.

scala> var m = “This is a book about Scala”

m: String = This is a book about Scala

scala> m = “Change this string”

m: String = Change this string

Notice that in both examples, I did not define the type. Scala’s ability to infer types makes the code less cluttered with unnecessary explicit type annotations. Though an explicit type annotation can both ensure the Scala compiler infer the type you intend as well as serve as a useful documentation for the readers of the code. In Scala, you specify a variable type after is name separated by a colon.

scala> val s:String = “Hello Scala Book”

s: String = Hello Scala Book

Scala Functions

scala> def max(x:Int, y: Int): Int = {

| if(x > y) x

| else y

| }

max: (x: Int, y: Int)Int

scala> max(99,767)

res2: Int = 767

Functions definitions starts with “def”, followed by the function’s name, followed by comma-separated list of parameters in parentheses. A type annotation must follow each parameter, because Scala does not infer function parameter types. After the close parenthesis another type annotation that defines the result type of the function. You can leave the result type and Scala will infer it.

while and if constructs

var i = 0

i: Int = 0

scala> while(i < 20){

| if(i >0) println(i)

| i += 1

| }

1

2


19

While (condition) statement

The while will execute the statement or block of statements (complex statement) contained within “{}” as long as the condition is true.

If(condition) statement1 else statement2

If will execute statement1 if the condition is true. If there is an else then statement2 will get executed if the condition is false.

Arrays

scala> val big = new java.math.BigInteger(“3728”)

big: java.math.BigInteger = 3728

scala> val g = new Array[String](5)

g: Array[String] = Array(null, null, null, null, null)

scala> g(0) = “Hi”

scala> g(1) = ” ”

scala> g(2) = ” Scala”

scala> g(3) = ” Says Functional”

scala> g(4) = ” is the way to go”

You instantiate objects using the “new” keyword. You can configure the object instance when you create it. For example as shown in the code above val big with instantiated with BigInteger with value of 3728. And g was created as an array of type string with 5 elements.

Since functions are first class constructs in Scala, you can pass the function literal that takes parameter to another function. If the function literal takes a single parameter, you need not name specify the argument.

scala> g.foreach(print)

Hi Scala Says Functional is the way to go

apply & update methods

In Scala, when you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So g(0) is transformed to g.apply(0). Any application of an object to some arguments in parentheses will be transformed to an apply method call. This will compile only if the type of the object defines an apply method. When an assignment is made to a variable to which parentheses and one or more arguments have been applies Scala will transform that into an invocation of an update method that takes the arguments in parentheses. So g(0) = “hello” will be transformed into g.update(0,”Hello”)

Lists

Scala array is a mutable sequence of objects that all share the same type. And Array[String] contains only string. Although you can’t change the length on an array after is instantiated. You can change its elements values. For an immutable sequence of objects that share the same type you can use Scala’s List class. List[String] can contain only strings.

scala> val a = List(1,2,3)

a: List[Int] = List(1, 2, 3)

scala> val b = List(7,8,3)

b: List[Int] = List(7, 8, 3)

scala> val ab = a ::: b

ab: List[Int] = List(1, 2, 3, 7, 8, 3)

scala> val s = 1::b

s: List[Int] = List(1, 7, 8, 3)

The code above establishes a new val named a initialized with a new List[Int] with values 1,2, and 3. Note that List.apply() is defined as a factory method in Scala. When you call a method on a List that might mutate the list, it will creates and returns a new list with the new value. For example the ::: method is for list concatenation.

scala> val k = 1 :: 2 :: 8 :: 9 :: Nil

k: List[Int] = List(1, 2, 8, 9)

Note, the method :: is method on its right operand in Scala, this issue will be discussed in more detail later.

Tuples

Tuple are a useful object contain. Tuples are immutable and contain different types of elements. Tuples are similar to C language struct construct. Though you do define the tuple structure in advance. Typically you use tuples when you need to return multiple objects from a method.

scala> val complexTuple = (78,”Rony”, “Alicante”, “Spain”)

complexTuple: (Int, String, String, String) = (78,Rony,Alicante,Spain)

scala> println(complexTuple._1)

78

scala> println(complexTuple._3)

Alicante

Once you have a tuple instantiated, you can access its elements individually with a dot, underscore, and the one-based index of the element, as shown in the example above.

Sets and Maps

Scala provides mutable and immutable alternatives for sets and maps, both use the same simple names but they are in different packages or namespaces. The default is the immutable set as shown in the listing below. The ‘+=’ operation returns a new set that is why the operation succeeds with var and fails with val.

scala> var set1 = Set(“Alicante”,”Granada”)

set1: scala.collection.immutable.Set[String] = Set(Alicante, Granada)

scala> var set2 = set1

set2: scala.collection.immutable.Set[String] = Set(Alicante, Granada)

scala> set2 += “Barcelona”

scala> set1

res20: scala.collection.immutable.Set[String] = Set(Alicante, Granada)

scala> set2

res21: scala.collection.immutable.Set[String] = Set(Alicante, Granada, Barceolona)

scala> val set3 = set1

set3: scala.collection.immutable.Set[String] = Set(Alicante, Granada)

scala> set3 += “Barcelona”

<console>:13: error: value += is not a member of scala.collection.immutable.Set[String]

Expression does not convert to assignment because receiver is not assignable.

set3 += “Barcelona”

to use the mutable version you import the scala.collection.mutable package as shown in the listing below

scala> import scala.collection.mutable

import scala.collection.mutable

scala> val mutableset = mutable.Set(“Alicante”,”Granada”)

mutableset: scala.collection.mutable.Set[String] = Set(Alicante, Granada)

scala> mutableset += “Barceolona”

res24: mutableset.type = Set(Alicante, Barceolona, Granada)

Now the ‘+=’ operator works with ‘val’ as the set is modified. The listing below shows similar operations for Map. To create a mutable Map use scala.collection.mutable package Map class implementation. The default Map uses the immutable implementation.

scala> val areaCode = mutable.Map[Int,String]()

areaCode: scala.collection.mutable.Map[Int,String] = Map()

scala> areaCode += (416-> “Toronto”)

res25: areaCode.type = Map(416 -> Toronto)

scala> areaCode += (905-> “GTA”)

res26: areaCode.type = Map(905 -> GTA, 416 -> Toronto)

scala> areaCode += (613-> “Calgary”)

res27: areaCode.type = Map(905 -> GTA, 613 -> Calgary, 416 -> Toronto)

scala> val stars = Map( 1->”*”,2->”**”,3->”***”,4->”****”,5->”*****”)

stars: scala.collection.immutable.Map[Int,String] = Map(5 -> *****, 1 -> *, 2 -> **, 3 -> ***, 4 -> ****)

scala> println(stars(3))

***

Semicolon Inference

In Scala, a semicolon at the end of a statement is usually optional. You can type one if you want but you do not have to if the statement appears by itself on a single line. On the other hand, a semicolon is required if you write multiple statements on a single line:

scala> val s = “Moustafa”; println(s)

scala> if (x <2)

| println(“too small”) else

| println(“Ok”)

Control Structures

Scala has the following control structures:

  1. if: if works like in Java and C#, it tests a condition and then executes one of two code branches depending on whether the condition holds true.

scala> var args:Array[String] = Array()

args: Array[String] = Array()

scala> val fileName = if(!args.isEmpty) args(0) else “default.txt”

fileName: String = default.txt

  1. while: Just like in C# and Java while has a conditions and a body. The body is executed over and over again as long as the condition holds true.

scala> var a = 20

a: Int = 20

scala> var b = 30 ;

b: Int = 30

scala> while (a != 0) { val temp = a

| a = b% a

| b = temp

| }

scala> b

res1: Int = 10

another form of the while loop is the do-while where the code block is executed at least once and keeps on executing as long as the while condition is true

do {

| line = readLine()

| println(” Read: “+ line)

| } while (line !=””)

  1. for: Scala’s for expression lets you combine a few simple ingredients in different ways to express a wide variety of iterations.
    1. Iteration through collections

val filesHere = (new java.io.File(“.”)).listFiles

for(file <- filesHere) println(file)

for ( i<- 1 to 4) prinrln(“Iterntion “+i)

  1. Filtering

val filesHere = (new java.io.File(“.”)).listFiles

for(file <- filesHere

if file.isFile

if file.getName.endsWith(“.scala”)) println(file)

  1. Nested Iteration

def fileLines(file: java.io.File) =
scala.io.Source.fromFile(file).getLines().toList

    def grep(pattern: String) =
								for (
    file <- filesHere
											if file.getName.endsWith(".scala");
    line <- fileLines(file)
															if line.trim.matches(pattern) 
  ) println(file + ": " + line.trim)
  1. Mid-stream variable bindings same as example above

  • Producing a new collection

 

val filesHere = (new java.io.File(“.”)).listFiles

val forLineLengths =

for {
file <- filesHere

if file.getName.endsWith(“.scala”)
line <- fileLines(file)
trimmed = line.trim

if trimmed.matches(“.*for.*”)
} yield trimmed.length

To generate a new value for each iteration in a for expression prefix the for expression body by the keyword ‘yield’. As in the example above each time the body of the for expression executes it produces one value in this case the length of the trimmed line.

  1. Try: this issued for handling exceptions.

def throws1 {

throw new IllegalArgumentException
}

def throws3 {

import java.io.FileReader

import java.io.FileNotFoundException

import java.io.IOException

try {

val f = new FileReader(“input.txt”)

// Use and close file

println(“f [” + f + “]”)
} catch {

case ex: FileNotFoundException => // Handle missing file

println(“ex [” + ex + “]”)

case ex: IOException => // Handle other I/O error

println(“ex [” + ex + “]”)
}

finally {
file.close() // Be sure to close the file
}


}

  1. Match: Scala match expression is similar to C# and Java switch statement. With default case si specified with an underscore (_) and there is no flow from case to case so no need for a break statement
def match2(args: Array[String]) {
								val firstArg = if (!args.isEmpty) args(0) else ""
																	
																	val friend =
    firstArg match {
																		case "salt" => "pepper"
																						case "chips" => "salsa"
																								case "eggs" => "bacon"
																										case _ => "huh?"
																											}           
																												
																												println(friend)
}
  1. function calls.

Almost all of Scala’s control structures result in some value even try expressions

def urlFor(path: String) =
								try {
										new URL(path)
  } catch {
														case e: MalformedURLException =>
																new URL("http://www.scala-lang.org")
  }

Scala does not have break and continue because they do not mesh well with functional literals.

Itinerary Configurator

Problem

I had many web services to implement with BizTalk ESB Toolkit. All these web service would take input message, perform some mapping/enrichment on the input message call a web service on a LOB system. The LOB web service result would then be mapped to the result of the web service and returned to the caller.

Figure 1: Web service implemented as an Itinerary

If you look at and web service implemented as an itinerary if would look as in figure 1. The itinerary consists of:

  1. A two way on ramp that receives the message
  2. A call to a map to prepare the LOB web service message request
  3. A rout to the LOB web service send port
  4. Call the LOB web service through the send port
  5. Map the response from the LOB web service to the web service schema response
  6. Route the response to the two way receive location through the on ramp

Now I need to implement more than 50 web services that would be performing the same logic except for a different maps to transform to different LOB web service and a different send port for each LOB web service. I can create an itinerary for each web service but that would lead a numerous number of itineraries with the same structure. So I wanted to create a Kind of an itinerary template for all these services. Let us first examine in more detail how an Itinerary implements a web service.

Implementing a Web Service with and ESB Itinerary

For simplicity assume I want to implement a simple web service with BizTalk ESB toolkit that would take as input two number, call a web service that would perform addition or other mathematical operation on them and then return the result to the caller.

The first step is to define the schemas for the request, response in a BizTalk Project. Use the BizTalk WCF Service Publishing wizard to publish a two way web service with request that takes the request schema and a response with the defined schema.

Second step is to start a new blank itinerary and add an onramp service, and configure it to be the receive port defined step 1. You will also need to change the receive location pipelines to be the ESB Toolkit pipelines Itinerary select Receive XML for the receive pipeline and Itinerary Send Pass through for the send pipeline

Secure Messaging Solution

We are sending end receiving sensitive information over the internet. We want to secure all the messages we are exchanging with our partners.

Technical Background

Microsoft® BizTalk® Server relies heavily on the security provided by certificates. By using certificates for encryption and digital signatures, BizTalk Server can send and receive data that can be trusted. By using certificates for encryption and digital signatures, BizTalk Server can:

  • Send and receive data that can be trusted.
  • Make sure that the data it processes is secure.
  • Make sure that authorized parties receive its messages.
  • Make sure that it receives messages from authorized parties.

Creating the Certificates

We will need to create a certificate to use for encrypting and decrypting our secure messaging example.
MakeCert Test Certificate
A MakeCert test certificate is an Authenticode digital certificate that is created by the MakeCert tool. A MakeCert test certificate is a self-signed, root certificate. To create a MakeCert test certificate, use the MakeCert tool as follows:


MakeCert -r -pe -ss TestCertStoreName -n “CN=CertName”  CertFileName.cer 

Where:

  • The -r option specifies that the certificate is self-signed, that is, the certificate is a root certificate.
  • The -pe option specifies that the private key that is associated with the certificate can be exported.
  • The -ss TestCertStoreName option specifies the name of the certificate store that contains the test certificate.
  •  The -n “CN=CertName” option specifies a name for the certificate that can be used with the SignTool command-line tool to identify the certificate. It is recommended that you use a certificate name that clearly identifies the certificate as a test certificate, for example, “WDK Driver Testing Cert – for in-house use only.” If the certificate name is not supplied, the default name of the certificate is “Joe’s Software Emporium.
  • “CertFilename.cer is the file name that contains a copy of the test certificate. The certificate file is used to add the certificate to the Trusted Root Certification Authorities certificate store and the Trusted Publishers certificate stores.
    Storing the Certificates
  • Depending on the purpose of a certificate (signing messages, verifying signatures, decrypting messages, encrypting messages, or party resolution), it must be installed in a specific certificate store. BizTalk Server uses two Windows® certificate stores – the Other People certificate store (in the Local Computer folder) for public keys, and the Personal certificate store (in the Current User folder) for the service account of each host instance for private keys.

Other People certificate store. Public key certificates, as their name implies, are public and accessible by anyone with access to the computer on which they are stored. BizTalk Server retrieves from this store the public key certificates to encrypt messages and to verify the digital signatures for incoming messages. All users can read and use the certificates in this store. The following figure shows the Other People certificate store that BizTalk Server uses for public key certificates.



Figure 1: Other People certificate store

Personal certificate store: BizTalk Server uses private key certificates to decrypt incoming messages and sign outbound messages. Every Windows account enabled to log on interactively on a computer has a personal certificate store that only that account can access. BizTalk Server uses the personal certificate store for the service account of each host instance to access the private key certificates to which each service account has access. The private key certificates must be stored in the Personal certificate store for the service account for each host instance on each computer that has a running host instance that requires the certificate for decryption or for signing outbound messages.
Note: The personal certificate store is also named the MY certificate store when it is used for programmatic operations, such as scripting the importing and exporting of certificates. The following figure shows the Personal certificate store that BizTalk Server uses for private key certificates.



Figure 2: Personal certificate Store

For more information about the certificate stores and the Certificate snap-in for the Microsoft Management Console (MMC), search for “Certificate console” in Windows XP, Windows Server™ 2003, or Windows 2000 Server Help.
Certificates That You Need in Each Store
The following table describes the certificates that you must install in each Windows certificate store.

Table 1 Certificates for each Windows certificate store

Certificate purpose Certificate type Certificate store
Signing Own private key Personal store for each service account of a host instance that has a send pipeline with a MIME/SMIME Encoder pipeline component configured to sign messages (Add Signing Cert To Message property set to True).
Verifying signature Partner’s public key Other People store on each computer that has a host instance that has a receive pipeline with a MIME/SMIME Decoder pipeline component.
Decrypting Own private key Personal store for each service account of a host instance that has a receive pipeline with a MIME/SMIME Decoder pipeline component.
Encrypting Partner’s public key Other People store on each computer that has a host instance that has a send pipeline with a MIME/SMIME Encoder pipeline component configured to encrypt messages (Enable encryption property set to True).
Party resolution Partner’s public key Other People store on the administration computer from which you are configuring party resolution.

Solution


Figure 3: Solution Concept

The solution consists of creating two pipelines. A receive pipeline that decrypts the incoming messages and a send pipeline that encrypts the outgoing messages. The example in this solution uses four ports, two for the encryption scenario and two for decryption scenario.

  1. Plain Receive port that consumes files in a directory to be encrypted. This receive port uses one receive location that uses the standard “Microsoft.BizTalk.DefaultPipelines.XMLReceive” pipeline.
  2.  Enc Send Port that subscribes to the receive plane text port. This send port uses the “PracticalBTS.EncryptPipeLine.EncSendPipeline” pipeline. The figure below shows the configuration. Notice that in the “Outbound Encryption” certificate name is set to the certificate in “other people certificates store” for the receiver.


Figure 4: Send Encrypted port settings.

  1. Enc Receive Port that consumes files in a directory that are encrypted and we want to decrypt them. This receive port uses one receive location that uses the “PracticalBTS.EncryptPipeLine.DecReceivePipeline” pipeline. The figure below shows the configuration.



Figure 5: End Receive Location port configuration


Notice that we do not specify the certificate to use to decrypt the message. As BTS uses the certificate defined for the BTS group as shown in the figure below



Figure 6: BizTalk Group properties certificate settings

  1. Plain Send Port this port subscribes to the Enc Receive Port and just save the output in a file so we can check it


Pipelines Implementation


Receive Decryption Pipeline


Figure 7: Receive Decryption Pipeline

The figure above shows the receive pipeline. As you can see we insert into the decode phase the MIME/SMIME pipeline component. And into the Disassemble pipeline the XML disassembler pipeline component. There are no special settings for any component in this receive pipeline we just accept the default settings.


Send Encryption Pipeline

 


Figure 8: Encryption Send Pipeline


The figure above shows the Encryption send Pipeline. In this pipeline we have the standard XML Assembler pipeline component in the assemble phase and the MIME/SMIME encoder component in the encode phase.



Figure 9: Encoder Pipeline Component Settings
The figure above shows the settings for the MIME/SMIME encoder pipeline component where we enable the encryption and we choose the “DES3” encryption algorithm. In this example we are not going to sign the messages so we select “NoSign” for the signature sign.
Deploying the solution
1. Installing the certificate
2. Compiling and deploying the solution

Use the secure message deployment script to deploy the solution.

Testing

To test the configuration, copy a sample xml file from the “Data Folders\Sample XML Files” or any other valid XML file and drop it in the folder “Data Folders\SecureMessaging\Encryption\In” after BTS process the message you will find the encrypted file at “SecureMessaging\Encryption\Out” the encrypted file should look like


Figure 10: Sample encrypted message


Copy the encrypted message to “Data\SecureMessaging\Decryption\In” and after BTS process the message you will find the plain message at “Data\SecureMessaging\Decryption\out”

Possible Issues

Certificate authorization

A message received by adapter “FILE” on receive location “EncReceive Location” with URI “…\*.txt” is suspended.
Error details: There was a failure executing the receive pipeline: “PracticalBTS.EncryptPipeLine.DecReceivePipeline, PracticalBTS.EncryptPipeLine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e56921b90feec973” Source: “MIME/SMIME decoder” Receive Port: “EncReceivePort” URI: “\SecureMessaging\Decryption\In\*.txt” Reason: Could not validate the Trust Chain of the encryption certificate. The certificate issuing authority may not be a trusted Certificate Authority.
MessageId: {9C0C7B4B-D2B7-489F-A343-6355F5BFA9AC}
InstanceID: {67753340-9C17-4C7B-8364-501BFD5F2FD3}

Solution

Make sure you have installed the certificate in the trusted Authority folder.

Create a SQL Database Programmatically

In this article I will explain how to use MS SQL Management Objects (SMO) to create a MS SQL database from C# code. In this sample will

  1. Enumerate all the SQL servers in the network and fill a list box where the user can select one of the servers.
  2. The user will enter the Database Name to create.
  3. The user will enter an AD account to grant right to.
  4. When the user click “Create Database” the system will check for the existence of the database.


Background

SQL Server Management Objects (SMO) are objects designed for programmatic management of Microsoft SQL Server. You can use SMO to build customized SQL Server management applications. Although SQL Server Management Studio is a powerful and extensive application for managing SQL Server, there might be times when you would be better served by an SMO application.

Enumerating SQL Servers

The  SmoApplication.EnumAvailableSqlServers() enumerates a list of available instances of Microsoft SQL Server. it returns a Datable object value that contains an enumerated list of information about the available instances of SQL Server. The table describe the different columns of the returned DataTable.

Column Data type Description
Name
String The name of the instance of SQL Server.
Server
String
The name of the server on which the instance of SQL Server is installed.
Instance
String
The instance of SQL Server.
IsClustered
Boolean A Boolean value that is true if the instance is participating in failover clustering, or false if it is not.
Version
String
The version of the instance of SQL Server.
IsLocal
Boolean
A Boolean value that is true if the instance is local, or false if the instance is remote.

The computer running the instance SQL Server might not receive responses to the EnumAvailableSqlServers method in a timely manner. The returned list might not show all the available instances of SQL Server on the network. When you call the EnumAvailableSqlServers method in subsequent tries, more servers might become visible on the network.

MessageBox.Show(“Going to look for all SQL Server in the network this might take some time. Do you want to proceed”, “SQL Servers”, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)DataTable dt = SmoApplication.EnumAvailableSqlServers();foreach (DataRow dr in dt.Rows)this.cbServers.Items.Add(dr[0]);

Connecting to SSQL Server

First we check if the user selected the local server or a  SQL serevr

//Connect to the local, default instance of SQL Server.

string srvname = this.cbServers.SelectedItem as
string;

Server srv;

if (srvname == null)

{

srv = new
Server();

sb.AppendLine(“Connected to local SQL server”);

}

else

 {

srv = new
Server(srvname);

sb.AppendLine(string.Format(“Connected to 01908433-d6b4-4413-939a-d55d1e4ee364”, srvname));

}

Checking if the Database Exists

It is easy to check if the database already exists or not, just use the Databases attribute of the server as follows

//Define a Database object variable by supplying the server and the database name arguments in the constructor.

 Database db = srv.Databases[this.tbDBName.Text.Trim()];

if (db != null)

{

if (MessageBox.Show(string.Format(“The ‘01908433-d6b4-4413-939a-d55d1e4ee364’ already exists do you want to drop it?”, this.tbDBName.Text), “Warning”, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)else

{

db.Drop();

}

 {

if (MessageBox.Show(string.Format(“Create the Tables and Stored Procedures for BT Error Manager on ‘01908433-d6b4-4413-939a-d55d1e4ee364’?”, this.tbDBName.Text), “Warning”, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)

{

sb.AppendLine(“Creating the Tables and Stored Procedures.”);

this.tbProgress.Text = sb.ToString();

db.ExecuteNonQuery(dbstring);

sb.AppendLine(string.Format(“Created the Tables and Stored Procedures for BT Error Manager on ‘01908433-d6b4-4413-939a-d55d1e4ee364′”, this.tbDBName.Text));this.tbProgress.Text = sb.ToString();this.tbProgress.ScrollToCaret();“Proceed or select another database”);this.tbProgress.Text = sb.ToString();this.tbProgress.ScrollToCaret();return;

}

sb.AppendLine(

}

}

Creating the Database

To create a database all you have to do is create a new Database object with the Server and the Name of the database then call the Create Method.

db = new
Database(srv, this.tbDBName.Text);

this.tbProgress.Text = sb.ToString();

this.tbProgress.ScrollToCaret();//Create the database on the instance of SQL Server.

db.Create();

sb.AppendLine(“Created the database.”);

sb.AppendLine(“Creating the Tables and Stored Procedures.”);

this.tbProgress.Text = sb.ToString();this.tbProgress.ScrollToCaret();

Running the SQL Script

The last step is to run the script that will create the tables, views , stored procedures etc.

//’Reference the database and display the date when it was created.

 db.ExecuteNonQuery(dbstring);

Notes

If you want to use this code in your project, you will need to add references to the SMO assemblies. You can locate the SMO assemblies in the C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies folder. Select the following files:

  • Microsoft.SqlServer.ConnectionInfo.dll
  • Microsoft.SqlServer.Smo.dll
  •  Microsoft.SqlServer.SqlEnum.dll
  • Microsoft.SqlServer.SmoEnum.dll

An Extensible Light Xml Rules Engine Component

he Extensible light XML rules engine component allows the easy configuration of rules in XML, definition of the interpretations of rules and the actions to be taken by client code. Though the component idea is simple its extensibility and completeness makes it worth of reuse. The component is developed in C# and .Net framework.

Component Concept:

A rule is defined in Webster Dictionary as “a prescribed guide for conduct or action”. In that sense the rules engine purpose is to take a certain action based on a guide. The guide consists of one or more condition and the current state of an object. The conditions can be group with various Boolean operations such as OR, AND, XOR and NOT etc. The combinations can get as complex as you can imagine. What about the action? The action would perform certain behavior based on the data the guide used. In that sense the rules engine as the plural of the rules indicates, contains a number of rules. The engine would check if a rule applies to a certain data object and if so to execute the action associated with that rule guide. For example the rules engine would allow us to formulate rules for entering a club like the ones bellow

* If Age > 18 then Allow to enter the club
* If Age > 18 and Name is Al then Enter the VIP section of the club.

Other kind of rules can be defined like the following generic rules
* If (Condition) then action
* If (condition1) and (Condition2) then action
* If (Condition1) or (Condition2) then action
* If ((Condition1) and (Condition2)) or ((condition3) and (Condition4)) then action
* If ((Condition1) or (Condition2)) and ((condition3) or (Condition4)) then action

Now how do we define the rules and the associated actions? We need to be able to change the rules definitions easily and extend the various guides that the rules use. These to requirements can be satisfied with XML and .Net Reflection technology. This is the approach that I took for the design and implementation of this component.

Requirements

Let’s convert the previous section into specific software requirements and let’s expand it to define the various unplanned actions “exceptions” that might occur as follows:

1. The component can be easily incorporated into other software be it managed code or unmanaged code.
2. The rules should be easily defined and changed without having to rewrite code.
3. The guides can easily be defined and the rules engine handling of different conditions (guides) can be easily enriched by the designer using the component.
4. The actions can easily be defined by the designer using the component.
5. The component should be robust and able to check the validity of the rules supplied.

Detailed Requirements

We can elaborate the requirements definition to:

1. The component would take an object as an input and applies the rules to this object and returns an action object.
2. The Action object exposes a method (Execute) that takes as an input an object and returns a Boolean value that indicates success or failure of the action.
3. The component would read the rules from an XML.
4. The logic used to evaluate the rules would be easy to extend on the fly.
5. Allows for easily configuration through an XML file.
6. The Component would apply the rules sequentially till one handles this object data. It then returns an Action object that is associated with the rule.
7. The component can be used from unmanaged code as well as managed code.
8. In case there is no rule that handles the current object data the component would throw a NonHandledException Exception.
9. If the rules File does not confirm to the schema then the rules engine would throw and exception BadRulesFileException
10. If the developer tries to apply rules to before loading the rules it would throw UnLoadeRulesException
11. The user of the component can use it like
IAction Action = rulesEngine.ApplyRules(prsn);
Action.Execute(prsn);
Or

rulesEngine.ApplyRules(prsn).Execute(prsn);

Rules Engine Component Detailed Design
Component Architecture

Figure 1: Component Architecture.

The Rules Engine component mainly consists of two DLLs, one for the functionality and one for the interfaces. The Fields and Actions DLLs can be combined into one DLL however for demonstrations purposes they have been separated in the sample. Through reflection the Rules engine gets access to the Fields and Actions DLLs. The XML rules file determines which assemblies would be loaded and the classes to instantiate for each field or action.
The kind of comparisons the rules engine can work with would be >, < , >=, <= .= Starts With, Ends With and Includes. These comparisons seems to cover every possible comparison the can be made based on numerical or textual information, though there interpretations would be defined by the client code.
Object Model

Figure 2: Object Model.

The rules engine class is the main class. It contains a rule class. The rule class consists of a list of conditions and an Action. The Conditions consists of several condition classes joined together by a logical condition (OR, AND). Each condition contains a field an enumeration that is preformed on that field. The Field objects implements IField interface described later. The Action class implements the IAction interface described later. Bellow is a simple description of the different classes in the diagram.

Class Description
RulesEngine The RulesEngine class is the main class of the component. Client code creates an instance of this class to get access to the component functionality. The constructor takes as argument the name (including the path) of the XML rules file. The RulesEngine class is the only class exposed by the RulesEngine component
The ApplyRules method is the only method that this class exposes. It return a IAction interface. Or throws either NonHandledException or UnLoadedRulesException

 

Rule The rule class is an internal class. It represents a single rule. The constructor accepts an XMLNode and parses it to build the rule
LogicalCondition This is an internal abstract class that is the base for the Conditions and Condition Classes.
Conditions This is an internal class. It represents a complex condition. A complex condition consists of several condition(s)
Condition This is an internal class. This represents a single condition. A condition can be one of
“StartsWith”

“EndsWith”

“Includes”

“Greater”

“GreaterOrEqual”

“Less”

“LessOrEqual”

A condition Has a field object which implements IField interface.


IAction Interface

The IAction Interface defines the action that a rule would perform provided that it guide is fulfilled. The interface is described n detail bellow:

Method/Property

Description

Initialize This method initializes the action. The action might require extra information that can be passed through a string and parsed there
Execute This the most important part of an Action. It performs the action as its name depicts. It takes as an argument the same object that the rule has checked for validity. It returns a Boolean to indicate success or failure
Name Property The name property is provided in case the client code needs to refer in the diagnostics or tracing to the action name in a human readable format. The Name would be set in initialize method.
Id property The Id property is provided in case the client code needs to perform different code depending on the action chosen by the rule to prepare for the action such as opening a database connection or establishing a connection with another server. Though I would advise that such code should be included in the Execute method or called from there.

IField Interface

The IField interface is the main working horse of the component. The implementer would determine how to interpret the various operations. I.e. what does Greater mean to your objects. The various methods are described bellow.

Method/Property

Description

Initialize This method initializes the Field. Mainly the default value that would be compared to is passed here. Other initializations can be preformed here too.
Greater Compares the passed object to the default value of the field and returns true if it is greater.
Less Compares the passed object to the default value of the field and returns true if it is less.
GreaterOrEqual Compares the passed object to the default value of the field and returns true if it is greater or equal.
LessOrEqual Compares the passed object to the default value of the field and returns true if it is less or equal.
Equal Compares the passed object to the default value of the field and returns true if it is Equal.
StartWith Compares the passed object to the default value of the field and returns true if it Starts with the value. Mainly this is used for string objects or objects with lists
EndWith Compares the passed object to the default value of the field and returns true if it ends with the value. Mainly this is used for string objects or objects with lists
Includes Compares the passed object to the default value of the field and returns true if it includes the value. Mainly this is used for string objects or objects with lists

Dynamic Model

Figure 3:Sequance Diagram.

The dynamic model is simple as after instatiation the client code would call Apply rules on the RulesEngine which would go through the rules apply each one till one returns an object that implements IAction which it passes to the client code. The client code would then call the execute method on the IAction. Bellow is a simple sequence diagram that shows this process.

Data Model “Rules XML Schema”

The Full XML Schema is located at..\Dev\RulesEngine\RulesSchema.xsd. It is too long to include in this document. I will point out a couple of important points.

Figure 4: Rules Schema

As you can see from the figure above the XML rules schema consists of a Rules node (the root node) which contains multiple Rule Nodes. A Rule node contains an Action Node and a one or more Conditions Nodes. An Action node as in the Schema fragment bellow has three attributes.

<xsd:complexType name=”ActionType”>
<xsd:attribute name=”ActionType” use=”required” />
<xsd:attribute name=”ActionAssm” use=”optional” default=”” />
<xsd:attribute name=”Data” use=”required” />
</xsd:complexType>

The ActionType attribute is the name of the class that the rules engine would instantiate. The ActionAssm is the name of the assembly that contains the class defined in the ActionType attribute. The Data attribute contains the initialization string that would be passed after instatianting the class to the IActioodn:Initialize method.

Figure 5: Conditions detailed schema
Figure 5 shows the Condition schema. The important point to notice here is that the field type and FieldAssm which is similar to the ActionType and ActionAssm explained above. Also notice the definitions of the operation attribute with the enumeration type to be able to validate the correct definition of different operations.

<xsd:complexType name=”ConditionType”>
<xsd:attribute name=”FieldName” use=”required” />
<xsd:attribute name=”FieldType” use=”required” />
<xsd:attribute name=”FieldAssm” use=”optional” default=”” />
<xsd:attribute name=”Operation” use=”required”>
<xsd:simpleType>
<xsd:restriction base=”xsd:string”>
<xsd:enumeration value=”StartsWith” />
<xsd:enumeration value=”EndsWith” />
<xsd:enumeration value=”Includes” />
<xsd:enumeration value=”Greater” />
<xsd:enumeration value=”GreaterOrEqual” />
<xsd:enumeration value=”Less” />
<xsd:enumeration value=”LessOrEqual” />
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name=”Value” type=”xsd:string” use=”required” />
<xsd:attribute name=”LogicalOperation” use=”optional” default=”AND”>
<xsd:simpleType>
<xsd:restriction base=”xsd:string”>
<xsd:enumeration value=”OR” />
<xsd:enumeration value=”AND” />
<xsd:enumeration value=”NOT” />
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:complexType>

Multi-Threading Support

The Rules engine gets initialized once and then can be used as many times. There is no dependency on object states between calls to ApplyRules. So there are no worries about simultaneous calls corrupting each other. The one thing the client code would need to protect is the object it sends to the ApplyRules method. Though I could have locked it as soon it entered to ApplyRules that measure did not make sense as the synchronization has to be though in the whole application context, so this is left to the client code to figure out.

Remoting Support

While a remoting scenario for the rules engine seems a far fetched one it is still possible that some client code would want to imply it that way. The RulesEngine class is implemented to inherit from MarshalbyRefObject so it can be marshaled by reference. Also there is IRulesEngine interface that exposes only ApplyRules. The reason I choose to marashal it by reference is that there is no sense in marshaling it by value as if you need to marshal it by value then all you have to do is send the xml rules file and schema to remote code. The exceptions are implemented to support remoting. The IAction interface remoting would depend on the object which implements it and your distributed system design. I provided the main functionality here but you will have to figure out how the Rules Engine would fit within your distributed system.
COM Support
The rules engine is exposed as a COM object with GUID {ECD78EB8-FF0E-4f36-A62F-93A6EAC7D1BB}. The Apply rules is exposed as MTA model to simplify the threading mode.

The Sample and source code

Attached with this article is the source code. The sample is a simple dialog through which you point the rules engine to the rules xml file (normally located at ..\Dev\RulesEngine\SampleRules.xml) and then you can run simple tests. The sample defines an Object called person which you enter the name and age. The rules determine if that person can enter the club, should go to the VIP section or should not enter the club at all. It is a simple rules but it explains the idea. There are two DLLs that define the various comparisons in the Fields.DLL and the Action is a simple implementation that just displays a dialog box with the rule message.