Simple Rule Engine in .NET

Introduction

Rule Engine is a Software system that contains rules on behalf of another system. A Rule Engine contains different types of rules which are related to business, legal etc… Rather than Rule It also helps to manage and classify the rules in a single location instead of hard coding in the application.

For Eg : A Bank could have a set of rules that check the interest associated with each account. Such rules can be included in Rule Engine and we can use it in calculation process without hard coding inside the application. Its just like .config file, that contains values. But rule engine is not for storing values like. config file. We understood that after reading this article.

Why Rule Engine?

Most companies business strategies may change due to their internal and external environments.
In case of bank, policies and rules may change, interest rates may change….Such changes can handle with the help of rule engine in maintainable, reusable, extensible and ownership way without touching the application code much.

What is SRE…?
From a technical prespective, SRE is a simple, flexible product aimed at enabling software developers to create applications that can be maintained with minimal effort and directly supported by designated business users.
It uses the flexiblity and robustness of XML into a context that business users can understand and own freeing developers to work on new functionality. It allows developers to combine rule-based and object oriented programming methods to add business rules to new and existing applications.

Ref : http://simpleruleengine.tripod.com/

So, let we can do a practical exercise on this.

1. First you need to create a Console Application in C#

2. Install the Package using Nuget (Tools > Nuget Package Manager > Package Manager Console) using the command Install-Package SimpleRuleEngine

3. Use the Reference in your code behind.

using RuleEngine.Compiler;

4. Create a SRE XML file like below, which specifying Rules.

<?xml version="1.0" encoding="utf-8" ?>
<RuleEngine>
 <Rules>
 <Rule id="RuleAgeabove18" desc="RuleAgeabove18" chainable="true" priority="1">
 <Condition><![CDATA[ Age > 18 ]]></Condition>
 <Actions>
 <Evaluate factId="Status"><![CDATA["Eligible"]]></Evaluate>
 </Actions>
 </Rule>
 <Rule id="RuleAgebelow18" desc="RuleAgebelow18" chainable="true" priority="2">
 <Condition><![CDATA[ Age < 18 ]]></Condition>
 <Actions>
 <Evaluate factId="Status"><![CDATA["Not Eligible"]]></Evaluate>
 </Actions>
 </Rule> 
 </Rules>
 
 <Facts>
 <Fact id="Age" desc="Age" type="double" modelId="Voting">
 <xpath><![CDATA[ Voting/Age]]></xpath>
 </Fact>
 <Fact id="Status" desc="Status" type="string" modelId="Voting">
 <xpath><![CDATA[ Voting/Status]]></xpath>
 </Fact>
 </Facts>
</RuleEngine>

Now, just copy paste the above xml file and save this as AgeRule.xml file in bin/Debug Folder. We will discuss about this soon.

private class RuleExecutor
{
public void ExecuteRules()
{
Console.Write("Enter you Age : ");
int inputage = Convert.ToInt32(Console.ReadLine());

string directory = AppDomain.CurrentDomain.BaseDirectory + @"\AgeRule.xml";
XmlDocument rules = new XmlDocument();
rules.Load(directory);

//model
XmlDocument model = new XmlDocument();
model.LoadXml(@"
<Voting>
<Age>" + inputage + @"</Age>
<Status></Status>
</Voting>");
ROM rom = Compiler.Compile(rules);
rom.AddModel("Voting", model);
rom.Evaluate();

var age = model["Voting"]["Age"].InnerText;
var status = model["Voting"]["Status"].InnerText;
var IsNull = model["Voting"]["IsNull"].InnerText;

var message = string.Format("Your Age is {0} So you are {1} for Voting", age, status);
Console.Write(message);
Console.Read();
}
}

We can start using Rule Engine in our program, by using the above class.

So lets we start explanation.

Tags and its Attributes in XML File:

RuleEngine : is the RootTag

Rules : Defines all the Rules inside this tag

Rule : Each Rules are defined using this Tag

Id : Its an Unique ID.

desc : Description of the Rule

chainable : Specify whether it’s chainable or not. SRE is chainable. So it should be always True.

Priority : Priority of the rule

Actions : Actions to be performed when the given condition is satisfied is given in this tag.

Evaluate : Assign the given value to specified FactId.

Facts : Tags to deal with input and output to/from the Rule Engine.

Fact : Specifies each fact, that is the input and output to/from the Rule engine.

type : Data type of the value. it can be double, string, boolean….

modelId : The XML root tag, that we are passing to rule engine.    ( The XML, which use in above code)

Xpath : The xml path from the passing model xml to refer the input and output.

Lets Run the app and see its working….

Happy Coding 🙂

An .NET application to Speak, what you have entered..

Today, we are going to understand a new library in .NET, which helps to speak, what you have entered.

First, you need to start a windows application in C#.

Add a textbox and button control to the form.

ReaderApp2

we need to make use of a Library Reference in .NET, for speak out.

