Value Mapping

by ion.robu 24. February 2009 11:31

 

There can be cases in mapping development when the developer needs to map some fields conditionally. More exactly, let say that there is need to map in the following situation: if a source field has a value, then a second source field must be mapped to a destination field, else, a third source field must be mapped to the destination field:

 

IF(SourceField1 == Value1) THEN

            DestinationField1 = SourceField2

ELSE [IF(SourceField1 == Value2)]

DestinationField1 = SourceField3

 

There are several solution to do this mapping (for example, using a Script functiod). In this example, we will do that using ValueMapping functoid.

Let’s consider the following example: we have a Biztalk application which simply receive a flat file, disassemble it according to a receive schema, perform a mapping as described above, assemble it according to a send schema and output the resulting file to a send port.

The input file is:

Receive schema is:

 

Tag field if the first character from record (in our example, A or B), Data1 is testdata1_1..5 and Data2 is testdata2_1..5

 

Send schema is:

 

And map is:

 

 

(of course, is a very simplified map and schemas).

The logic of the mapping is:

IF(Tag == “A”) THEN

            Dest.Data1 = Source.Data1

ELSE IF(SourceField2 == “B”)

Data2 = Source.Data2

            In Equal functoids, we have 2 comparisons which return true or false:

and

 

The ValueMapping functoids functions as follows: if the first parameter is true, then second parameter value is returned and is mapped to destination fields. Else, no value is returned, and destination field does not receive anything.

Thus, in our example, for the fields which starts with “A”, Data1 value will be mapped (testdata1_1..5), else, Data2 field will be mapped(testdata2_1..5).

According to these, we obtain output file:

 

 

We can see that, for records 1, 2, and 4 from source file, that start with “A” (Atestdata1_1testdata2_1, AtestData1_2testdata2_2, Atestdata1_4testdata2_4) we have Data1 fields in destination file (testdata1_1, testdata1_2, testdata1_4) and for records 3 and 5, that start with “B” (Btestdata1_3testdata2_3, Btestdata1_5testdata2_5), we have Data2 in destination file (testdata2_3, testdata2_5)

 

 

ValueMapping.rar (14.41 kb)

Tags:

Programming

Debatching SWIFT messages

by ion.robu 24. February 2009 11:24

 

SWIFT is a standard which describe acollection of messages formats. There are a lot of financial applications whichworks with financial transactions, and, often, these applications must communicatebetween them. Because each of them worked with certain formats, there washarder and harder to maintain a good transmission of information, and requireda lot of time and effort.

