Angel “Java” Lopez on Blog

June 21, 2009

Code Generation for Mere Mortals Framework

In the current project, my agile team is developing a full health application (Medusa Project), using Mere Mortals Framework as a base to business objects, persistence and WinForm/ASP.NET presentation. You can download a trial version of this framework:

http://www.oakleafsd.com/

There is a feature list at

http://www.oakleafsd.com/MMNetFeatures/pgMMNetFeatures.htm

You can download the developer Guide from

MM .NET Developer’s Guide

The framework were developed by Kevin McNeish, Microsoft MVP, president and Chief Architect of Oak Leaf Enterprise. The framework supports typed entities, but in the background, it’s based on datasets. You can generate a business objects project from templates, and with a code generator provided by the product, you can populate that library with classes, derived from a database.

In my team, we are feeding metadata reading database information, and then, we are generating a full ASP.NET Web Application, a business object libraries, stored procedures, and DDLs for database regeneration. All using AjGenesis, my open source code generation utility. I should post about the experience. The seed task and templates, were derived from the example:

AjGenesis- Generating the model from the database

In this post, I describe another approach: starting from an abstract model, I’m generating:

- Scripts for creating the database
- Business Objects a la Mere Mortals class library
- WinForm project with maintenance forms

I posted about generating applications from an abstract model at:

Application Generation using AjGenesis

but caveat: AjGenesis is based in a free model. You can model what you want. The trivial example:

Code Generation with AjGenesis- A Hello World application

The model

You can download the example from the Codeplex project site example page:

MereMortalsExamples200906.zip

It contains:

The model resides in Projects/AjFirstExample/Project.xml

<Project>

    <Name>AjFirstExample</Name>

    <Description>First Example using AjGenesis</Description>

    <Prefix>AjFE</Prefix>

    <Domain>com.ajlopez</Domain>

    <CompanyName>ajlopez</CompanyName>

    <Model>

        <Entities>

            <Entity Source="Entities/Customer.xml"/>

            <Entity Source="Entities/Supplier.xml"/>

        </Entities>

        <Lists>

            <List Entity="Customer"/>

            <List Entity="Supplier"/>

        </Lists>

        <Forms>

            <Form Entity="Customer"/>

            <Form Entity="Supplier"/>

        </Forms>

        <Views>

            <View Entity="Customer"/>

            <View Entity="Supplier"/>

        </Views>

    </Model>

</Project>

There are two entities, Customer and Supplier. The Customer entity:

<Entity>

    <Name>Customer</Name>

    <Description>Customer Entity</Description>

    <SetName>Customers</SetName>

    <Descriptor>Customer</Descriptor>

    <SetDescriptor>Customers</SetDescriptor>

    <SqlTable>Customers</SqlTable>


    <Properties>

 

        <Property>

            <Name>Id</Name>

            <Type>Id</Type>

        </Property>

 

        <Property>

            <Name>Name</Name>

            <Type>Text</Type>

            <SqlType>varchar(200)</SqlType>

        </Property>

 

        <Property>

            <Name>Address</Name>

            <Type>Text</Type>

            <SqlType>text</SqlType>

        </Property>

 

        <Property>

            <Name>Notes</Name>

            <Type>Text</Type>

            <SqlType>text</SqlType>

        </Property>

 

    </Properties>

</Entity>

 

There is a technology dependent model at Projects/AjFirstExample/Technologies/VbNet3.xml:

<Technology>

    <Programming>

        <Dialect>VbNet3</Dialect>

    </Programming>

    <Database>

        <Dialect>MsSql</Dialect>

        <Name>AjFirstExampleMM</Name>

        <Host>(local)</Host>

    </Database>

</Technology>

You can change the host to .\SQLEXPRESS if you don’t have a running MS SQL Server. You can add <Username> and <Password> if you are using SQL security. If there are not present, the code uses integrated security.

Generating the application

You must download AjGenesis current release 0.5 from http://ajlgenesis.codeplex.com. Add the bin directory to your path. Then, run from the example directory:

GenerateProject.cmd AjFirstExample VbNet3

The first parameter is the project name, and the second is the technology to use. The command invokes

AjGenesis.Console Projects\%Project%\Project.xml tasks\BuildProject.ajg  Projects\%Project%\Technologies\%Technology%.xml tasks\BuildTechnology.ajg tasks\BuildProg.ajg tasks\BuildSql.ajg

It loads the project model, execute the BuildProject task, then loads the technology model, executes the BuildTechnology tasks. The task BuildProg generates the code, and BuildSql generates the DDL to create the database.

It creates a new folder, Build, containing

In Sql folder, you find the ExecuteAll.cmd to create the database

You can run it with a parameter, specifiying your server:

ExecuteAll.cmd Bombadil

If you run this command without a parameter, it uses the host specified in the technology model. There is a VS 2008 solution with two projects, in Src folder:

You can load and compile in Visual Studio (you must have Mere Mortals Fwk installed).

The class library project contains Mere Mortal business objects definition (using partial classes, data access calling stored procedures, rules)

The Win form project has two maintenance forms, for Customers and Suppliers:

Well, it’s not the “killer application” but it’s running:

You can download the generated solution, from my Skydrive

AjFirstExampleMereMortals.zip

Conclusions

Using an abstract model, we can generate the usual text artifacts required by Mere Mortals fwk (or any other framework, technology). With partial classes and separated files, we can regenerate the code from the model, without losing our manual code. We can augment the generated code with automatic validation, rules, and any coding standard we were using.

But the main point, for me, it’s that using an abstract model, we are separating the important core from the technicalities. I could regenerate the application with other base framework, other languages, but our model could be the same. The model describes what we want. Tasks and templates compose an expert system, that knows HOW to get what we want as application.

Angel “Java” Lopez

http://www.ajlopez.com/en

http://twitter.com/ajlopez

June 3, 2009

First NHibernate 2.x example

Filed under: .NET, C Sharp, NHibernate — ajlopez @ 9:23 am

I was working creating a .NET solution, containing a minimal NHibernate 2.x example. I’m using NHibernate GA 2.0.1 binary distribution, following the reference manual instruction.

You can download the source code from my Skydrive folder:

NHibernateExample1.zip 

I was using the online documentation from

http://nhforge.org/doc/nh/en/

and I built the same manual in .pdf format, from the SVN trunk:

https://nhibernate.svn.sourceforge.net/svnroot/nhibernate

You can download the manual in .pdf from

nhibernate-reference.pdf

The solution contains two projects: a class library, and a console application:

The domain contains only one class, Cat (following the first example included in the NHibernate doc):

namespace NHibernateExample1.Domain
{
    public class Cat
    {
        private string id;
        private string name;
        private char sex;
        private float weight;

        public Cat()
        {
        }
        public virtual string Id
        {
            get { return id; }
            set { id = value; }
        }

        public virtual string Name
        {
            get { return name; }
            set { name = value; }
        }

        public virtual char Sex
        {
            get { return sex; }
            set { sex = value; }
        }

        public virtual float Weight
        {
            get { return weight; }
            set { weight = value; }
        }
    }
}

There is an embedded resource describing the mapping: Cat.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="NHibernateExample1.Domain" assembly="NHibernateExample1.Domain">
  <class name="Cat" table="Cats">
    <!-- A 32 hex character is our surrogate key. It's automatically
generated by NHibernate with the UUID pattern. -->
    <id name="Id">
      <column name="CatId" sql-type="char(32)" not-null="true"/>
      <generator class="uuid.hex" />
    </id>
    <!-- A cat has to have a name, but it shouldn' be too long. -->
    <property name="Name">
      <column name="Name" length="16" not-null="true" />
    </property>
    <property name="Sex" />
    <property name="Weight" />
  </class>
</hibernate-mapping>

There is an ExecuteAll.cmd in Sql folder, that creates the database (you can pass the MS SQL Server as parameter, .\SQLEXPRESS is the default value):

The console application is simple: configures NHibernate, gets a session, inserts new objects inside a transaction, executes a query, and list the result:

        static void Main(string[] args)
        {
            ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();

            ISession session = sessionFactory.OpenSession();
            ITransaction tx = session.BeginTransaction();

            Cat cat;

            cat = new Cat() { Name = "Moe", Sex = 'M', Weight = 9.0f };

            session.Save(cat);

            cat = new Cat() { Name = "Larry", Sex = 'M', Weight = 8.5f };

            session.Save(cat);

            cat = new Cat() { Name = "Sue", Sex = 'F', Weight = 7.5f };

            session.Save(cat);

            tx.Commit();

            IQuery query = session.CreateQuery("select c from Cat as c where c.Sex = :sex");

            query.SetCharacter("sex", 'M');

            foreach (Cat kitty in query.Enumerable())
                System.Console.Out.WriteLine("Male Cat: " + kitty.Name);

            session.Close();

            System.Console.ReadLine();
        }

Running the console application inserts this data in the database:

The example is simple. Now I have an updated running example using NHibernate 2.0, I’m planning to update my AjGenesis templates for NHibernate to use that version.

Angel “Java” Lopez

http://www.ajlopez.com/en

http://twitter.com/ajlopez

May 28, 2009

AjGenesisCF: code generation for .NET Compact Framework

Filed under: .NET, AjGenesis, Code Generation — ajlopez @ 10:29 am

Thanks to Federico Boerr and his team, there is a new version of AjGenesis, rewritten to run using .NET Compact Framework:

http://ajgenesiscf.codeplex.com/

This version uses only the reflection features supported by CF. Then, you don’t have all the original features. As example, the creation of instances using parameters in the constructor is not supported in CF. But you can compile AjGenesis as a .DLL, and invoke it from your program, use templates, tasks and AjBasic. The published code contains a sample program.

More information about the original program at:

http://ajgenesis.codeplex.com
http://ajlopez.wordpress.com/category/ajgenesis/

Angel “Java” Lopez
http://www.ajlopez.com/en
http://twitter.com/ajlopez

April 27, 2009

Presenting AjCat

Filed under: .NET, C Sharp, Programming Languages — ajlopez @ 9:16 am

Some weeks ago, I was working on an interpreter of the Cat language:

The Cat Programming Language

Cat is a functional stack-based programming language inspired by the Joy programming language. The primary differences is that Cat provides a static type system with type inferencing (like ML or Haskell), and a term rewriting macro language extension language called MetaCat.

Cat is a high-level intermediate language translation that can also be used as a stand alone language for simple application development. In this way it occupies a similar niche to PostScript. Cat is also an appropriate language for teaching of basic programming concepts.

If you are not familiar with Cat language, you can learn more at:

Cat Tutorial
Cat Specification
Cat Primitives

I published the code as part of my Code Katas Google code project. It’s named AjCat:

http://code.google.com/p/ajcodekatas/source/browse/#svn/trunk/AjCat

The solution contains three projects:

The implementation is not complete. It’s only support integers, no .NET object support yet, and no graphics primitives.

Running the console program, you can enter and evaluate expressions:

This code is dedicated to Rodolfo Finocchieti (@rodolfof in Twitter) who pointed me to Cat language, a fascinanting idea.

Tests are green:

And good code coverage

Angel “Java” Lopez
http://www.ajlopez.com/
http://twitter.com/ajlopez

April 22, 2009

Introducing AjProcessor (Part 1)

Filed under: .NET, AjMessages, Grid Computing, Windows Communication Foundation — ajlopez @ 7:05 pm

Last month, I was working in AjProcessor code, as part of my code katas Google project:

http://code.google.com/p/ajcodekatas/source/browse#svn/trunk/AjProcessor

The idea is the evolution of some exploratory coding with AjMessages and other examples. I want to have an application, based in message passing, that can be run in a grid of heterogeneus machines. The application could 
be partitioned in steps, and each step could run in the same host machine, or on a another machine. The deployment in machines should be transparent to the writing of the application code.

Some of those goals were reached with AjMessages, but this time, I want a more clear kick off, based on the lesson learnt of my previous attempts.

First, I want to write down some basic ideas, to explain the motivation of the initial code written for AjProcessor. The basic idea, is to have message processors. A message processor is a code that receives a message, and process it.

 

The message has a payload (an arbitrary object, string, anything), and additional properties, with key/value.

Another essential brick in this lego-like application, is the element that publish messages. That is, there is a publisher:

 

An outgoing message could be received by any other code. The same message can be processed by more than one processor:

 

It’s like the publish/subscribe pattern. Another pattern to take into account, is a router-like component. Depending on the message (property, content), it could be send to different targets.

 

Frequently, a component will implement both roles, message processor and message publisher. In order to call plain old .NET objects, it would be nice to have a processor that receives a message, take some part of the message (i.e. the payload), and send it as a parameter to one its methods. The return value could feed a new message.

 

The components can be arranged as a chain, implementing a pipeline to process a message:

 

A more complex arrangement could receive a message, and forward it to different pipelines, according to some property or content in incoming message.

 

(this concept could be mapped to an application in AjMessage, but without the idea of distributed processing). A more interesting idea is to run that kind of pipeline routers in many machines

 

AjProcessor infrastructure is in charge of the serialization/routing/deserialization of messages between host machine. It could be WCF or anything else. The basic idea is to have a pluggable transport.

Well, these are the seed ideas behind the project. In an upcoming post, I’ll explain some of the current code (only few interfaces and classes, now).

Angel “Java” Lopez
http://www.ajlopez.com/en
http://twitter.com/ajlopez

March 30, 2009

First sabbatical week 2009

Filed under: Software Development — ajlopez @ 9:13 am

Past Friday I started my first sabbatical week of this year. This “extended week” should end at Monday April 6th. But the current project I’m working on was extended one more week. Usually, I don’t teach classes, nor give any speech, but this time, cause of rescheduling of other activities, I’m going to give an Scrum course and a .NET class.

So, I decided to commit to some technical goals, but to be accomplished in two weeks, before April 13rd.

The list includes:

- Write a blog post to explain the motivations and initial ideas to implements in AjProcessor.

- Minor improvements (.NET object access support), medium-size refactoring, and first published version of AjCat, and post.

- Add full support to blocks, block context, indexed variables in AjTalk, and post.

- Write and publish a post about AjPepsi.

- Initial code of a new open source project, this time in Java, and post.

Well, that’s all. I would like to put more focus in this week, but this time, I should attend other duties.

As usual, I’ll publish a closure post with the resulting outcomes.

Angel “Java” Lopez
http://www.ajlopez.com/
http://twitter.com/ajlopez

March 11, 2009

TDD and Code Kata: Writing a Lexer for AjRuby

Filed under: C Sharp, Programming Languages, Software Development — ajlopez @ 7:20 am

Usually, I write programs as code katas, to train me in some software development topics. During last months, I wrote many mini interpreters, using TDD-like approach, code coverage, and C#. Past week, I was working in the kickoff of yet another one, AjRuby. The starting point: the lexer.

A lexer is a program that analizes a source code text, and returns the tokens, the "words" that compose the program. In the case of AjRuby, I wrote a lexer that follows the Ruby language grammar. It’s not complete yet, but it’s working.

You can see my progress at my code katas Google code project:

http://code.google.com/p/ajcodekatas/source/browse#svn/trunk/AjRuby

The solution has a library project, and a test project:

It has a Token class, that represents each token:

public class Token { public string Value { get; set; } public TokenType TokenType { get; set; } }

The TokenType is an enum:

public enum TokenType { Name, Integer, Real, Boolean, String, Operator, Separator }

There is a LexerTest.cs class, containing tests like:

[TestMethod] public void ShouldProcessName() { Lexer lexer = new Lexer("name"); Token token; token = lexer.NextToken(); Assert.IsNotNull(token); Assert.AreEqual(TokenType.Name, token.TokenType); Assert.AreEqual("name", token.Value); token = lexer.NextToken(); Assert.IsNull(token); }

There is a test for every kind of token to be processed. Other example:

[TestMethod] public void ShouldProcessNameWithInitialUnderscore() { Lexer lexer = new Lexer("_name"); Token token; token = lexer.NextToken(); Assert.IsNotNull(token); Assert.AreEqual(TokenType.Name, token.TokenType); Assert.AreEqual("_name", token.Value); token = lexer.NextToken(); Assert.IsNull(token); }

I wrote the tests using TDD ideas: write the test, compile with error, fix the compiler issues, run the tests in red, fix them, get green status. I skipped most of the refactor steps. I guess the tested code could be improved, but by now, I’m trying to get a working lexer. The tests are in green state, good!

My goal is to have > 80% of code coverage, at any time during the project development:

It’s good to write something only for fun and learning. For me, it’s part of the continuous improvement every software developer should pursuit.

Angel "Java" Lopez

http://www.ajlopez.com/en

http://twitter.com/ajlopez

March 9, 2009

Distributed Web Crawler using AjMessages

Filed under: .NET, AjMessages, C Sharp — ajlopez @ 8:09 am

Last January, I update my AjMessages project to support communication using DSS/CCR and Windows Communication Foundation. AjMessages is a program that can run in a distributed way, sending asynchronous messages from one logical node to another. The logical nodes can be hosted in one or more physical machines. More info about AjMessages at:

AjMessages- a message processor
Distributed Applications with AjMessages using DSS/CCR

You can download the source code from

http://www.codeplex.com/ajmessages

I had the idea of write a distributed message processor. Years ago, I wrote my first attempt, named AjServer

Hacia el AjServer (Spanish Post)

After that project, I met Fabriq ideas and implementation, where there are logical message handler, that can be distributed in a transparent way, via configuration:

In 2007, I wrote the first version of AjMessages, as a proof of concept: I could reproduce most of the Fabriq ideas, trying to raise some abstraction, in order to have a little more flexibility. Fabriq was more SOA-oriented. AjMessages is oriented to arbitrary message processing, to have a grid-like application.

This is the current AjMessages solution:

There is core project, and two transport projects: one for WCF support, and another to DSS/CCR (Microsoft Robotics technology). If you don’t have DSS/CCR, you can remove the related projects. The core AjMessages is free of dependencies on such technologies. AjMessages.SampleApp contains simple handler: a decrement handler, that takes a message with an integer, and produces a new message with a new decremented integer. AjMessages.WebCrawler implements the message and handlers that make a distributed web crawler application. You can run it in only one machine or in many hosts.

Each AjMessage message has:

Body: an arbitrary payload
Headers: additional information, key-value.
Action: describing the target of the message, using pattern Application/Node/Action

(more detail in the mentioned post AjMessages- a message processor)

Let’s explore the distributed web crawler example. This application is composed by nodes, that can be orchestrated to visit a link, and gets from that initial page all the links and related pages, up to a level. Logically, it can be described as:

The first messages is send to the node Controller, action Dispatch. It contains the initial page to visit. The message is enriched, and passed to node Controller, action Resolve. It’s in charge to keep a list of visited page, and to control the deep of processing. If the link is aproved, then a message is send to node Downloader, action Download. The content of the page is downloaded, added to the message, and forwarded to node Harvester, action Harvest. This action analyze the content of the page, and emits many message, one for each link found in  it. The recipient of the new links is the node Resolver, action Resolve. So, the process continues up to visit all pages (with a limit on the deep of processing).

This application can be described using an XML configuration file, example:

<?xml version="1.0" encoding="utf-8" ?> <AjMessages> <Application Name="WebCrawler"> <Node Name="Dispatcher"> <Handler Name="DispatcherHandler" Type="AjMessages.WebCrawler.Handlers.Dispatcher, AjMessages.WebCrawler"/> <Action Name="Dispatch" Handler="DispatcherHandler"/> </Node> <Node Name="Harvester"> <Handler Name="HarvesterHandler" Type="AjMessages.WebCrawler.Handlers.Harvester, AjMessages.WebCrawler"/> <Action Name="Harvest" Handler="HarvesterHandler"/> </Node> <Node Name="Downloader"> <Handler Name="DownloaderHandler" Type="AjMessages.WebCrawler.Handlers.Downloader, AjMessages.WebCrawler"/> <Action Name="Download" Handler="DownloaderHandler"/> </Node> <Node Name="Controller"> <Handler Name="ResolverHandler" Type="AjMessages.WebCrawler.Handlers.Resolver, AjMessages.WebCrawler"/> <Action Name="Resolve" Handler="ResolverHandler"/> </Node> </Application> </AjMessages>

An application is composed by nodes. Each node can be viewed as a “logical class”. Each node can handle Actions, that are the targets of messages. An action can be composed by one or more steps, of message handler. This is the extensibility point of the application: you must provided the steps, the message handler, and write a configuration file to orchestrate the message processing.

But one thing is the application, and another its distribution over physical machines. You can have two hosts, and install different logical nodes in each one:

In this diagram, the Dispatcher and Resolver are in one host, and the Downloader and Harvester in the other one. But you can put harversters in each host, or in twenty machines. It’s up to you how to distribute the load of the work. When a message is sent to a target, AjMessage forwards it to an appropiate host, that have a node capable of attending the message action.

The distribution of logical nodes into physical host is defined via configuration, an example:

<?xml version="1.0" encoding="utf-8" ?> <AjMessages> <Host Name="Server1" Address="http://localhost:50002/AjMessages" Activate="true"> <Application Name="AjMessages"> <Node Name="Administration"/> </Application> <Application Name="WebCrawler"> <Node Name="Controller"/> <Node Name="Dispatcher"/> <Node Name="Harvester"/> <Node Name="Downloader"/> </Application> </Host> <Host Name="Server2" Address="http://localhost:50003/AjMessages"> <Application Name="AjMessages"> <Node Name="Administration"/> </Application> <Application Name="WebCrawler"> <Node Name="Dispatcher"/> <Node Name="Harvester"/> <Node Name="Downloader"/> </Application> </Host> </AjMessages>

Running the Web Crawler example

You can test the program, launching two host, in the same machine. Run the console program AjMessage.Console. Then enter the command

fork

This command launches a second host. Now, you are ready to configure the two hosts. In the first one, enter:

load ConfigurationServer1.xml

This file loads the initial AjMessage application, and define a WCF endpoint to listen messages. Then, enter:

load ConfigurationWebCrawler.xml

This command loads the Web Crawler node definitions (no deploy info yet). The third command define the distribution in hosts:

load ConfigurationWebCrawlerNode1.xml

Now, back to second host console. Enter the corresponding commands:

load ConfigurationServer2.xml
load ConfigurationWebCrawler.xml
load ConfigurationWebCrawlerNode2.xml

You are ready to launch the first web crawling. Go to first console, and enter:

send WebCrawler/Dispatcher/Dispatch http://ajlopez.zoomblog.com

(that is my Spanish non technical blog… ;-)

The web crawling begins to work, in both consoles. A typical view on first console:

Next steps

I should fix some problems in DSS/CCR tranport (I could run a simpler app, but not the web crawler). Two points to implements:

- Remote configuration of nodes
- Distribution of message handlers bits to remote nodes
- One configuration for all the nodes (now, each node is configured separately)

I began to experiment with a more abstract way of processing message, that should implement uses cases like:

- A simple hello world
- Decrement example, as in AjMessages sample app (see AjMessage.SampleApp)
- Distributed web crawler
- Enterprise Service Bus-like app

My first steps at:

http://code.google.com/p/ajcodekatas/source/browse#svn/trunk/AjProcessor

But the project is still in its infancy. Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com/
http://twitter.com/ajlopez

March 4, 2009

Windows Communication Foundation configuration madness

Filed under: .NET, Software Development, Windows Communication Foundation — ajlopez @ 10:09 am

Windows Communication Foundation was created to support the creation of distributed applicacions, trying to give us a library of communication tools, so we can reuse it, without writing the service gateways and service interfaces from scratch. Technologies like web services, evolved, and there are many versions and details to take into account if you want to have secure, relaible and interoperable communication.

The concept of a Service Model, is a great advance. But today, I have to raise my hand, only to point to something makes WCF a convoluted solution. I’m referring to WCF configuration.

If you want to use any WCF feature, beyond the simplest one, quickly you’ll be fighting with the configuration options of this beast. What is the sympton? If you miss some minimal part, your channel doesn’t work. If you miss some configuration option when creating a certificate, if you forget to do one step in a dozen or more of “to do list”, your call will not work. And you have to manage a lot of concepts, like certificates, tokens, issuers, chain of trust, behaviors, bindings, endpoints, identities, custom bindings, factories,  service hosts, channel factories, security options, enumeration types, extensions methods, and …. I could continue for hours.

A minimal example. I just browsing the web, and I found the article

WCF (Windows Communication Foundation) Example

I read there:

Being able to switch the transport layer from TCP (Secure SSL) into HTTP with some simple code, that’s amazing!

Yes, but

I did have some problems, though. The tcpBinding.Security.Mode = SecurityMode.None; is very crucial on both sides. I’m not sure what it does, but it does not turn off the security completely as I have read in my references. There is still SSL encryption, but on a lower level. It is possible to add certificates to the connection, which also makes the connection more secure.

That’s the problem. If you play exploring the different properties and methods of binding and endpoints, you’ll enter a maze without visible exit. Notice that the author is not sure about one of the configuration he is using. And this is only one option: you have dozens more to set, if you want to fine tune your service.

Yes, there is declarative configuration. You can use the WCF configuration wizard:

Ok, can you see the three tabgs, at right? They have more options to fill and understand! Can you see the tree at left? It’s only the top of the iceberg. If you expand the bindings, you’ll enter a new Narnia world:

More properties to fill, and one more tabs! You begin to feel uneasy. If you have courage, create and expand  anything in the advanced branch:

The tree is becoming a amazonic forest. I could take snapshops of each branch this wizard exposes, to publish a complete volume. Most of these options ARE REQUIRED if you want to secure your service, use tokens issued by other systems, define the authentication of the client and service, and more. And my point is: if you fail in filling and defining a minimal part of this stuff, your system is a sand castle, a tower of cards in delicated equilibrium. This is the butterfly effect: a fly of a butterfly in one configuration file, could create an storm in your system. You must pay attention to too many details. It’s common to have to pay attention to details in software development. But I guess in this case, it’s too much: it’s insane to any single human mind.

In other systems, you have lot of options, too (remember the count of properties of any form control?). But you don’t need to master all (or halft) of the details. That is not the case with WCF configuration. This state of affairs sucks. And if you like to write down directly the XML configuration, you have to fight with something like this:

 

There are few uglier thing I met in my 30 years of software development (I could enumerate: EJB configuration, Cocoon ideas, Job Control Language in the old IBM mainframes…).

I have a theory. Enrico Fermi asked: if the extraterrestials exist, where are they? The story is: they exist. They began to study our planet (remember first “flying soucers”? They was seen at Mount Rainer at forties, near Seattle… yes, they were researching the origin of all this…). For decades, they read our literature, watch our film productions, made controlled experiments with some human beings. But when they began to study WCF and EJB configuration, our planet was doomed: they declared it under quarantine, we will be out of contact, isolated from the rest of the galaxy for the next ten thousand years. The humankind is a crazy civilization, there is no hope for our future.

Ok, I must stop whining. WCF has a great service model: now, it can manage JSON, XML, and it’s prepared to be flexible and extensible. But sometimes, we must stop the ball, and balance the flexibility with the accompaning complexity. This post is the result of days of fightings with WCF, WCF examples, documentations and guidelines.

Angel “Java” Lopez
http://www.ajlopez.com/
http://twitter.com/ajlopez

February 25, 2009

Presenting AjLambda: Lambda calculus implementation in C#

Filed under: .NET, C Sharp, Functional Programming, Programming Languages — ajlopez @ 8:21 am

I was working on my “code kate” AjLambda, a Lambda Calculus implementation, written using C#:

http://code.google.com/p/ajcodekatas/source/browse/#svn/trunk/AjLambda

(If you are new to Lambda Calculus notation, there are tutorial links at the end of this post)

Yes! It’s the geeky project I wrote this year…;-).. The solution is simple, it contains three projects:

It has a core library, AjLambda, a test project AjLambda.Tests and an AjLambda.Console program to run. The core library has few main classes:

Expression is the base abstract class. .Reduce is the method that implements the reduction of an expression. .Replaces is used to change a variable by other. Sometimes, it’s needed to choose a new name for a variable, that it doesn’t collides with another free variable name. .FreeVariables is the method to obtain the list of free variables in an expression. For example, in the lambda expression:

\x.xy

x and y are variables, but y is a free variable, and x is a bound parameter.

Variable express the variable (a lower-case letter in this implementation). Lambda is the lamba (parameter plus body). The lambda is entered using:

\x.x

The short version with multiple parameters is supported:

\xy.yx

This is the .Reduce implementation for Pair (a pair of expression, left and right): 

public override Expression Reduce() { if (this.left is Lambda) return ((Lambda)this.left).Apply(this.right); Expression newLeft = this.left.Reduce(); if (newLeft != this.left) return new Pair(newLeft, this.right); Expression newRight = this.right.Reduce(); if (newRight == this.right) return this; return new Pair(newLeft, newRight); }

Running AjLamnda.Console with a parameter:

AjLambda.Console Boot.l

loads the auxiliary file Boot.l, where I defined some predefined functions:

; True
T = \xy.x
; False
F = \xy.y
; And
AND = \ab.abF
; If Then Else
IFTHENELSE = \x.x
; Natural numbers
0 = \fx.x
1 = \fx.fx
2 = \fx.f(fx)
3 = \fx.f(f(fx))
; Succesor
SUCC = \nfx.f(nfx)
; Add
ADD = \nmfx.nf(mfx)
; Multiply
MULT = \nmf.n(mf)
; Is Zero
ISZERO = \nxy.n(\z.y)x
; Predecessor
PRED = \nfx.n(\gh.h(gf))(\u.x)(\u.u)
; Pair Functions
PAIR = \xyf.fxy
FIRST = \p.pT
SECOND = \p.pF
NIL = \x.T
NULL = \p.p(\xy.F)
; Fixed Point
A = \xy.y(xxy)
Y = A A
; Factorial
FACT = Y (\f.\n.IFTHENELSE (ISZERO n) (1) (MULT n (f (PRED n)))))

You can ask about the predefined names. I defined the first natural numbers, including zero:

Names are words that begin with upper case letter. Variable names are lower letter (from ‘a’ thru ‘z’, only one letter per variable).

As usual, I defined SUCC and PRED (succesor and predecessor functions):

Each reduction step is printed, until no more reduce is possible.

You can define new functions using Name = <expression>:

More information about Lambda Calculus at:

Lecture Notes on the Lambda Calculus (pdf) (excellent paper to learn Lambda Calculus)

Peter Selinger- Papers

Lambda calculus – Wikipedia, the free encyclopedia

A Tutorial Introduction to the Lambda Calculus

http://delicious.com/ajlopez/lambda

Lambda Calculus implementation from Fred’s Page

Angel “Java” Lopez
http://www.ajlopez.com/
http://twitter.com/ajlopez

Older Posts »

Blog at WordPress.com.