                    System.Speech

We need to add this reference from in the Solution explorer by right clicking on reference > Add Reference > Select System.Speech > Ok.

After that, you can see References like below.

ReaderApp1

Now open the code behind for the form.

Then we need to use the Speech reference in our code behind.

using System.Speech.Synthesis;

Add a click event for the button, we have placed in form design, by double clicking it, and add the following two 3 line code.

var msg = textBox1.Text;

SpeechSynthesizer ss = new SpeechSynthesizer();

ss.SpeakAsync(msg);

Yes, the app is ready. Just run and write some text in textbox and click the button.

See the Magic….

Change Lync status using C#

Hi All,

Today we are going to understand how to work with Microsoft Lync using C#.

Here, we are going to change the status of Lync using C#. It can be achieved by following the below steps.

  1. First you need to download and install Lync SDK from here.
    Note: Remember the SDK installing directory ‘
  2. After installation, Create a new windows application project in Visual Studio and place a button control and change the caption as “Busy“.
  3. Now we need to give references of Lync SDK DLL’s to our project,  You get the DLL’s from the SDK installed directory.
  4. Then you need to add reference of the  Microsoft.Lync.Model DLL to your project by right click on Reference -> Add Reference from Solution Explorer.
  5. Add namespace in the .cs file
using Microsoft.Lync.Model;

6.   Write the below C# code in the Button Click event

LyncClient lyncClient = LyncClient.GetClient();
if (lyncClient.State == ClientState.SignedIn)
{
  Dictionary<PublishableContactInformationType, object> status = new Dictionary<PublishableContactInformationType, object>();
  status.Add(PublishableContactInformationType.Availability, ContactAvailability.Busy);
  lyncClient.Self.BeginPublishContactInformation(status,null,null);
}
  • Now Sign in to Microsoft Lync
  • Set the status as ‘Available
  • Run the program
  • Press the button
  • See the status in Lync

Use XML Serialization Attributes for customizing xml file

In the previous post, we discussed, how to serialize an object to XML file. So in this post, we are going to discuss how to customize the XML file while serializing. This can be done with the help of XML attributes.To use XML Attributes, we need to use System.XML.Serialization namespace. Following are some of the commonly used XML attributes:

  1. XmlRoot Attribute
  2. XmlElement Attribute
  3. XmlAttribute Attribute
  4. XmlText Attribute
  5. XmlIgnore Attribute

NOTE: Please understand and do the previous post exercise before proceeding.

XMLRootAttribute

This attribute specifies the Root element in an XML file. Normally it will be the class name, but we can change that by using this property.

[XmlRoot("StudentDetails")]
public class Student
{
 public string StudName { get; set; }
 public int Age { get; set; }
 public string Phone { get; set; }
}

In the above example, by default root name in XML is Stud. But we are given an attribute to change that. So the root element in XML file will be Student.

Before applying attribute
<Student>
  <StudName> </StudName>
  <Age> </Age>
  <Phone> </Phone>
</Student>

After applying attribute
<StudentDetails>
  <StudName> </StudName>
  <Age> </Age>
  <Phone> </Phone>
</StudentsDetails>

 XMLElement Attribute

This attribute specifies the name of the element, that is to be in XML file instead of property names. Normally, property names became the element tags in the XML file. See the above code, The property names, and tag names are same in both class and XML file. By using this attribute, we can change the tag name instead of the property name. See the below code;

[XmlRoot("StudentDetails")]
public class Student
{
[XmlElement("StudentName")]
 public string StudName { get; set; }
 public int Age { get; set; }
 public string Phone { get; set; }
}

The output XML file will be as follows

<StudentDetails>
  <StudentName> </StudentName>
  <Age> </Age>
  <Phone> </Phone>
</StudentDetails>

See, the property name in class is Stud, but we change that to StudentName by using XmlElement attribute.

XmlAttribute Attribute

This attribute is used to make a property as an attribute of another element/tag. See the below code;

[XmlRoot("StudentDetails")]
public class Student
{
[XmlElement("StudentName")]
 public string StudName { get; set; }
[XmlAttribute("Age")]
public int Age { get; set; }
 public string Phone { get; set; }
}

The output XML file will be as follows;

<StudentDetails Age = "" >
  <StudentName> </StudentName>
  <Phone> </Phone>
</StudentDetails>

See, the property name Age became an attribute of the Root element Student.

XmlText Attribute

This attribute will convert a property value as a text of a particular tag/element. See the below code,

 [XmlRoot("Student")]
 public class Stud
 {
   private Mark studmark;

  [XmlElement("StudentName")]
  public string StudName { get; set; }
  [XmlAttribute("Age")]
  public int Age { get; set; }
  public string Phone { get; set; }
  [XmlElement("Mark")]
  public Mark mark 
  {
   get{return studmark;}
   set{studmark = value;}
  }
 }
public class Mark 
{  
   [XmlAttribute("Subject")] 
   public string subject  {  get;  set;  }
   [XmlText()]  
   public int mark  {  get;  set;  } 
}

From the above code, we can understand that, there are two classes, Stud, and Mark. In Stud class, we add an extra property mark in Mark class type. Mark is a class created by me, a user-defined class. So we need to define that class as well, that is the 2nd class. In class Mark, we created 2 properties subject and mark, and we are converting this class as XML tag inside Student Tag.

See, to create an attribute for Stud class or Student element, we need to decorate a property inside stud class as XMLAttribute…right? So, what will we do, suppose if we want to add an attribute to an element inside Student element…? It can be achieved through only creating a separate class for that element. That’s why we created 2 classes here.

Here I want to add an attribute subject to mark element. So I created a class  for that and created  properties and decorated it n Mark class type.

If we didn’t create a separate class, we can only store a value inside mark element. But I need to add an extra attribute to that element, so I achieved it through a separate class. Now I need to store a value in that mark element, For that, I created a property in mark class and decorated it with XMLText(). So the value assigned to that property will become the value of XML tag.

The C# code to achieve this is below;

Stud stud = new Stud() { StudName  =  "Vyshag",  Age  =  21, Phone = "8089388438", 
mark = new Mark {subject ="C#" , mark = 5 } };

The XML Output is like below;

<Student Age="21">
 <StudentName>Vyshag</StudentName>
 <Phone>8089388438</Phone>
 <Mark Subject="C#"> 5 </Mark>
</Student>

XmlIgnore Attribute

From the name itself we can easily identify that, this attribute will ignore the specified property.

So we are giving an attribute to property Phone like below

[XmlIgnore()]
public string Phone { get; set; }

Now run the application and check XML file. Phone element is not there right..? That’s the use of XmlIgnore Attribute. If we don’t need to serialize a property we can decorate that property as XmlIgnore.

Working with Space.js, an Open Source helps to give 3D effect in scrolling

We know, today there are so many websites are coming with different types of UI’s, effects, animations etc… So we are going to look into an open source library Space.js which helps to create a web page with a 3D scrolling effect.

By using this javascript library, It’s very simple to create a 3D effect, without writing any codes.

For this, just download the library(Space.js / Space.min.js) from Space.js Github repository

  • Then include that library in your web page Body section (Don’t forget to add a jQuery library as well).
  • Then give class ‘space-frame‘ to each main Div element. This is the Div tag which shows in each scroll. So we need to create multiple Div’s like this to show different details/ information in each scroll.
  • Inside these Div tags, Use section tag with class ‘space-inner-frame’, Its not important to use this class. You can use your own class as well. But It strongly recommended using ‘space-inner-frame’ class, because it will help in some CSS stylings.
  • Then Give your details inside the section tag.
  • It’s also possible to change the animations and its timing as well by using some specific attributes.

Find the Complete Guide from the Space.js Github repository

See Live Demo

Find below sample HTML application,

  • Copy below code to notepad and save it as .html
  • Download Space.js from Github
  • Keep both space.js and HTML file in same directory
  • Run the web page
  • Scroll and see the effetcs
<HTML>
 <Head>
 <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
 </Head>
 <Body>
 <div class="space-frame" data-enter="fadeIn" data-exit="zoomOut fadeOut" data-duration="1.3">
 <section class="space-inner-frame">
 <section>
 <p>Demo 1</p>
 <h1>The Gallery</h1>
 </section>
 </section>
 </div>
 
 <div class="space-frame" data-duration="5.3" data-transition="rotate3dOut">
 <section class="space-inner-frame">
 <section>
 <p>Demo 2</p>
 <h1>The Gallery</h1>
 </section>
 </section>
 </div>
 
 <div class="space-frame" data-transition="rotateOut" data-duration="2.3">
 <section class="space-inner-frame">
 <section>
 <p>Demo 3</p>
 <h1>The Gallery</h1>
 </section>
 </section>
 </div>
 
 <div class="space-frame" data-enter="fadeIn" data-exit="zoomOut" data-duration="1.5">
 
 <section class="space-inner-frame">
 <section>
 <p>Demo 4</p>
 <h1>The Gallery</h1>
 </section>
 </section>
 </div>
 <script type="text/javascript" src="space.min.js"></script>
 </Body>
</HTML>

XML Serialization in C#

In order to store an object in a database, file or memory, we need to convert that object into a stream of bytes. That process of converting an object to stream of  bytes is called Serialization. The reverse process is called Deserialization, i.e.. from a stream of bytes to object.

Why XML Serialization…?

In simple words, by using XML Serialization, we can easily store class(s) variables/properties values into an XML file. This XML file contains markups(tags) with the same name of properties. But we can change them also. This is the simplest way of storing class values into a file. Before doing serialization, we need to keep below points in mind;

  1. The properties should be public.
  2. It stores only the values of the variables/properties.
  3. Read-only properties were not stored.

In order to perform serialization, we need to use the namespace System.Xml.Serialization.

Let’s we can done a simple serialization using a class Student. So create a Console Application and create a class as like following;

 public class Student
 {
     public string StudName { get; set; }
     public int Age { get; set; }
     public string Phone { get; set; }
     public string City
     {
       get
       {
         return "Kochi";
       }
      }
 }

Here we created a class Student, with 4 properties StudName, Age, Phone, and City. Notice that all these properties are public and they have both get and set accessors except City. City has only ‘get’ accessor means read-only and cannot be serialized.  Rest are in read/write mode and all are eligible for serialization. It’s not mandatory that all properties should be in read/write mode. But note that read-only and write-only properties (used only to set values to other fields) will ignore while serializing.

Here we are going to convert the above class Student into an XML file, which holds the property values in the form of tags.

So, our class is ready, then we need a method to serialize this class. it looks like below. add this to ‘main’ class.

static void Serialize(Student stud)
 {
    XmlSerializer serialize = new XmlSerializer(typeof(Student));
    using (TextWriter writer = new StreamWriter(@"Xml.xml"))
    {
       serialize.Serialize(writer, stud);
    } 
 }

Here we pass the Student object to this method because we need to serialize that class. After that, an object serialize is created for XmlSerializer class which present in System.Xml.Serialization namespace, and pass the type of our class Student using ‘typeof ‘keyword to the constructor of XmlSerializer. After that, Create an object writer for TextWriter class and initialize it with StreamWriter class by passing the XML file name with extension, then we call the method Serialize of XmlSerializer class by using its object and pass the TextWriter object and our class object as parameters.

So our method to Serialize an object is completed, now we need values to serialize. For that write the following code in the main method.

Student stud = new Student() 
{ StudName = "CodePlacer", Age = 20, Phone = "0123456789"};
Serialize(stud);
Console.ReadLine();

Here we create the object for our class Student  and pass the values for properties. Here we pass only 3 values, but in Student class we have 4 properties. why? because, out of 4, 1 is read-only, we can’t assign values to a read-only property. After that, we call the method Serialize and pass the Student object as parameter.

now run the Program and go to the project folder > bin > Debug, there we can see the XML file. open it and we can see a file like following.

XML Serializer Output

Note that, the root tag name is same as our class name and the tag names are also same as our property names.

See how simple is to convert an object to XML file.

How to Draw Piechart in Objective-C Using XYPieChart Library

What is XYPieChart…?

XYPieChart is an external chart library, which helps to draw PieCharts in iOS devices. It has a  simple and clean coding structure with understandable methods. You can download the Library from THIS LINK.

After downloading the above file, extract it and copy the XYPieChart folder which contains XYPieChart.h & XYPieChart.m files, to your project.

Now you are ready with the library, so lets draw the chart by following below simple steps.

1) Add a UIView to the storyboard or .xib file.

2) Change the class of UIView to XYPieChart.

3) Import XYPieChart.h to your viewcontroller.h file, where you want draw chart.

4) Create an object for UIView in viewcontroller.h file.

5) Implement XYPieChartDelegate and XYPieChartDataSource to the viewcontroller.h file.

6) Add the following piece of code inside the ViewDidLoad method

float viewWidth = self.pieChart.bounds.size.width / 2;
float viewHeight = self.pieChart.bounds.size.height / 2;
[self.pieChart setDelegate:self];
[self.pieChart setDataSource:self];
[self.pieChart setStartPieAngle:M_PI_2];
[self.pieChart setAnimationSpeed:1.5];
[self.pieChart setLabelColor:[UIColor whiteColor]];
[self.pieChart setLabelShadowColor:[UIColor blackColor]];
[self.pieChart setShowPercentage:YES];
[self.pieChart setPieBackgroundColor:[UIColor whiteColor]];

//To make the chart at the center of view
[self.pieChart setPieCenter:CGPointMake(self.pieChart.bounds.origin.x + viewWidth, self.pieChart.bounds.origin.y + viewHeight)];

//Method to display the pie chart with values.
[self.pieChart reloadData];

7) Now add below XYPieChartDataSource methods definition to ViewController.m file.

//Specify the number of Sectors in the chart
- (NSUInteger)numberOfSlicesInPieChart:(XYPieChart *)pieChart
{
    return 2;
}
//Specify the Value for each sector
- (CGFloat)pieChart:(XYPieChart *)pieChart valueForSliceAtIndex:(NSUInteger)index
{
    CGFloat value = 0.0;
    if(index % 2 == 0)
    {
      value = 25;
    }
    else
    {
      value = 75;
    }
    return value;
}

//Specify color for each sector
- (UIColor *)pieChart:(XYPieChart *)pieChart colorForSliceAtIndex:(NSUInteger)index
{
   UIColor *color;
   if(index%2 == 0)
   {
     color = [UIColor redColor];
   }
   else
   {
      color = [UIColor greenColor];
   }
  return color;
}

 Explanation:

In ViewDidLoad Event, we initialized the Piechart with its main properties. You can change those values as per your scenario. At last we call the method reloadData to display the Piechart with values, reloadData method is called where you change the values of the Piechart, then only it will reflect in piechart.

When ever we call the reloadData method, then ii will automatically call the DataSource methods. Then from there, we specify the number of sectors in Piechart in numberOfSlicesInPieChart method. Here am specified 2. You can change it as per your scenario.

Then it will call valueForSliceAtIndex method to give the values for each sector.Then it will call colorForSliceAtIndex method to specify the color for each sector. You can also give a single color as well.

Now Build your project and run…You will see the chart….

Output :

step0002