Because of that, SWIFT standard wasreleased to describe how the messages should be structured and how to exposethe information, in order to be properly interpreted, to be easier tomanipulate and, thanks God, make developer life easier. [More...

Tags:

Programming

LateBinding

by ion.robu 10. February 2009 16:55

In this article we will present a sample about how to use late binding in .NET using System.Reflection namespace and System.Type class.

What is Late Binding? – is a mechanism which allow to instantiate types and accessing members of objects created without knowing these types at compile time. Shortly, these types are not referred “classically”, through dot and new operators, but at runtime, acquiring information about structure type, instantiating objects and invoking its members. All of these without referring that type at all (anyway, we cannot do that, given that we did not include information about that type at compiling time.). All we need is to know structure of used type, more exactly, knowing what methods and properties we need to use.

This approach can be very useful in a lot of cases, due of these capabilities to manipulate objects at runtime, while they are unknown at compile time; this fact help us to provide a much more flexibility to our applications when interacting with others application and/or third-party software (such as COM).

Example – in the following example, we will manipulate objects from a .NET assembly using reflection mechanisms. In this assembly we have class Employee, which exposes some members and methods, and class EmployeeMethods, which exposes a collection of Employee objects and some methods which works on this collection. These 2 types (classes) will be used from main application (a website) without referring it at developing type, but operating on it at execution time. The referred assembly is stored on disk, and its location is given in web.config (you should copy it manually in this location).

Here is the code:

Code from assembly Objects.LateBinding.dll

using System;

using System.Collections.Generic;

namespace Objects.LateBinding

{

       public class Employee

       {

              public string EmployeeName = "";

              public int EmployeeAge = 0;

              public string EmployeeFunction = "";

              public Employee(string name, int age, string function)

              {

                     EmployeeName = name;

                     EmployeeAge = age;

                     EmployeeFunction = function;

              }

              public string PresentEmployee()

              {

                     return string.Format("Hi, I am {0}, {1} years old and I work as {2}", EmployeeName,EmployeeAge, EmployeeFunction);

              }

       }

       public class EmployeeMethods

       {

              public List<Employee> Employees;

              public void Init()

              {

                     //in real scenarios, data will be loaded from various sources

                     Employees = new List<Employee>();

                     Employees.Add(new Employee("John", 26, "Programmer"));

                     Employees.Add(new Employee("Joe", 30, "Web developer"));

                     Employees.Add(new Employee("Jim", 40, "Software architect"));

              }

              public Employee GetEmployee(int i)

              {

                     return Employees[i];

              }

              public int GetEmployeesCount()

              {

                     return Employees.Count;

              }

              public void AddEmployee(string name, int age, string function)

              {

                     Employees.Add(new Employee(name, age, function));

              }

       }

}

Code from Default.aspx.cs from main application:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Reflection;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page

{

       Assembly Asmb = null;

       Type EmployeeMethods = null;

       Type EmployeeType = null;

       object EmpMethods = null;

    protected void Page_Load(object sender, EventArgs e)

    {

              InitTypes();

              if (!IsPostBack)

              {

                     InitEmployees();

                     PresentEmployees();

              }

    }

       private void InitTypes()

       {

              //get assembly with Employee classes

              Asmb = Assembly.LoadFrom(System.Configuration.ConfigurationManager.AppSettings["TestAssembly"]);

              //get EmployeeMethods type information

              EmployeeMethods = Asmb.GetType("Objects.LateBinding.EmployeeMethods");

              EmpMethods = Activator.CreateInstance(EmployeeMethods);

       }

       private void InitEmployees()

       {

              //invoke Init method on EmployeeMethods to init employee collection

              MethodInfo mtdInfo = EmployeeMethods.GetMethod("Init");

              mtdInfo.Invoke(EmpMethods, null);

       }

       private void PresentEmployees()

       {

              //get employees count from EmployeeMethods object created earlier

              MethodInfo mtdInfoEmpCount = EmployeeMethods.GetMethod("GetEmployeesCount");

              object employeesCount = mtdInfoEmpCount.Invoke(EmpMethods, null);

              int emplCount = (int)employeesCount;

              //get each employee object

              for (int i = 0; i < emplCount; i++ )

              {

                     object[] parEmpl = new object[] { i };

                     MethodInfo mtdInfoEmp = EmployeeMethods.GetMethod("GetEmployee");

                     object employee = mtdInfoEmp.Invoke(EmpMethods, parEmpl);//get employee

                     //invoke PresentEmployee method for current employee

                     EmployeeType = employee.GetType();

                     MethodInfo mtdInfoEmpPresent = EmployeeType.GetMethod("PresentEmployee");

                     object employeePresent = mtdInfoEmpPresent.Invoke(employee, null);

                     //display the 'response' of the method

                     Response.Write(employeePresent.ToString() + "<br/>");

              }

       }

       private void AddEmployee(string Name, int Age, string Function)

       {

              //Add employee with values from interface

              object[] parEmpl = new object[] { Name, Age, Function };

              MethodInfo mtdInfoEmpAdd = EmployeeMethods.GetMethod("AddEmployee");

              mtdInfoEmpAdd.Invoke(EmpMethods, parEmpl);

       }

       protected void btnAddEmployee_Click(object sender, EventArgs e)

       {

              InitEmployees();

              AddEmployee(txtName.Text, int.Parse(txtAge.Text), txtFunction.Text);

              PresentEmployees();

       }

}

Code from Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Late binding</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

              <table>

                     <tr>

                           <td colspan="2"><b>Add an employee:</b></td>

                     </tr>

                     <tr>

                           <td>Name:</td>

                           <td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>

                     </tr>

                     <tr>

                           <td>Age:</td>

                           <td><asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>

                     </tr>

                     <tr>

                           <td>Function:</td>

                           <td><asp:TextBox ID="txtFunction" runat="server"></asp:TextBox></td>

                     </tr>

                     <tr>

                           <td colspan="2"><asp:Button ID="btnAddEmployee" runat="server" OnClick="btnAddEmployee_Click" Text="Add employee"/></td>

                     </tr>

              </table>

    </div>

    </form>

</body>

</html>

In this example we list some employees, hardcoded, and add a new one through web interface, using only reflection mechanisms.

Note: Code is not optimized, and no validation was made, since is not point of interest in this article.

Prj.rar (7.70 kb)

Tags:

Programming

Oslo usefull in the end

by Bogdan Nedelcu 14. November 2008 23:22

I really missed the link between the output of the MGrammar and the C# bits of code. Now it seems get some shape. Read here. The movie is inspiring also.

Tags: , ,

Programming

How to load an assembly from a location on disk at runtime

by adrian.tosca 27. September 2008 09:49

Let's say there is an assembly in a certain location on disk and should be loaded at run time. Possible uses for these are: loading external addins for an application, meta information tools etc. How to do this? Well the first idea is to use Assembly.Load(fileName). Unfortunately this overload of the Load method take only an assembly name string, not a file path and can be used only if the assembly is in the same path as the calling assembly. The following will load the TestAddIn.dll assembly from the same location as the calling assembly:

Assembly testAddIn = Assembly.Load("TestAddIn");

 

If one tries to pass the full file name to the method, for example:

Assembly testAddIn = Assembly.Load(
    @"c:\AssemblyLoadSolution\AssemblyLoad\AddIns\TestAddIn.dll");

 

The following FileLoadException will be thrown: "Could not load file or assembly 'file' or one of its dependencies. The given assembly name or codebase was invalid."

The solution is to use another overload of the method Assembly.Load(AssemblyName assemblyRef). The AssemblyName describes the assembly in full including version and strong name. But for a simple use you only need to use the Name and CodeBase properties:

AssemblyName name = new AssemblyName("TestAddIn");
name.CodeBase = @"c:\AssemblyLoadSolution\AssemblyLoad
    \AddIns\TestAddIn.dll";
Assembly testAddIn = Assembly.Load(name);

 

The CodeBase property needs to be set to the full file path of the assembly. The only catch is that the application will need permissions to the folder where the application is loaded. This might be an additional issue on web applications.

Tags: , , ,

Programming

Dryad - a LINQ computation GRID

by Bogdan Nedelcu 19. September 2008 09:10
On DotNet rocks there is a show featuring Dryad, a parallel grid computation model using LINQ. It is rather interesting as you simply write LINQ queries which are distributed and computed in parallel (just like PLINQ) and the restult is assembled into a large dataset. Used primarly for large batch loads processing and not for real-time applications this gives a clue about the power of linq. More infos at the research center.

Tags: ,

Programming

usefull presentation about REST and WCF

by Bogdan Nedelcu 5. August 2008 20:09

I just want to mention a nice presentation about REST and Winows Communication Foundation. REST is about standard HTTP methods in order to perform basic operations. It is easy and accessible to all programming languages.

Read it here.

Tags: ,

General | Programming

How to abuse exception handling

by adrian.tosca 2. August 2008 12:09

1.

Exceptions are silly. Just do a:

try {
	/* do stuff */
} catch {}

and you will never get any exceptions. Do this for each block of code. Randomly let some lines of code outside the try catch block to appear that you carefully considered which blocks of code to handle and which not.

2.

If the users report they receive an error about some weird exception, don't spend too much time to identify the reason the exception appear. Just find the place where the exception is thrown and do a:

try {
	/* stuff that caused the exception*/ }
catch (WeirdException) {}

Make absolutely sure you do not log the exception. Also very important, don't write any meaningful comment about the reason the exception is catch.

3.

Catch exceptions and throw them again without any change:

try {
	/* do stuff */
} catch (Exception ex) {
	throw ex;
}

This way you can not be accused that you didn't handle exceptions. The loosing of the exception stack trace is an added bonus.

4.

Put a lot of exception handling and make sure it is intricate with the code logic:

Service s; 
try {
	s = new Service();
	if (s.IsOnline) {
		try {
			s.IsOnline = false;
		} catch (Exception ex2) {
			s.Link = s.DefaultlLink;
		}
	} else {
		try {
			s.ResetDefaultLink();
		} catch (Exception ex3) {
			s.IsOnline = true;
		}
	}
} catch(Exception ex1) {
	s = new Service(true);
	s.IsOnline = s.Link == s.DefaultLink ? true : false;
}

Anyone who looks over this code will be amazed to see the great care you took for exception handling. Do not add any comment as this would clutter the code even more than already is. No one will understand a thing of that code, nor even you, but this is expected as everyone knows exception handling is hard to code.

5.

Make your own exception class and use it every time to re-throw exceptions:

public class MyApplicationException : Exception {
	public MyApplicationException(string m) : base(m) {
	}
}

try {
	/* do stuff */
} catch (Exception ex) {
	throw new MyApplicationException("Error message here.");
}

Make sure the error message is as unintelligible or as useless as possible. "An error occured" is a good candidate and should be amoung your favorites. Also very important is to make sure you do not include the original exception as inner exception.

Tags: , , ,

Programming

The Specification Pattern and c# 3.5

by adrian.tosca 30. July 2008 13:37

The specification pattern popularized by Eric Evans and Martin Fowler can prove a powerful tool to make rules scattered all around the code explicit and part of the model. The specification pattern, in its simplest form is no more than Boolean test implemented in terms of objects.

Test methods like productStock.IsEmpty() are part of any application and as long as they are simple they can remain as Boolean tests. But tests often depend on complex object state. The tests can be combined to create even more complex rules. The rules are often scattered in every corner of the application and the same tests can appear in more than one place, making modifications difficult and error prone. In such cases it is often better to refactor the rules in classes and make the tests explicit specifications.

In the simple case of the productStock.IsEmpty() the initial code:

class ProductStock {
	public int ProductCount {
		get {
			return _productCount;
		}
	}

	public bool IsEmpty() {
		return ProductCount == 0;
	}
}

Can be refactored into:

class ProductStock {
	public int ProductCount {
		get {
			return _productCount;
		}
	}
}

class EmptyStockSpecification {
	bool IsSatisfiedBy(ProductStock candidate) {
		return candidate.ProductCount == 0;
	}
}

The new class EmptyStockSpecification is a "specification" that states a constraint on the state of another object. The simplest use of this new class is to test if an object satisfy the criteria. It doesn't look like a big improvement but the usefulness became apparent when the simple specifications can be combined to provide complex rules the same way the predicates are combined in logic expressions. The pattern remain simple but allow complex rules without a complex model. There are three main uses of specification pattern:

Validation - To see if an object fulfill some conditions or is ready for some use

if (emptyStockSpec.IsSatifiedBy(prodStock)) {
    ...
}

Selection - To select a subset of objects from a collection based on some criteria

foreach(ProductStock prodStock in allProdStocks) {
    if (emptyStockSpec.IsSatifiedBy(prodStock))
        results.Add(prodStock);
}

Generation - To allow creation of new objects that fulfill some need

ProductStockView view = new ProductStockView();
foreach(ProductStock prodStock in allProdStocks) {
    if (emptyStockSpec.IsSatifiedBy(prodStock))
        view.ProductStocks.Add(prodStock);
}

The three uses are the same on conceptual level. The selection is one of the most used pattern. In c# 2.0 there was possible to use the composite pattern to build complex specifications out of simple ones as can be seen in this very good presentation of the specification pattern. In c# 3.5 the possibility to use lambda expressions and LINQ to Entities for combining specifications makes the pattern much simpler to use.

For example,

struct ProductStock {
	public int ProductCount;
	public int MinLimit;
	public DateTime NextSupplyDate;
}

interface ISpecification
{
	bool IsSatisfiedBy(T candidate);
}

class CloseToMinLimitStockSpecification : ISpecification {
	decimal _variationPercent;
	public CloseToMinLimitStockSpecification(decimal variationPercent) {
		_variationPercent = variationPercent;
	}
	public bool IsSatisfiedBy(ProductStock candidate) {
		return candidate.ProductCount < 
			candidate.MinLimit * (1 + _variationPercent);
	}
}

defines the CloseToMinLimitStockSpecification specification that allows selection of product stocks that are close to the minimum stock limit. The new class can be used to select from a list of stocks the ones that are close to the minimum limit like this:

CloseToMinLimitStockSpecification closeToMinLimit =
	new CloseToMinLimitStockSpecification(0.1M);
IList stocksCloseToLimit =
	all.Where(p => closeToMinLimit.IsSatisfiedBy(p)).ToList();

The possibility to combine specifications in complex conditions is very powerful and simple to use. If another specification that allows selection of products stocks for which the supply date is not far away is defined like this,

class FarToSupplyDateStockSpecification : ISpecification {
	TimeSpan _span;
	public FarToSupplyDateStockSpecification(TimeSpan span) {
		_span = span;
	}
	public bool IsSatisfiedBy(ProductStock candidate) {
		return DateTime.Now.Add(_span) <= candidate.NextSupplyDate;
	}
}

the two specifications can be used to make a complex selection:

FarToSupplyDateStockSpecification farToSupplyDate =
	new FarToSupplyDateStockSpecification(new TimeSpan(60, 0, 0, 0));
IList stocksLikelyToGoUnderLimit =
	all.Where(p => closeToMinLimit.IsSatisfiedBy(p)
	&& farToSupplyDate.IsSatisfiedBy(p)).ToList();

However if it is necessary to combine specifications to make complex rule explicit classes, the composite pattern is to be used. The same classes can be even used with database objects but of course there are performance issues to consider in this case that require a more complex approach.

Download the complete example SpecificationPattern.zip (3.76 kb) containing the code listed above.

Tags:

Programming

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

RecentComments

Comment RSS

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar