Angel “Java” Lopez on Blog

December 5, 2009

People and software

Filed under: Software Development — ajlopez @ 12:56 pm

Every day, as software developers, we are so concentrated in our interests, in software development, that we lost the big picture: software is good for people. Software industry, beyond our crazy love for programming, has big impact on humankind. I could not imagine one human activity that was not be touched by software, in one or another way.

For me, all started with a tweet by @dbasch:

This is the story:

http://www.reddit.com/r/pics/comments/abam0/help_me_fix_my_last_picture_of_mom/

(read all the comment list)

This is the power of peole and the web, too.

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

November 28, 2009

Generating a model from the Database using AjGenesis

Filed under: AjGenesis, Code Generation, Software Development — ajlopez @ 10:46 pm

AjGenesis, my code generation open source project, use tasks, templates and a free model, to generate text artifacts, usually source code. Most of the examples use models serialized as XML or text files. But you can use anything as the initial input. Even a model could be the output of this process. Month ago, I wrote about generating the model from the database. In my opinion, the database is not the more expressive model to use as starting point, but it is an ubiquitous one (you should admit: I’m improving my English vocabulary…;-)

In my current agile project, the team took the database as the base model. Actually, we are using a more abstract model, but the database was a good asset to use as first model.

So, I back to play with my old example, and improved it. You can download the current example from my Skydrive DatabaseExample01.zip. (the code in flux is in the code repository at Codeplex, under examples\DatabaseExamples).

After download and expand it, you have the folders:

The content of Projects\Northwind\Metadata.xml:

<Metadata>
  <Project>
    <Name>Northwind</Name>
  </Project>
  <Database>
    <Name>Northwind</Name>
    <ConnectionString>server=.\SQLEXPRESS;database=Northwind;Integrated Security=true</ConnectionString>
  </Database>
</Metadata>

It describes the connection string to use to connect to example database. It use Northwind database, in SQL Server (full or express). If you don’t have Northwind, the creation scripts are in Sql folder.

To create the project and entities (the model to generate), run:

MakeModelFromDatabase.cmd

AjGenesis (compiled in Bin folder) begin to work:

The executed commad contains:

Bin\AjGenesis.Console Projects\Northwind\Metadata.xml Tasks\DatabaseProcess.ajg

This command loads Metadata.xml as model in memory, and executes the AjBasic task DatabaseProcess.ajg. This tasks use Information Schema views to obtain information about database structure (using information schema views opens the possibility of database independence).

The task creates Projects\Northwind\Project.xml file:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<Project>
  <Name>Northwind</Name>
  <Model>
    <Entities>
      <Entity Source="Entities/Customer.xml"/>
      <Entity Source="Entities/Shipper.xml"/>
      <Entity Source="Entities/Supplier.xml"/>
      <Entity Source="Entities/Order.xml"/>
      <Entity Source="Entities/Product.xml"/>
      <Entity Source="Entities/OrderDetail.xml"/>
      <Entity Source="Entities/CustomerCustomerDemo.xml"/>
      <Entity Source="Entities/CustomerDemographic.xml"/>
      <Entity Source="Entities/Region.xml"/>
      <Entity Source="Entities/Territory.xml"/>
      <Entity Source="Entities/EmployeeTerritory.xml"/>
      <Entity Source="Entities/Employee.xml"/>
      <Entity Source="Entities/Category.xml"/>
    </Entities>
  </Model>
</Project>

The project and entities are similar to the ones I used in Application generationg using AjGenesis (but there are not the same). Part of the generated file Projects\Northwind\Entities\Customer.xml:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<Entity>
  <Name>Customer</Name>
  <Description>Customer</Description>
  <SetName>Customers</Name>
  <Descriptor>Customer</Descriptor>
  <SetDescriptor>Customers</SetDescriptor>
  <SqlCatalog>Northwind</SqlCatalog>
  <SqlSchema>dbo</SqlSchema>
  <SqlName>Customers</SqlName>
  <Properties>
    <Property>
      <Name>CustomerID</Name>
      <Description>CustomerID</Description>
      <SqlName>CustomerID</SqlName>
      <SqlLength>5</SqlLength>
      <IsKey>True</IsKey>
      <SqlType>nchar</SqlType>
      <SystemType>String</SystemType>
      <IsNullable>False</IsNullable>
    </Property>
....
  </Properties>
</Entity>

The main logic resides in Tasks\DatabaseProcess.ajg, written in AjBasic dynamic language, fragment:

cmd = new System.Data.SqlClient.SqlCommand()
cmd.Connection = conn
cmd.CommandText = "select * from Information_Schema.Tables where Table_Type = 'BASE TABLE'"
conn.Open()
PrintLine "Reader"
dr = cmd.ExecuteReader()
Tables = CreateList()
while dr.Read()
  PrintLine "Table " & dr.Item("Table_Name") & ": " & dr.Item("Table_Type")
  Table = CreateObject()
  Table.SqlCatalog = dr.Item("Table_Catalog")
  Table.SqlSchema = dr.Item("Table_Schema")
  Table.SqlName = dr.Item("Table_Name")
  Table.Name = Table.SqlName.Replace(" ","")

  if IsPlural(Table.Name) then
    Table.SetName = Table.Name
    Table.Name = ToSingular(Table.Name)
  else
    Table.SetName = ToPlural(Table.Name)
  end if

  Table.Descriptor = Table.Name
  Table.SetDescriptor = Table.SetName

  Table.Description = Table.Name

  Tables.Add(Table)
end while
dr.Close()

Possible improvements

This examples is a “proof of concept”. To be used in a more general way, it should be improved. Some points to work:

- Use the generated model to generate a working application, scaffolding or not.

- Support of more meta data obtained via Information Schema

- Try another databases, try a real example

- Relation treatment: detecting cascade and other actions

Another posts about initial models for AjGenesis:

Another model for AjGenesis

Textual model for code generation in AjGenesis

AjGenesis: Generating the model from assemblies

AjGenesis: Generating the model from the database

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

November 22, 2009

Generating code with AJGenesis using NHibernate hbm files

Filed under: .NET, AjGenesis, C Sharp, Code Generation, NHibernate — ajlopez @ 9:50 am

I was working on generating C# classes, using as starting point .hbm NHibernate mapping files. As usual, I wrote an example with AjGenesis, my open source code generation engine.

You can download a first example from my Skydrive:

Examples > AjGenesis > NHibernateMappingExample01.zip

(the code is in the trunk, in the current change set, under examples\NHibernateMappinp:

but if you want to go directly to the example, the Skydrive download I mentioned has all you need to run this demo, including AjGenesis trunk code compiled to binaries).

After expanding the file, you have this content:

 

To create C# classes, execute at command prompt:

GenerateClasses AjFirstExample
GenerateClasses AjTest

To create a .NET project with the .cs and .hbm files, run:

GenerateProject AjFirstExample
GenerateProject AjTest

The generated files are created under Build folder.

The two example projects are AjFirstExample, with two simple plain mappings, and AjTest, with a more interesing mapping, with bags and many to one relations.

Currently, each project is described by a simple Project.xml:

<Project Name="AjTest">
</Project>

This is one of the mapping files in Projects\AjTest\Mappings, Department.hbm:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
  assembly="AjTest.Entities"
  namespace="AjTest.Entities"
  >
  <class name="Department" table="departments">
    <id name="Id" column="Id" type="Int32">
      <generator class="native"/>
    </id>
    <property name="Description" type="String"/>
    <bag name="Employees" lazy="true" inverse="true" cascade="all">
      <key column="IdDepartment"/>
      <one-to-many class="AjTest.Entities.Employee, AjTest.Entities"/>
    </bag>
  </class>
</hibernate-mapping>

This is the generated code for this mapping, Department.generated.cs:

using System;
using System.Collections.Generic;
using Iesi.Collections.Generic;
namespace AjTest.Entities
{
  public class Department {
    public int Id { get; set; }
    public string Description { get; set; }
    public IList<Employee> Employees { get; set; }
    public Department()
    {
      this.Employees = new List<Employee>();
    }
  }
}

Lets take a look to generation process. This is GenerateProject.cmd:

@echo off
set ProjectName=%1%
if "%1%"=="" set ProjectName=AjFirstExample
Bin\AjGenesis.Console.exe Projects\%ProjectName%\Project.xml Tasks\AddMappings.ajg Tasks\BuildCSharp.ajg
xcopy Libraries\*.* Build\%ProjectName%\CSharp\Src\Libraries /Y /Q

The main line is the one containing AjGenesis.Console.exe invocation. Project.xml is loaded in memory. The AddMapping.ajg task is loaded and executed, and then, BuildCSharp.ajg task is processed. AddMapping.ajg code (written in AjBasic, the dinamic language currently used by AjGenesis):

' Add mappings from directory if not specified in Project model
Include("Utilities/Utilities.tpl")
if not Project.Mappings then
  Project.Mappings = CreateList()

  di = new System.IO.DirectoryInfo("Projects/${Project.Name}/Mappings")

  for each fi in di.GetFiles("*.hbm.xml")
    filename = fi.Name
    Project.Mappings.Add(filename.Substring(0, filename.Length - 8))
  end for
end if

It adds the name of mapping files contained in the Mapping folder of the project. A more interesing task is GenerateCSharp.ajg. First, it loads the NHibernate library to use its hbm parser:

include "Utilities/Utilities.tpl"
include "Utilities/FileUtilities.tpl"
include "Utilities/TypeUtilities.tpl"
Include("Utilities/NHibernateUtilities.tpl")
include "Templates/CSharp/UtilitiesCs.tpl"
include "Templates/CSharp/CSharpFunctions.tpl"
AssemblyManager.LoadFrom("Libraries/NHibernate.dll")
parser = new NHibernate.Cfg.MappingSchema.MappingDocumentParser()

Then, it creates the solution and project objects:

if not Project.BuildDir then
  Project.BuildDir = "Build/${Project.Name}/CSharp"
end if
message "Creating Directories..."
FileManager.CreateDirectory(Project.BuildDir)
FileManager.CreateDirectory("${Project.BuildDir}/Sql")
FileManager.CreateDirectory("${Project.BuildDir}/Src")
FileManager.CreateDirectory("${Project.BuildDir}/Src/Libraries")
message "Defining Solution and Projects..."
Project.Solution = CreateObject()
Project.Solution.Guid = "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"
Project.Solution.Projects = CreateList()
message "Defining Entities Project..."
PrjEntities = CreateObject()
PrjEntities.Includes = CreateList()
PrjEntities.Guid = CreateGuid()
PrjEntities.COMGuid = CreateGuid()
Project.Solution.Projects.Add(PrjEntities)
Project.Entities = CreateList()

Then, it iterates on each hbm file, to get information about the entities to generate:

for each MappingName in Project.Mappings
  filename = "Projects/${Project.Name}/Mappings/${MappingName}.hbm.xml"
  mapping = parser.Parse(OpenAsStream(filename))

  for each hbmclass in mapping.Items where IsType(hbmclass, "HbmClass")
    Entity = CreateObject()

    Project.Entities.Add(Entity)

    Entity.ClassName = hbmclass.name
    Entity.Namespace = mapping.namespace

    ' Namespace as default project name for Entities Project
    if not PrjEntities.Name then
      PrjEntities.Name = mapping.namespace
      PrjEntities.Directory = "${Project.BuildDir}/Src/${PrjEntities.Name}"
      FileManager.CreateDirectory(PrjEntities.Directory)
    end if

    Entity.Properties = CreateList()

    if hbmclass.Id then
      Property = CreateObject()
      Property.Name = hbmclass.Id.name
      Property.Type = HbmTypeToCSharp(hbmclass.Id.type1, Entity.Namespace)
      Entity.Properties.Add(Property)
    end if

    for each item in hbmclass.Items
      if IsType(item, "HbmProperty") then
        Property = CreateObject()
        Property.Name = item.name
        Property.Type = HbmTypeToCSharp(item.type1, Entity.Namespace)
        Entity.Properties.Add(Property)
      end if

      if IsType(item, "HbmManyToOne") then
        Property = CreateObject()
        Property.Name = item.name
        Property.Type = HbmTypeToCSharp(item.class, Entity.Namespace)
        Entity.Properties.Add(Property)
      end if
      if IsType(item, "HbmSet") then
        Property = CreateObject()
        Property.Name = item.name
        Property.IsSet = true
        Property.Type = HbmTypeToCSharp(item.Item.class, Entity.Namespace)
        Entity.Properties.Add(Property)
      end if
      if IsType(item, "HbmBag") then
        Property = CreateObject()
        Property.Name = item.name
        Property.IsList = true
        Property.Type = HbmTypeToCSharp(item.Item.class, Entity.Namespace)
        Entity.Properties.Add(Property)
      end if
    end for
  end for
end for

You can extend the capabilities, processing more tags (I should write an example using Meta tags), and detecting more NHibernate mapping idioms. Now, the task generates the code:

for each Entity in Project.Entities
  TransformerManager.Transform("Templates/CSharp/Entity.tpl", "${PrjEntities.Directory}/${Entity.ClassName}.generated.cs", Environment)
  PrjEntities.Includes.Add(CreateFileCs("${Entity.ClassName}.generated"))
end for

The tasks not only generates the .cs files, but it creates a solution and a C# project, copying and embedding the original mapping files:

for each MappingName in Project.Mappings
  filename = "Projects/${Project.Name}/Mappings/${MappingName}.hbm.xml"
  targetfilename = "${PrjEntities.Directory}/${MappingName}.hbm.xml"
  System.IO.File.Copy(filename, targetfilename, true)
  PrjEntities.Includes.Add(CreateFileType(MappingName,"hbm.xml"))
end for
for each CsProject in Project.Solution.Projects where CsProject.ProjectType<>"Web"
  FileManager.CreateDirectory(CsProject.Directory)
  FileManager.CreateDirectory(CsProject.Directory & "/Properties")
  TransformerManager.Transform("Templates/CSharp/CsProject.tpl", "${CsProject.Directory}/${CsProject.Name}.csproj", Environment)
  TransformerManager.Transform("Templates/CSharp/AssemblyInfoCs.tpl", "${CsProject.Directory}/Properties/AssemblyInfo.cs", Environment)
end for
TransformerManager.Transform("Templates/Solution.tpl", "${Project.BuildDir}/Src/${Project.Name}.sln", Environment)

This is the generated solution:

Next steps

I should work in these point:

- Generate a more complete solution (with NHibernate infrastructure, Web Presentation, etc…) as in others AjGenesis examples.

- Support more NHibernate mapping options

- Use meta tags

But now, you are able to play with this example. You can change the templates to generate more artifacts, as Visual Basic .NET source files.

Thanks to @fabiomaulo for pointing me to the NHibernate hbm parser capabilities!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

November 21, 2009

The beauty of Twitter: Example 1

Filed under: .NET, Software Development, Twitter — ajlopez @ 1:17 pm

I’m an avid user of Twitter. Usually, I use TweetDeck as client. Twitter is a simple idea (short messages, you can follow every user with public profile) that has changed the way we are interacting. In the software development arena, Twitter is a great complement (or complete replacement) to reading feeds. This is an example of its efectiveness.

Today, all begins with a tweet from @jfroma, a software developer (he is argentinian, like me:

I didn’t read all his messages, then, I was curious about his comment: Model View View Model pattern. I know José (@jfroma) has working examples of data binding in WPF over models retrieved via NHibernate, so I followed the link and began to read @michaellperry messages. It was my first contact with Michael:

Then, I found his presentation:

Session Detail: Data binding without INotifyPropertyChanged

asking @jfroma:

Now, having more context, I discovered Michael interests in his blog (note: Michael is display Twitter status at left):

http://adventuresinsoftware.com/blog

I discovered the open source library, base of Michael presentation:

http://updatecontrols.net

I started to tweet about this library, and others take notice, like @jyinglee:

 

All started with a simple message. That’s the power of Twitter. There is a “serendipity with help” from interesting people you follow and that follows you.

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

October 31, 2009

NHibernate running in the Azure Cloud

Filed under: .NET, Azure, Cloud Computing, NHibernate — ajlopez @ 1:12 pm

Yesterday, I was talking with Fabio Maulo (@fabiomaulo) about many things, related to software development, teaching programming and, of course, NHibernate. We are living in Buenos Aires, Argentina, and it was a pleasure to talk with him, as usual. Í’m following Fabio in Twitter, and I’m a suscriber of his blog. Fabio is collaborating with NHibernate project for years, and he is a recognized developer in the .NET software community.

He told me details about a site built using NHibernate, and running on SQL Azure. You can see it online (Spanish content, Mexican site):

http://salondetokio.autocosmos.com.mx/

Fabio and his team worked hard to write this site, in less of a month (I’m waiting the team posts, with more detailed info, so, I’ll write only about the public parts here).

Curiously, the site is running using WebForms, but without ViewState, and without form tags embracing the full body inner HTML. All we are waiting Maulo and his team, explaining the implementation details. The code is based on using Model View Presenter, and it was build using tests, mocks and stubs, from presentation to persistence. Hey, Fabio! Please, write about the process and architecture decisions! :-)

More info about NHibernate and Azure:

NHibernate on the cloud: SQL Azure Ayende NHibernate test results on Azure

Quick news NHibernate with SQL Azure Fabio’s first steps “All work… even the SchemaExport.” !!

NHibernate dialect for SQL Azure Adjustments for SchemaExport

I’m collecting links about NHibernate and Azure at:

http://delicious.com/ajlopez/nhibernate+azure

There is an excellent post serie from Brad Adams, explaining Azure, Azure SQL, NHibernate, Silverlight, RIA .NET Service, and more:

Index for Business Apps example for Silverligth 3 RTM and .NET RIA Services July Update

Related to NHibernate and Azure, in that series:

Part 20: NHibernate
Part 23: Azure

Any other project using NHibernate on the cloud?

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

October 15, 2009

A 10 finger Multitouch User Interface

Filed under: Interface, Video — ajlopez @ 10:34 am

This a video demostration new ideas about a multitouch device from http://10gui.com/:

Over a quarter-century ago, Xerox introduced the modern graphical user interface paradigm we today take for granted.
That it has endured is a testament to the genius of its design. But the industry is now at a crossroads: New technologies promise higher-bandwidth interaction, but have yet to find a truly viable implementation.
10/GUI aims to bridge this gap by rethinking the desktop to leverage technology in an intuitive and powerful way.

More info at http://10gui.com/background/. You can follow Clayton Miller in Twitter: @claymill.

It’s interesting to see the drawing pad idea now leveraged with multitouch. This way, we could add multitouch capabilities to any monitor, hardware, instead of using a dedicated multitouch display. The problem: the fingers are out of our vision. The solution: the fingers are tracked and displayed on screen, in the same way we usually track the mouse using the onscreen arrow cursor.

The other interesting point is the “con10uum”, and the finger set interaction. I guess it’s like learning to play a musical instrument: you must practice, but with little effort, the finger gestures seem practical.

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

October 14, 2009

Time for simplicity?

Filed under: Software Development — ajlopez @ 12:00 pm

These days, Ted Neward wrote a very interesting post “Agile is treating the symptons, not the disease” quoting a phrase of Billy Hollis, from Patterns and Practice Submit this week in Redmond. I read:

“A lot of software written back in the 90’s was written by 1 or 2 guys working for just a few months to slam something out and see if it was useful”

“The problem is the complexity of the tools we have available to us today preclude that kind of software development.”

I see the problem is more associated with technologies, not with the tools. Web services, as example. For me, web services are not a tool, like libraries, compilers, or IDE. Web services are technology. Most of the tools (i.e. Eclipse, Visual Studio) are fighting the complexity of the underlying technologies. 1 or 2 guys, today, can still create a wonderful open source library, but try to write with the same team an enterprise application, involving database, communications, security, manageability, instrumentation, and so on. There are lots of details in the underlying technologies to implement, that the complexity of any non trivial application could be (and usually is) dauting.

Back to web services. Did you visit Wikipedia page about that topic, recently? You’ll find dozens of specifications. You could spend weeks or months, trying to grasp all the technicalities involved in WS-Trust, WS-Addressing, WS-Transaction, WS-PutYourWordHere. I guess REST style adoption is a reaction to such madness (REST style, not REST principles, or RESTFul). Sometimes, libraries are coming to rescue, and sometimes, their fail. My preferred example of a failed trying to hide web service complexity is Windows Communication Foundation (WCF). I wrote about this at Windows Communication Foundation configuration madness.

Complexity in software, is not bad for itself. It could be good. Software is in every human activity. Internet popularity, fueled by the World Wide Web adoption, is now in practically every place of our days. As software developers, we are contributing to such progress. We are not pursuing our comfort zone, we are looking for software value.

Now, customer requirements are more challenging: massive multiuser access, scalability, distributed processing, online availability, are usually included in most of current enterprise applications. And there is no simple solution now to cover all the corners.

Said that, complexity is still with us, and it could be fighted. I spend most of my work hours teaching programming, and the rest of the time working on software development. I suffer the complexity of the current state of affairs in software development. The amount of details to take into account (ORMs setups, dependency injection configuration, testing setup, mock libraries, WCF or JBoss configuration… ) is so big, that our minds are lost in the middle of such jungle.

Do you remember Petzoldian age? Lots of lines to write a simple “Hello world” program that runs on Windows. Then, Visual Basic was born. Visual Basic was an effective way to hide the Windows API and behaviour complexity, saving generations of developers of struggling with handles, and LONG values where the mouse coordinates are coming in the Windows messages. That was hell, truly hell.

Do you remember reading VTOCs in IBM disks? Writing Job Control Language? Writing macro assemblers? For each of those tools, there were a solution that hides the underlying complexity, using the “old trick”: raising the level of abstraction. Instead of thinking in registers and sectors, we could manage variables, and SQL statements.

I guess it was end of eighties, beginning of nineties, were the software development in PC arena reach the top of power/complexity ratio (Turbo Pascal, Visual Basic, Access): lots of power, low complexity. Since then, we are in a free fall. The “old trick” of “rise the abstraction level” didn’t embrace again: we are still building software using third generation languages, the macro assemblers of the sixties.

One way to escape is going for the next level of abstraction. We forget about registers and Branch And Link Register instruction and adopted general programming languages. Now, we need to write software in a higher level. My bet: Domain Specific Models and Languages. But it’s only a bet. Using DSLs, DSMs, code generation (do you realize that compiling your C# program is “code generation” NOW?), we could leverage the existing technology, hiding the underlying complexity.

With so many languages, libraries, technologies to use, there is no simple solution to hide all this mess. Note that there are many kinds of complexity. One is the complexity of the customer requirements: business logic, functional requirements. That’s ok. And I think that agile methodologies are attacking such kind of complexity. But the complexity that hurts us now, is the technological one. We should stop the journey towards a Petzoldian age. (recently, I found the concept of Accidental Complexity, in a Rich Hickey talk (hmmm… I guess he named it as incidental complexity). From Wikipedia page about accidental complexity:

Accidental complexity is complexity that arises in computer programs or their development process (computer programming) which is non-essential to the problem to be solved. While essential complexity is inherent and unavoidable, accidental complexity is caused by the approach chosen to solve the problem

)

Another interesting posts, triggered by Neward original one:

Jeffrey Palermos’s Response: “Agile is treating the symptoms, not the disease” by Ted Newardç
Phil Haack’s Software Externalities
Ted Neward’s response to Haack Haacked, but not content; agile still treats the disease 

I have so much to comment about all these writings and thoughts. But they deserve other commenting posts, not to comment now.

I want to remember one more thing here: complexity is not the only challange in software development. Every succesful project could suffer of complexity AND change. Those are the problems agile methodologies are treating: fighting complexity with baby steps, eating an elephant piece by piece, and stop fearing change, embracing it, adopting disciplines to lower the cost of change in the middle of the development.

Another point: with Internet adoption, our current software development culture is flourishing, with so many ideas, reference implementations, open source libraries, patterns, practices, frameworks, and programming languages (there a new set of dynamic languages, mounted over Java and .NET). The Pandora’s box was open: I don’t see any way to close it.

In his cited post, Ted Neward wrote:

Let me rephrase Billy’s talk this way: Where is this decade’s Access?

I have some ideas, to response to that question. But now, I should go to teach .NET: I hope no big complexity hurts today class.

(Note: English is not my mother tongue, so, feel free to suggest corrections to my writing. Most of my ideas about the complexity subject should be expressed in a short way, that could be clear enough, I hope still this post could be understood: this is a fascinanting topic: how to improve the creation of software?)

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

September 23, 2009

Exploring objects

Filed under: Programming Languages, Smalltalk — ajlopez @ 9:38 am

I’m following @jarober (James A. Robertson) in Twitter, Cincom Smalltalk Product Evangelist. He post links about news and resources about Smalltalk, and Cincom Smalltalk in particular. He writes a blog:

http://www.cincomsmalltalk.com/blog/View.ssp

powered by Smalltalk. If you visit his blog, there are many entries about Smalltalk. Recently, Robertson posted:

Smalltalk Daily: Exploring Objects

There is the video:

Robertson wrote:

Many times, you want to do something, know that it can be done – but just aren’t sure how to construct the code to do it. If you have an object, you can usually solve that problem by drilling into it with the inspector and looking at it. Today we learn how to programmatically change workspace page text by drilling into a workspace.

It’s refreshing to see such interaction with objects, so “Smalltalk-way” of interaction.

I should work on my Smalltalk VM (interpreter) AjTalk, to have support of visual interaction. My idea is to wire the current VM with .NET framework, WinForms. In this way, I could leverage the built-in GUI support in the framework. In these day, every language should take advantage of a class framework: .NET and Java are the obvious choice (see Clojure as a “modern” example of this strategy)

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

September 21, 2009

AjSharp programming language: a C#-like dynamic language

Filed under: .NET, AjSharp, Programming Languages — ajlopez @ 8:58 am

During the creation of AjGenesis, my code generation project, I defined an interpreted language, named AjBasic, used to write templates and tasks for code generation process. Last year, I began to separate AjBasic implementation of AjGenesis core, and as a proof of concept, I wrote AjSharp, another interpreted language but with more C#-like syntax, using the same core interpreter that I wrote for AjBasic. The core machine was AjInterpreter. More info at:

AjSharp- a C Sharp-like interpreter, work in progress

Now, this year, I started a clean implementation, inside my AjCodeKatas Google Code. The core interpreter is now AjLanguage, and AjSharp is the language with a parser that relies on the core “virtual machine” to build and execute an abstract tree:

Current source code (under development) can be downloaded from:

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

Variables, expressions and commands

Variables are untyped, and are automatically declared when they are used:

a = 1;
b = 2;

These variables contain integer values, but they can be assigned to values of other types:

a = “one”;
b = “two”;

The common commands are supported:


if (k>0)
 return;

for (k=1; k<=10;
k++)
 sum = k+sum;

while
(j<10)
 DoProcess(j);

foreach (element in
elements)
 AddElement(element);

Conditional expressions can be any expression, not only boolean ones. See above, False value explanation.

Functions and Subroutines

This is the sintax to write down a factorial function:

function Factorial(n)
{
 if
(n<=1)
 return
1;
 return n * Factorial(n-1);
}

The word “sub” can be used to define subroutines.

Functions and subroutines are like any other values. They can be defined without name and assigned to variables:


Add1 = function (n) { return n+1; }
two = Add1(1);
function Apply(func,values)
{
 list = new
List();
 foreach (value in
values)
list.Add(func(value));
 return list;
}
numbers = new
List();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
function Square(n) { return n*n; }
squared = Apply(Square, numbers);
squared2 = Apply(function (n) { return
n*n; }, numbers);


Native .NET objects

One of the design goals of AjLanguage core is to have access to .NET objects. They can be created using the new keyword:


ds = new System.Data.DataSet();
dinfo = new System.IO.DirectoryInfo(“.”);
foreach (fi in dinfo.GetFiles()) {
PrintLine(fi.FullName);
}

Dynamic objects

Dynamic objects can be created using the new keyword. A dynamic object accepts new members (variables and methods):


dynobj = new DynamicObject();
dynobj.FirstName = “Adam”;
dynobj.LastName = "Genesis”;
dynobj.Age =
800;
dynobj.FullName = function() { return FirstName + “ “ + LastName; }

Another notation:

dynobj = new { Name = “Adam”, Age = 800 };

Another notation:


dynobj = new { var FirstName = “Adam”; var LastName = “Genesis”; function
FullName() { return FirstName + “ “ + LastName; }

Dynamic objects are defined automatically, setting theirs properties:


Project.Database.Provider = “…”;
Project.Database.ConnectionString =
“…”;

creates Project dynamic object, with a Database property pointing to another dynamic object. It’s equivalent to:


Project = new DynamicObject();
Project.Database = new
DynamicObject();
Project.Database.Provider =
“…”;
Project.Database.ConnectionString = “…”;

An experiment: lists are defined automatically using Add method:

Project.Entities.Add(new { Name = “Customer”, Table = “dbo.Customers” });

it’s equivalent to:


Project = new DynamicObject();
Project.Entities = new
List();
Project.Entities.Add(new { Name = “Customer”, Table = “dbo.Customers”
});

Dynamic classes

A class can be defined using this sintax:


class Person {
 var FirstName;
 var
LastName;
 var Age;

 function
FullName {
 return FirstName + “ “ +
LastName;
 }
}

A new instance can be created as usual:

adam = new Person() { FirstName = “Adam”, LastName = “Genesis”, Age = 800 };

The instance is dynamic: new members can be attached to it, and methods could be redefined:

adam.FullName = function() { return “The “ + FirstName; };

You can create class as values:

Person = new DynamicClass();

but the interface to add members is still in flux.

Defined Classes

There are some predefined classes:


dynobj = new DynamicObject();
list = new List(); // implementing 
IList
dict= new Dictionary(); // implementing IDictionary

Primitive Functions

A few functions and subroutines are predefined:


Print(“Hello”);
PrintLine(“Hello World”);

There three predefined functions to execute and evaluate dinamic code:

Include("program.ajs");
Evaluate("k+1");
Execute("k=1;");
Include execute the commands in a file. Evaluate parses and evaluate an expression. And Execute compile and execute commands.

False value

Anything that is false, null, zero or empty string, is evaluated as false in conditional expression:


if (k)
 PrintLine(“true”);
else
PrintLine(“false”);

The above command prints “false” on execution, if k is zero or undefined. If a variable is undefined, any access to its member returns null, instead of a null exception:


if (Project.Database.ConnectionString)
PrintLine(“true”);
else
 PrintLine(“false”);

This command prints “false” again, if variable Project is undefined.

Arrays, List and Dictionaries

Native arrays can be defined with length:


firstprimes = new int[10];

or with values:


firstprimes = new int[] { 1, 2, 3, 5, 7, 9 };

A list is created if you need a dynamic array:


numbers[0] = “zero”;
numbers[1] = “one”;
numbers[2] =
“two”;
numbers[3] = “three”;

A dictionary is automatically created if the subindices are not numeric:


numbers[“one”] = 1;
numbers[“two”] = 2;
numbers[“three”] = 3;

If you need more feature, remember, you can use the native .NET framework.

Console interface

The project AjSharp.Console is a console application, where you can enter and execute AjSharp commands (not expressions):

No command to exit, yet. Just control+c in Windows.

Next steps

There are so many features I want to add. Partial list:

- AjBasic as another language over AjLanguage

- Generics support

- Template support (as in AjGenesis)

- Integrate to AjGenesis code generation

- Compile AST to Dynamic Language Runtime

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

September 15, 2009

Lord of the REPLs (Read Eval Print Loops) and CodePad

Filed under: AjLisp, Lisp, Programming Languages — ajlopez @ 9:26 am

These days, I’m implementing interpreted language. My first interest is Clojure, my work is an implementation using C#, written from scratch, you can see the progress at:

http://code.google.com/p/ajlisp/source/browse#svn/trunk/AjSharpure

Last year I wrote a Lisp interpreter AjLisp- a Lisp interpreter in .NET, that I should improve, but past weeks, I started to write an Scheme-like language:

http://code.google.com/p/ajlisp/source/browse#svn/trunk/AjScheme

With so much activity on Lispy languages, I did research about many implementations. My discoveries were collected, as usual, in my delicious:

http://delicious.com/ajlopez/lisp
http://delicious.com/ajlopez/clojure
http://delicious.com/ajlopez/scheme

One of the gems I discovered, is this Google App Engine tool:

http://code.google.com/p/lotrepls/

LotREPLs is a multi-lingual read-eval-print-loop in your browser powered by Google App Engine and the Java runtime. It’s a technical demo, not something to do serious work with. The following languages are supported:

  • BeanShell
  • Clojure
  • JavaScript
  • Python
  • Ruby
  • Scala
  • Scheme

You can try it a:

http://lotrepls.appspot.com/

You can enter your command, and see the result of evaluation, without installing nothing in your machine.

Another discovery, supporting C, C++, D, Haskell, Lua, Ocaml, PHP, Perl, Python, Ruby, Scheme, Tcl, is:

http://codepad.org/

codepad.org is an online compiler/interpreter, and a simple collaboration tool.
Paste your code below, and codepad will run it and give you a short URL you can use to share it in chat or email.

The code you enter and run, can be referenced by an URL, to share with other developers:

Some day, all our tools will be in the browser… :-)

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

Older Posts »

Blog at WordPress.com.