Angel \”Java\” Lopez on Blog

March 13, 2012

Acquarella Syntax Highlighter

Filed under: .NET, Acquarella, C Sharp, Open Source Projects — ajlopez @ 2:15 pm

Past weekend, I was coding a simple and configurable syntax highlighter, in C#, named Acquarella. You can see the result at:

https://github.com/ajlopez/Acquarella

The current solution has a class library project, a console program and a test project:

The idea is to have a library you can reference and use from your projects, in case you need some syntax highlighting functionality. The library takes a text (an string) and, giving the source code language and style name, transform it to another text, using configuration files. There is a more detailes information at project README.md.

Dog fooding, the Token.cs class transformed by Acquarella:

namespace Acquarella.Lexers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class Token
    {
        private string text;
        private int start;
        private int length;
        private TokenType type;

        public Token(TokenType type, string text, int start, int length)
        {
            this.type = type;
            this.text = text;
            this.start = start;
            this.length = length;
        }

        public string Value
        {
            get
            {
                return this.text.Substring(this.start, this.length);
            }
        }

        public TokenType Type { get { return this.type; } }

        public int Start { get { return this.start; } }

        public int Length { get { return this.length; } }
    }
}

Nice :-)

Pending work: Recognize comments, more styles (maybe using css files), more language configurations, extending Lexer (maybe RubyLexer, CSharpLexer, etc.)

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

February 29, 2012

AjBase (1) Implementing an In-Memory Database

Filed under: .NET, AjBase, C Sharp, Open Source Projects — ajlopez @ 8:29 pm

In mid 2009, I started to write an in-memory database, as a coding exercise in C#. These days, I resumed work on that project. Now the code resides in my GitHub repository:

https://github.com/ajlopez/AjBase

Nice history image at Github:

The current solution:

As usual, it was developed using Test-Driven Development. All tests in green:

The key implemented elements are:

Engine: It has a list of created databases (in memory, there is no persistence).

Database: It is the container for tables.

Table: A table has rows, and a RowDefinition.

RowDefinition: it manages the list of columns in a table.

Row: it keeps the values of the table columns, in an object array.

I have a doubt: to keep the schema (RowDefinition) per table, or go for a schema-less (free columns) per row. Now, I will keep the schema approach.

This year, I started to parse SQL statements. SQL is not my preferred languages (too many quirks, etc…), but the project can parse the simplest commands:

I want to add an ADO.NET provider, see the Data namespace:

I have a simple ADO.NET DbConnection, with some very basic (incomplete) ExecuteQuery, ExecuteNonQuery support.

Next steps: complete ADO.NET provider, more SQL parse support, concurrency and transaction support (big challenges! :-) .

Next posts: examples for creating a database, creating a table, inserting data, selecting data, by code and by SQL statements. Meanwhile, you can explore the tests code, to see how to code those examples.

Keep tuned!

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

September 20, 2011

C# 5: Links, News and Resources (1)

Filed under: .NET, C Sharp, C Sharp 5, Links, Programming Languages — ajlopez @ 10:18 am

These are my links about the new C# 5, its history, and the main two new features: compiler as a service, async/wait asynchronous programming. Related post: Windows 8 and WinRT: Links, News and Resources.

Future directions for C# and Visual Basic
http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T
Anders will talk about asynchronous programming and Windows 8 programming, coming in the next version of Visual Studio. He will also discuss the long-lead project “Roslyn”, including object models for code generation, analysis, and refactoring, and upcoming support for scripting and interactive use of C# and Visual Basic.

Mono’s C# Compiler as a Service on Windows.
http://tirania.org/blog/archive/2010/Apr-27.html
The Mono team is proud to bring you a preview of C# 5.0 a few years before our friends in Building 41 do.

Project Roslyn or Compiler-as-a-Service. Bringing flexibility of dynamic languages to C#
http://blog.softelegance.com/net/project-roslyn-or-compiler-as-a-service-bringing-flexibility-of-dynamic-languages-to-c/

Microsoft previews Compiler-as-a-Service software
http://www.computerworld.com/s/article/9220056/Microsoft_previews_Compiler_as_a_Service_software
Microsoft’s Roslyn project will bring the flexibility of dynamic languages to C# and Visual Basic

BUILD conference–day 3, The future of C#
http://lostechies.com/gabrielschenker/2011/09/16/build-conferenceday-3/

Roslyn: Compiler as a Service, not a black-box anymore!
http://www.codequake.com/post/2011/09/16/Roslyn-Compiler-as-a-Service-not-a-black-box-anymore!.aspx

what is C# 5 and where does it come from?
http://stackoverflow.com/questions/4135010/what-is-c-5-and-where-does-it-come-from

Using C# Compiler as a Service in F#, PoshConsole (Powershell)
http://naveensrinivasan.com/2010/05/11/using-c-compiler-as-a-service-in-f-poshconsole-powershell/

C# 4.0 and beyond by Anders Hejlsberg
http://channel9.msdn.com/blogs/matthijs/c-40-and-beyond-by-anders-hejlsberg

C# 5 Async
http://blogs.msdn.com/b/ericlippert/archive/tags/async/

The Future of C# and Visual Basic
http://channel9.msdn.com/events/PDC/PDC10/FT09

Discussion of C# 5′s new async features
http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/00cc045a-f9e6-402c-bffb-feb4fe1e0611/

C# 5 – await and async in ASP.NET « I Came, I Learned, I Blogged
http://evolpin.wordpress.com/2011/05/02/c-5-await-and-async-in-asp-net/

Await Keyword in C# 5 for Async Programming
http://www.pnpguidance.net/post/AwaitKeywordCSharp5AsyncProgramming.aspx

C# 5 Async Support – Await Keyword
http://davidhayden.com/blog/dave/archive/2010/10/31/Csharp5AwaitKeyword.aspx

Coroutines with C# 5′s await — Logos Bible Software Code Blog
http://code.logos.com/blog/2010/10/coroutines_with_c_5s_await.html

Asynchrony in C# 5, Part One
http://blogs.msdn.com/b/ericlippert/archive/2010/10/28/asynchrony-in-c-5-part-one.aspx

C# 5 Async, Part 1: Simplifying Asynchrony – That for which we await : Reed Copsey, Jr.
http://reedcopsey.com/2010/10/28/c-5-async-part-1-simplifying-asynchrony-that-for-which-we-await/

C# 5 – Jon Skeet: Coding Blog
http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx
Check the Eduasync series
http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx

Hiring for Roslyn
http://blogs.msdn.com/b/ericlippert/archive/2010/12/16/hiring-for-roslyn.aspx

C# 5.0 Other news
http://blog.functionalfun.net/2010/11/c-50-other-news.html

C#5 and Meta-Programming
http://codebetter.com/patricksmacchia/2010/05/31/c-5-and-meta-programming/

Progress Reporting in C# 5 Async
http://www.codeproject.com/KB/Parallel_Programming/AncillaryAsyncProgress.aspx

C# 5 Async Exception Handling
http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions

C# 5 Async, Part 1: Simplifying Asynchrony – That for which we await
http://reedcopsey.com/2010/10/28/c-5-async-part-1-simplifying-asynchrony-that-for-which-we-await/

C# 5 New Features
http://www.pluralsight-training.net/microsoft/courses/tableofcontents?courseName=csharp-newincs5

Ok, you have interpreter as a service, dynamic objects, goroutines, channels,
software transaction memory, REPL, distributed code in AjSharp ;-)
http://ajlopez.wordpress.com/category/ajsharp/

My Links
http://www.delicious.com/ajlopez/c%235

Keep tuned, more to come!

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

September 16, 2011

Windows 8 and WinRT: Links, News and Resources

Filed under: .NET, C Sharp, HTML5, JavaScript, Links, Windows 8, WinRT — ajlopez @ 9:38 am

This week Windows 8 was unveiled and introduced into society, at Build Conference. Some links I found interesting about Windows 8, Metro applications, WinRT and .NET programming.

http://en.wikipedia.org/wiki/Windows_8

WinRT demystified – Miguel de Icaza
http://tirania.org/blog/archive/2011/Sep-15.html

Building Windows 8 – Site Home – MSDN Blogs
http://blogs.msdn.com/b/b8/

Build Conference
http://www.buildwindows.com/

Some Thoughts on Windows 8
http://blogs.microsoft.co.il/blogs/sasha/archive/2011/09/14/some-thoughts-on-windows-8.aspx

Sessions at BUILD Day 2 and Windows 8
http://blogs.microsoft.co.il/blogs/sasha/archive/2011/09/15/sessions-at-build-day-2-and-windows-8.aspx

WinRT and .NET in Windows 8
http://blogs.microsoft.co.il/blogs/sasha/archive/2011/09/15/winrt-and-net-in-windows-8.aspx

Bye Bye Brain, first game on Windows 8
http://vimeo.com/29104421

The final days of Adobe Flash
http://www.bytheshaw.com/article/The+final+days+of+Adobe+Flash.html

Windows Developer Preview Metro style app samples
http://code.msdn.microsoft.com/Windows-Developer-Preview-6b53adbb
The Windows Developer Preview Samples Gallery contains a variety of code samples that exercise the various new programming models, platforms, features, and components available for the BUILD conference.

Using WinRT from .NET
http://ermau.com/using-winrt-from-net/

WinRT is Replacing Win32
http://www.winsupersite.com/blog/supersite-blog-39/windows8/winrt-replacing-win32-140605

Build 2011: What Is WinRT, and Is Silverlight Dead?
http://www.readwriteweb.com/hack/2011/09/build-2011-what-is-winrt-and-i.php
The Windows Runtime library (WinRT) is the principal provider of system services for applications in Windows 8 that will be designed to incorporate the new "Metro" style

Functional Fun: Windows Runtime – Dial in the right expectations before reading up
http://blog.functionalfun.net/2011/09/windows-runtime-dial-in-right.html

InfoQ: WinRT: An Object Orientated Replacement for Win32
http://www.infoq.com/news/2011/09/WinRT-API
User interfaces in C++ will be written primarily in XAML.
Overlapping Windows No Longer Exist <— I remember Windows 1.0 ;-)
Under WinRT all APIs are exposed as objects that C# and VB can consume directly.
The fourth major language for Windows 8 is JavaScript.
All Metro Applications Must be Digitally Signed.

Sinofsky outlines the Windows 8 vision | News | TechRadar UK
http://www.techradar.com/news/software/operating-systems/sinofsky-outlines-the-windows-8-vision-1027101?src=rss&attr=all

Best place to discuss Windows 8
http://blogs.msdn.com/b/b8/archive/2011/09/14/best-place-to-discuss-windows-8.aspx

Metro style browsing and plug-in free HTML5
http://blogs.msdn.com/b/b8/archive/2011/09/14/metro-style-browsing-and-plug-in-free-html5.aspx

Experiencing Windows 8 touch on Windows 7 hardware
http://blogs.msdn.com/b/b8/archive/2011/09/13/experiencing-windows-8-touch-on-windows-7-hardware.aspx

Welcome to Windows 8 – The Developer Preview
http://blogs.msdn.com/b/b8/archive/2011/09/13/welcome-to-windows-8-the-developer-preview.aspx

JAPF » Blog Archive » BUILD: WinRT, Silverlight, WPF, XAML
http://www.japf.fr/2011/09/build-winrt-silverlight-wpf-xaml/

Building real-time web apps with WebSockets using IIS, ASP.NET and WCF | BUILD2011 | Channel 9
http://channel9.msdn.com/Events/BUILD/BUILD2011/SAC-807T

A bad picture is worth a thousand long discussions. « Doug Seven
http://dougseven.com/2011/09/15/a-bad-picture-is-worth-a-thousand-long-discussions/

Internet Explorer 10 Metro will not support Flash, Silverlight – Tech Products & Geek News | Geek.com
http://www.geek.com/articles/news/internet-explorer-10-metro-will-not-support-flash-silverlight-20110915/

C#er : IMage: Windows 8: What you Need to Know
http://csharperimage.jeremylikness.com/2011/09/windows-8-what-you-need-to-know.html?m=1

"What’s New in the .NET Framework 4.5 Developer Preview" (and Yield is coming to VB.Net!) – Greg’s Cool [Insert Clever Name] of the Day
http://coolthingoftheday.blogspot.com/2011/09/new-in-net-framework-45-developer.html

Guide to Installing and Booting Windows 8 Developer Preview off a VHD (Virtual Hard Disk)
http://www.hanselman.com/blog/GuideToInstallingAndBootingWindows8DeveloperPreviewOffAVHDVirtualHardDisk.aspx

A few facts about Microsoft’s new Windows Runtime « Tim Anderson’s ITWriting
http://www.itwriting.com/blog/4866-a-few-facts-about-microsofts-new-windows-runtime.html

OK, so I think HTML/JS for Metro apps is a good idea « codeface
http://blog.markrendle.net/2011/09/15/ok-so-i-think-the-htmljs-for-metro-apps-is-a-good-idea/

I know what you’re thinking, and you’re wrong. « Doug Seven
http://dougseven.com/2011/09/14/i-know-what-youre-thinking-and-youre-wrong/
Metro, Silverlight, .NET

Microsoft to developers: Metro is your future | ZDNet
http://www.zdnet.com/blog/microsoft/microsoft-to-developers-metro-is-your-future/10611

Microsoft Unveils ‘Reimagined’ Windows 8 at Build Event — Visual Studio Magazine
http://visualstudiomagazine.com/articles/2011/09/13/build-preview-of-windows-8.aspx

Welcome to Windows 8 – The Developer Preview – Building Windows 8 – Site Home – MSDN Blogs
http://blogs.msdn.com/b/b8/archive/2011/09/13/welcome-to-windows-8-the-developer-preview.aspx

Delivering fast boot times in Windows 8 – Building Windows 8 – Site Home – MSDN Blogs
http://blogs.msdn.com/b/b8/archive/2011/09/08/delivering-fast-boot-times-in-windows-8.aspx

Windows 8 will feature Hyper-V guest OS machine virtualization | ExtremeTech
http://www.extremetech.com/computing/95339-windows-8-will-feature-hyper-v-guest-os-machine-virtualization?obref=obinsite

"A sort of PC": how Windows 8 will invade tablets (and why it might work)
http://arstechnica.com/microsoft/news/2011/08/a-sort-of-pc-how-windows-8-will-invade-tablets-and-why-it-might-work.ars

Improving our file management basics: copy, move, rename, and delete – Building Windows 8 – Site Home – MSDN Blogs
http://blogs.msdn.com/b/b8/archive/2011/08/23/improving-our-file-management-basics-copy-move-rename-and-delete.aspx

My Links
http://www.delicious.com/ajlopez/windows8
http://www.delicious.com/ajlopez/winrt
http://www.delicious.com/ajlopez/vs2011

Angel "OMGC++Again" Lopez

September 13, 2011

AjScript: Javascript-Alike interpreter in C# (2) Expressions

Previous Post

As in other interpreters, one key piece is the Expression, something to evaluate during the execution of a program. In AjScript (repository) I have an IExpression:

public interface IExpression
{
    object Evaluate(IContext context);
}

These are the implemented expression in current solution:

A simple expression, ConstantExpression:

public class ConstantExpression : IExpression
{
    private object value;
    public ConstantExpression(object value)
    {
        this.value = value;
    }
    public object Value { get { return this.value; } }
    public object Evaluate(IContext context)
    {
        return this.value;
    }
}

A bit more interesting, VariableExpression, given a name, and a context, returns the value of a named variable:

public class VariableExpression : IExpression
{
    private string name;
    public VariableExpression(string name)
    {
        this.name = name;
    }
    public string Name { get { return this.name; } }
    public object Evaluate(IContext context)
    {
        return context.GetValue(this.name);
    }
}

Sometimes, an expression has one or two parameters. I have UnaryExpression, BinaryExpression as abstract class. The BinaryExpression code:

public abstract class BinaryExpression : IExpression
{
    private IExpression leftExpression;
    private IExpression rigthExpression;
    public BinaryExpression(IExpression left, IExpression right)
    {
        this.leftExpression = left;
        this.rigthExpression = right;
    }
    public IExpression LeftExpression { get { return this.leftExpression; } }
    public IExpression RightExpression { get { return this.rigthExpression; } }
    public abstract object Apply(object leftValue, object rightValue);
    public object Evaluate(IContext context)
    {
        object leftValue = this.leftExpression.Evaluate(context);
        object rightValue = this.rigthExpression.Evaluate(context);
        return this.Apply(leftValue, rightValue);
    }
}

Note that the Apply method is abstract. A concrete implementation:

using Microsoft.VisualBasic.CompilerServices;
public class ConcatenateExpression : BinaryExpression
{
    public ConcatenateExpression(IExpression left, IExpression right)
        : base(left, right)
    {
    }
    public override object Apply(object leftValue, object rightValue)
    {
        if (leftValue == null)
            leftValue = string.Empty;
        if (rightValue == null)
            rightValue = string.Empty;
        return Operators.ConcatenateObject(leftValue, rightValue);
    }
}

I'm a lazy programmer: note the use of Visual Basic Operators. I could write a custom implementation. I have all the tests in place to refactor this expression.

I didn't write all expressions at once. An example: I wrote Context class using tests, and then the VariableExpression class using tests. Then I added variable support in Parser, and evaluates simple expressions that use constants and variables. I use this pattern many times: add a new base class (Context, Function…), add a new expression, improve lexer/parser to support the new expression, use the expression in code tests, etc.

Upcoming topics: commands, function implementation, closures, hoisting, native objects. And AjScript examples.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

September 12, 2011

AjScript: Javascript-Alike interpreter in C# (1) Base Interface

Filed under: .NET, AjScript, C Sharp, JavaScript, Open Source Projects, Programming Languages — ajlopez @ 11:12 am

Next Post

I’m working on implementing a C# interpreter of AjScript: a Javascript-alike language. The code in progress is published at:

https://github.com/ajlopez/AjScript

Initially it was at my AjCodeKatas project in Google Code, but now I prefer GitHub: it able me to have more projects. Google Code has a limit in the number of projects, so I was forced to put little projects in the AjCodeKata. Now, GitHub frees me from that limitation. And GitHub with its public forks and pull request has its charm.

The idea is to have an interpreter with the “good parts” of Javascript. I should discuss with myself about inheritance support. But a key point that it supports is: access to native .NET objects. You can write var obj = new System.IO.DirectoryInfo(‘.’) directly in AjScript. And you can invoke AjScript code from a .NET application.

But now, I will present the base interfaces of this interpreter. First, IObject, the interface that every AjScript object should implement:

 

public interface IObject
{
    IFunction Function { get; }
    object GetValue(string name);
    void SetValue(string name, object value);
    ICollection<string> GetNames();
    object Invoke(string name, object[] parameters);
    object Invoke(ICallable method, object[] parameters);
}

Interesting, every object has a Function property: that function is the “class” of the object, the function used in the new command.

To keep the variable names and their values, I have an IContext interface:

public interface IContext
{
    IContext RootContext { get; }
    ReturnValue ReturnValue { get; set;  }
    void SetValue(string name, object value);
    object GetValue(string name);
    void DefineVariable(string name);
}

Note that a context could have a parent context, in order to support nested context. ReturnValue property is used to detect the return command that could have executed many levels inside the current execution.

Any AjScript method implements ICallable:

public interface ICallable
{
    int Arity { get; }
    IContext Context { get; }
    object Invoke(IContext context, object @this, object[] arguments);
}

Note that functions are IObject and ICallable but with the power of create a new object:

public interface IFunction : ICallable, IObject
{
    object NewInstance(object[] parameters);
}

Upcoming posts: examples, closures, native object management, lexer and parser, test and TDD (I wrote the interpreter using TDD, I have > 80% code coverage).

Pending work: implements Function with arguments, prototype with .constructor and other properties, typeof, Javascript original “classes” like Number and others, decide what features of Javascript are “in” and what ones are “out”. Suggestions?

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

June 29, 2011

AjModel: Model by Code (Part 2) Models and Repositories

Filed under: .NET, AjModel, ASP.NET MVC, C Sharp, Software Development — ajlopez @ 10:50 am

Previous Post

I was working on my AjModel project. You can download the source code from my AjCodeKatas Project under trunk/AjModel. I added a Model class, and enhanced Entity Model and Property Model:

The model refers all the entity models I want to have in the coded model. AjModel enrich the already coded classes of your model, adding information like human descriptions, legends, etc. The idea is to generate automatically a UI for the coded model, for different technologies. The enhanced model could have nothing new, and AjModel should generate the initial UI, at runtime. The enhanced model could be consumed from differents UI technologies: the “proof of concept” application is an ASP.NET MVC one.

There is a fluent interface for EntityModel, and PropertyModel. There are extension methods, and wrappers/builders, like:

Some usage examples, borrowed from my tests:

EntityModel<Customer> model = new EntityModel<Customer>();
FluentEntityModel<Customer> fluentModel = new FluentEntityModel<Customer>(model);
fluentModel.Name("BusinessCustomer")
    .SetName("BusinessCustomers")
    .Descriptor("Business Customer")
    .SetDescriptor("Business Customers");
//..
Model model = new Model();
var entityModel = model.ForEntity<Customer>();
entityModel.Descriptor("Business Customer")
    .SetDescriptor("Business Customers");
//..
Model model = new Model();
model.ForEntity<Customer>().Property(
    c => c.Name,
    pm => pm.Descriptor("Customer Name")
            .Description("The Customer Name")
);

Where pm is a FluentPropertyModel.

In the UI process, I want to retrieve an entity by its identity. Or I need to get a list of entities to build a grid. Then, I need something to manage the entities, as a list. I implemented repositories in a context, to be implemented by different technologies. The current implementation is an in-memory list:

I’m planning to write adapter examples to NHibernate, Entity Framework, but those ideas are still in blueprints ;-)

Usage examples:

this.entityModel = new EntityModel<Customer>();
this.domain = new SimpleDomain();
this.repository = new Repository<Customer>(this.entityModel, this.domain.Customers);

Note that the repository is a typed one, using generics. And it needs an entity model, and (in the current implementation) an IList to manage. The context contains a list of repositories:

var entityModel = new EntityModel<Customer>();
var domain = new SimpleDomain();
var repository = new Repository<Customer>(entityModel, domain.Customers);
var context = new Context();
context.AddRepository(this.repository);
var repo = context.GetRepository("Customer");

SimpleDomain is a class I created for tests:

public class SimpleDomain
{
    public SimpleDomain()
    {
        this.Customers = new List<Customer>();
        for (int k = 1; k <= 10; k++)
        {
            Customer customer = new Customer()
            {
                Id = k,
                Name = string.Format("Customer {0}", k)
            };
            this.Customers.Add(customer);
        }
    }
    public IList<Customer> Customers { get; set; }
    public ProductList Products { get; set; }
}

A model can be created using a class like SimpleDomain. It discovers IList public properties:

var model = new Model(typeof(SimpleDomain));
var entityModel = model.GetEntityModel("Customer");
Assert.IsNotNull(entityModel);
entityModel = model.GetEntityModel("Product");
Assert.IsNotNull(entityModel);

I plan to add all types in an assembly that satisfied a predicate, like having “Entities” in their namespaces.

Entities can be added and retrieved to/from a repository:

Customer entity = new Customer() { Id = 1000 };
this.repository.AddEntity(entity);
Customer newEntity = this.repository.GetEntity(1000);

And they can be removed, too.

Entity model has the info to create new entities from values: a feature I will use in the UI:

EntityModel<Person> model = new EntityModel<Person>();
IDictionary<string, object> values = new Dictionary<string, object>()
{
    { "Id", 1 },
    { "FirstName", "Joe" },
    { "LastName", "Doe" },
    { "Age", "30" }
};
object entity = model.NewEntity(values);

In the next posts, I will discuss MVC UI implementation. All is work in progress, but the project is taking shape. And I having fun coding it ;-)

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

June 24, 2011

Writing An Application Using TDD (Part 5) Adding Views

Previous Post
Next Post

Now I have some tests in place, I add some MVC views in this step. You can download the code from my AjCodeKatas Google Project, under trunk/AppTdd/Step04. So, this post has few new tests: it shows how we can build the interface AFTER the tests, and WITHOUT having a database or service layer, yet.

First, I added a new Site.master master page and style.css (borrowed from another ASP.NET MVC project)

I added a new Home controller:

Then, I added a view using the context menu over the Index method:

 

I modified the master page code, to have a new entry in its menu:

I added a new view associated to Index action in Subject controller:

I selected the “List” view content, and “Subject” as the type to use in the model.

But the controller method is:

public ActionResult Index()
{
    return View(subjects);
}

It uses a subject list, that is injected in the constructor by the tests:

public SubjectController(IList<Subject> subjects)
{
    this.subjects = subjects;
}

But wait! That list is injected by the tests. Now, I should inject in the normal process of the controller, in its parameter-less constructor:

public SubjectController()
    : this(Domain.Instance.Subjects)
{
}

I added a Domain.Instance to use as our in-memory domain:

public class Domain
{
    private static Domain instance = new Domain();
    private Domain()
    {
        this.Subjects = new List<Subject>()
        {
            new Subject() { Id = 1, Name = "Mathematics" },
            new Subject() { Id = 2, Name = "Physics" },
            new Subject() { Id = 3, Name = "Biology" },
            new Subject() { Id = 4, Name = "Literature" }
        };
    }
    public static Domain Instance { get { return instance; } }
    public IList<Subject> Subjects { get; set; }
}

I changed the links generated in the Index view from:

to use the Id property as primary key:

This is the result:

I created the other views using the Visual Studio “Add View…” wizard:

I had some missing actions, I wrote a new:

public ActionResult Edit(int id)
{
    var model = this.subjects.Where(s => s.Id == id).FirstOrDefault();
    return View(model);
}

With tests! ;-)

[TestMethod]
public void GetSubjectForEdit()
{
    IList<Subject> subjects = GetSubjects();
    SubjectController controller = new SubjectController(subjects);
    ActionResult result = controller.Edit(1);
    Assert.IsNotNull(result);
    Assert.IsInstanceOfType(result, typeof(ViewResult));
    ViewResult viewResult = (ViewResult)result;
    Assert.IsInstanceOfType(viewResult.ViewData.Model, typeof(Subject));
    Subject model = (Subject)viewResult.ViewData.Model;
    Assert.AreEqual(1, model.Id);
    Assert.AreEqual("Mathematics", model.Name);
}

Curiously, I detected a “bad” test. I had written in my AddSubject test:

Assert.IsTrue(subjects.Any(s => s.Name == "Chemistry"));
Assert.AreEqual(4, subject.Id);

But the new id should be 5 (our testable list has 4 predefined subjects):

Assert.IsTrue(subjects.Any(s => s.Name == "Chemistry"));
Assert.AreEqual(5, subject.Id);

I fixed the code and the controller action, run the web application, and voila!

Main points:

- I am using an in-memory domain.

- The views run over the already tested actions

No service layer or persistence yet. Next steps: add more classes to domain (Books), service layer (using test), and some persistence.

Interesting related post about development with TDD without a database (or adding it after the tests) by @RonJeffries:

But We Need a Database … Don’t We? | xProgramming.com

See? We Don’t Need a Database … Yet | xProgramming.com

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

June 16, 2011

AjModel, Model by Code (Part 1) Inception

Filed under: .NET, AjModel, ASP.NET MVC, C Sharp, Software Development — ajlopez @ 11:12 am

Next Post

I’m a big proponent of raise the level of abstraction, separate problems from solutions. One of my project, AjGenesis, is dedicated to design free models that can produce (via code generation) applications in different platforms and technologies. Now, I want to explore another way: instead of code generation, I want to use simple runtime code to define and use an enhanced model.

First ideas

It’s natural to have a model (domain model, business model, you can name it):

You can have main classes (entities), associations, collection associations, services with methods, etc. And you can build all these artifacts using TDD, or not. But these artifacts ARE the system core. But you need to enhance the model, if you want to expose in a user interface. An example from AjGenesis:

<Entity>
    <Name>Customer</Name>
    <Description>Customer</Description>
    <SetName>Customers</SetName>
    <Descriptor>Customer</Descriptor>
    <SetDescriptor>Customers</SetDescriptor>
    <SqlTable>customers</SqlTable>
    <Properties>
	<Property>
	    <Name>Id</Name>
	    <Description>Id</Description>
	    <Type>Id</Type>
	    <SqlType>int</SqlType>
	</Property>
	<Property>
	    <Name>Name</Name>
	    <Description>Name</Description>
	    <Type>Text</Type>
	    <SqlType>varchar(200)</SqlType>
	    <Required>true</Required>
	</Property>
    </Properties>
</Entity>

This abstract model has attributes like Name, SetName to be uses as names in code generation, and Descriptor, Description to be used in interface (user communication) code generation. These additional attributes is part of I named “Enhanced Model”: a model with additional properties, information that help to describe the model in human terms. Maybe, I could add some additional data (SQL field lengths, etc), to be used in persistence, but it is not a target in my initial steps:

Interface models depend of the base technology to use. Once the enhanced model describe the entities and properties in user terms, view models can be built based on such information. And if the “human name” of an entity or property is missing, the code name can be used. There is “default” data and behavior in an enhanced model: use the model, Luke! In the following paragraphs are code that shows the way to enhance the model. But one key design decision is: if the model is not enhanced, I could generate all the interface from the plain model.

Some code

Then, I began to code AjModel. You can see my progress in my AjCodeKatas Project under trunk/AjModel. My first enhanced models are dedicated to Entities (main objects in the model) and their Properties:

This is a test model class, a simple Customer:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Notes { get; set; }
}

Then, one test:

[TestMethod]
public void GetProperties()
{
    EntityModel model = new EntityModel(typeof(Customer));
    var properties = model.Properties;
    Assert.IsNotNull(properties);
    Assert.AreEqual(4, properties.Count);
    Assert.AreEqual("Id", properties.First().Name);
    Assert.AreEqual("Name", properties.Skip(1).First().Name);
    Assert.AreEqual("Address", properties.Skip(2).First().Name);
    Assert.AreEqual("Notes", properties.Skip(3).First().Name);
}

Upcoming: ServiceModel (describing services), and Model (containing the list of Entity and Service Models). More properties in EntityModel, like .Descriptor, .SetDescriptor, etc.

Each interface model depends of the final technology. As a proof of concept, I started to define an ASP.NET MVC interface model, in AjModel.WebMvc project. There is an EntityController, now dedicated to Customer:

public ActionResult Index()
{
    var model = new EntityListViewModel();
    model.Entities = Domain.Instance.Customers;
    model.EntityModel = new EntityModel(typeof(Customer));
    return View(model);
}

Domain.Instance.Customers is a in-memory list of customers. Some code in view:

<h2>
    <%= this.Model.Title %></h2>
<table>
    <tr>
        <% foreach (var property in this.Model.EntityModel.Properties)
           {
        %>
        <th>
            <%= Html.Encode(property.Name) %>
        </th>
        <%} %>
    </tr>
    <% foreach (var entity in this.Model.Entities)
       { %>
       <tr>
       <% foreach (var property in this.Model.EntityModel.Properties)
          { %>
          <td><%= property.GetValue(entity) %></td>
       <%} %>
       </tr>
    <%} %>
</table>

Next steps

I want to have a fluent interface like:

model.ForEntity<Customer>()
      .Descriptor("Customer")
      .SetDescriptor("Customers")

And I want to use Expression<Func…> to leverage code validation (define properties by code instead by name):

model.ForEntity<Customer>()
     .ForProperty(c => c.Name)
         .Description("Customer Name")
         .IsRequired()

Or something like:

model.ForEntity<Customer>()
     .Property(c => c.Name,
          pm => pm.Description("Customer Name")
                  .IsRequired()
        )
     .Property(c => c.Address,
          pm => pm.Description("Customer Address")
        )

where pm is a PropertyModel. .ForProperty returns a PropertyModel fluent interface. But .Property returns a fluent EntityModel builder, so it uses the second parameter to extended the selected property.

But no committed code in repo, yet. You know, I’m working in my free time, I’m still need to work, family fortune dissolved in Montecarlo tables ;-)

Code Generation vs Runtime

I’m still prefer code generation from an free-defined model: it makes a clear distinction of the problem and the technological solution. And it can be easily adapted to the changes of technologies and language (Java vs Scala vs C# vs … whatever upcoming combination.. ;-) . But most developers prefer to work with code. That's the reason for this experiment. Since late nineties, I know morphic  in Smalltalk world (thanks to SUGAR Smalltalk User Group Argentina meetings, now defunct) See History of Morphic. And Naked Objects is another way to expose the model to the user/developer. See Naked Objects, Wikipedia. I read:

1. All business logic should be encapsulated onto the domain objects. This principle is not unique to naked objects: it is just a strong commitment to encapsulation.

2. The user interface should be a direct representation of the domain objects, with all user actions consisting, explicitly, of creating or retrieving domain objects and/or invoking methods on those objects. This principle is also not unique to naked objects: it is just a specific interpretation of an object-oriented user interface (OOUI).

The original idea in the naked objects pattern arises from the combination of these two, to form the third principle:

3. The user interface should be created 100% automatically from the definition of the domain objects. This may be done using several different technologies, including source code generation; implementations of the naked objects pattern to date have favoured the technology of reflection.

The naked objects pattern was first described formally in Richard Pawson's PhD thesis[1] which includes a thorough investigation of various antecedents and inspirations for the pattern including, for example, the Morphic user interface.

This century, I found Magritte.

Now, it’s time to explore the runtime/reflection way in .NET. Pros: developers can enhanced the model using their IDEs and code; their can create new interface models. Cons: it's limited to the underlying technology, in my case: .NET; new dynamic interface models can be hard to create; custom extension by manual code could be not easy.

Ok, enough for today, back to coding (and to work).

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

June 1, 2011

Writing An Application Using TDD (Part 4) Update and Insert

Previous Post
Next Post

In the previous post, I implemented the retrieve of one Subject data. No view is implemented yet. I’m writing the tests and then, implementing the code in the controller. It’s time to add a new Subject, using an action in the controller:

This was my first test:

[TestMethod]
public void AddSubject()
{
    IList<Subject> subjects = GetSubjects();
    Subject subject = new Subject() { Name = "Chemistry" };
    SubjectController controller = new SubjectController(subjects);
    ActionResult result = controller.Create(subject);
    Assert.IsNotNull(result);
    Assert.IsTrue(subjects.Any(s => s.Name == "Chemistry"));
    Assert.AreNotEqual(0, subject.Id);
}

GetSubjects() is a helper method presented in the previous post. It returns a list of test subjects. I added a new action in the controller class, so the solution could be compiled:

public ActionResult Create(Subject subject)
{
    throw new NotImplementedException();
}

The test was red:

Then, I completed the action method, with the minimal code to pass the test:

public ActionResult Create(Subject subject)
{
   subject.Id = this.subjects.Max(s => s.Id);
   subjects.Add(subject);
   return RedirectToAction("Index");
}

But I want to redirect to the details view for the new item. I added assertions to the test:

RedirectToRouteResult redirect = (RedirectToRouteResult)result;
Assert.IsTrue(string.IsNullOrEmpty(redirect.RouteName));
Assert.IsTrue(redirect.RouteValues.ContainsKey("id"));
Assert.AreEqual(subject.Id, redirect.RouteValues["id"]);
Assert.IsTrue(redirect.RouteValues.ContainsKey("action"));
Assert.AreEqual("Details", redirect.RouteValues["action"]);

I changed the action code, only to comply with the new requirement:

public ActionResult Create(Subject subject)
{
    subject.Id = this.subjects.Max(s => s.Id);
    subjects.Add(subject);
    return RedirectToAction("Details", new { id = subject.Id });
}

Now, the test is red:

I followed a similar path to write and pass the test for update a subject. This is the current version of the test:

[TestMethod]
public void UpdateSubject()
{
    IList<Subject> subjects = GetSubjects();
    Subject literature = subjects.Where(s => s.Name == "Literature").FirstOrDefault();
    Subject subject = new Subject() { Name = "SciFi" };
    SubjectController controller = new SubjectController(subjects);
    ActionResult result = controller.Update(literature.Id, subject);
    Assert.IsNotNull(result);
    Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
    RedirectToRouteResult redirect = (RedirectToRouteResult)result;
    Assert.IsTrue(string.IsNullOrEmpty(redirect.RouteName));
    Assert.IsTrue(redirect.RouteValues.ContainsKey("id"));
    Assert.AreEqual(literature.Id, redirect.RouteValues["id"]);
    Assert.IsTrue(redirect.RouteValues.ContainsKey("action"));
    Assert.AreEqual("Details", redirect.RouteValues["action"]);
    Assert.IsTrue(subjects.Any(s => s.Name == "SciFi"));
    Assert.AreEqual(literature.Id, subjects.Where(s => s.Name == "SciFi").Single().Id);
}

The current controller action:

public ActionResult Update(int id, Subject subject)
{
    Subject toupdate = this.subjects.Where(s => s.Id == id).Single();
    toupdate.Name = subject.Name;
    return RedirectToAction("Details", new { id = id });
}

All the tests are green:

Some warnings: the tests are testing two ouputs: the change in the domain (a simple list) and the result action (an MVC concern). I should refactor (in an upcoming post) the implemention of the controller to separate the updates applied to the domain from the navigation results. I wrote the example in this way to show how to refactor the obtained code to have a better implementation. I could add tests that exercises the expected behavior when the subject to add is already in the domain, or the subject to update is missing.

Other note: there is no views yet. But I have the test in place to have confidence: when I added the views, I will have the expected behavior tested and in place.

Keep tuned!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

Older Posts »

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.