Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

The Time Machine

4.91/5 (13 votes)
9 May 2012CPOL6 min read 35.6K   1.2K  
Long time strategy of software design and development

Time machine

1. Introduction

Recently, one aviation designer told me that he had a lot of ideas. However his colleagues threatened him with a madhouse. It is a typical reason for Russian immigration. I was not threatened with a madhouse by my colleagues who found that my ideas are stupid. The best chance had persons which did not have any ideas. Now designer is 60 years old, and he is a former designer. I would not like his destiny for myself. I would like implementation of my ideas. But I understand that waiting for a better time is not a good way. Men from the above picture returned to the past for fixing past bugs. But reality does not support this option. Past bugs cannot be fixed. So I invented "The time machine", for the future. I did not know my future. However, I would like to have good software for my unknown future. Any good software should support Change Pattern and Change Pattern paradigm can be regarded as the time machine. However, my time machine predicts time by decades. The most important was usage of Category Theory as the main idea. I shall write a lot about it. In this article, some particular ideas are described. My invention of time of time machine has three purposes. Besides time machine as itself, I would like to show an example for talents. If talent did not have an opportunity for implementation of his ideas, then he/she can invent time machine. Moreover, I would like to show a good style of software development. At 2002, I was engaged by 3D graphics. I had a need for multiwindow mode. De facto DirectX did not support multiwindow mode. So I should use OpenGL. I found that high coupling to OpenGL is not a good idea. Later, I found that Autodesk 3ds Max can use both OpenGL and DirectX. I developed an abstract layer for 3D Graphics for the future. For many years, I was not engaged by 3D Graphics. At 2010, I had resumed 3D Graphics development, and implemented WPF implementation of abstract 3D Graphics level. I found that high coupled to OpenGL software could not be adapted to other 3D Graphics technologies. I had no need for abstract layer at present, however I will need it in future.

2. Background. Metadriver

Math contains levels of theories. First level arithmetic contains theorems about integers. Second level theorems (metatheorems) are theorems about first level theorems. The third arithmetic, fourth one, etc. The duality theorem concerns to theorems and therefore it is metatheorem. In this chapter, metadriver is discussed. Following code can be regarded as metadriver. This code is looking for singletons of objects which implement one interface:

C#
/// <summary>
/// Gets interfaces from assembly (Searching of driver assembly)
/// </summary>
/// <typeparam name="T">Interface type</typeparam>
/// <param name="assembly">Assembly</param>
/// <returns>Interface objects</returns>
public static IEnumerable<T> GetInterfaces<T>(this Assembly assembly) where T : class
{
    Type[] types = assembly.GetTypes(); // Assembly types
    string st = typeof(T).FullName;     // Interface full name
    foreach (Type t in types)
    {
        Type ti = t.GetInterface(st);   // Gets interface
        if (ti == null)
        {
            continue;
        }
        FieldInfo fi = t.GetField("Singleton"); // Gets Singleton field
        if (fi != null)
        {
            yield return fi.GetValue(null) as T; // yeild Singleton
        }
    }
}

Following code snippet contains search of singletons in a set of assemblies:

C#
/// <summary>
/// Gets interfaces
/// </summary>
/// <typeparam name="T">Interface type</typeparam>
/// <param name="directory">Directory</param>
/// <returns>Interface objects</returns>
public static IEnumerable<T> GetInterfaces<T>(this string directory) where T : class
{
    string[] fn = Directory.GetFiles(directory, "*.dll");   // Dll files
    Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies(); // Current domain assemblies
    List<string> l = new List<string>();
    foreach (Assembly a in ass) // Looking for objects in loaded assemblies
    {
        l.Add(a.Location);
        IEnumerable<T> en = a.GetInterfaces<T>();
        foreach (T t in en)
        {
            yield return t;
        }
    }
    foreach (string f in fn) // Looking for objects in directory
    {
        if (!l.Contains(f))
        {
           IEnumerable<T> en = Assembly.LoadFile(f).GetInterfaces<T>();
           foreach (T t in en)
           {
               yield return t;
           }
        }
    }
}

/// <summary>
/// Gets interfaces from base directory
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <returns>Interfaces</returns>
public static IEnumerable<T> GetInterfacesFromBaseDirectory<T>() where T : class
{
    return AppDomain.CurrentDomain.BaseDirectory.GetInterfaces<T>();
}

In many cases, one driver only is needed. Following code contains looking for a single driver:

C#
/// <summary>
/// Gets first interface object
/// </summary>
/// <typeparam name="T">Type of interface</typeparam>
/// <param name="directory">Directory</param>
/// <returns>First object</returns>
public static T GetFirstInterfaceObject<T>(this string directory) where T : class
{
    IEnumerable<T> en = directory.GetInterfaces<T>();
    foreach (T t in en)
    {
        return t;
    }
    return null;
}

/// <summary>
/// Gets first interface object
/// </summary>
/// <typeparam name="T">Type of interface</typeparam>
/// <returns>First object</returns>
public static T GetFirstInterfaceObjectFromBaseDirectory<T>() where T : class
{
    return AppDomain.CurrentDomain.BaseDirectory.GetFirstInterfaceObject<T>();
}

Instruction of the above code usage is very simple. Dynamic link library file (files) should be copied to base directory of current domain.

3 Applications

3D Graphics

The following code represents common 3D Graphics interface:

C#
/// <summary>
/// Factory of 3D objects and cameras
/// </summary>
public interface IPositionObjectFactory
{
    /// <summary>
    /// Creates  3D object
    /// </summary>
    /// <param name="type">Object's type</param>
    /// <returns>The object</returns>
    object CreateObject(string type);

    /// <summary>
    /// Creates new camera
    /// </summary>
    /// <returns></returns>
    Camera NewCamera();

    /// <summary>
    /// Creates editor of properties of camera
    /// </summary>
    /// <param name="camera">The camera</param>
    /// <returns>The property editor</returns>
    object CreateForm(Camera camera);

    /// <summary>
    /// Creates editor of properties of visible object
    /// </summary>
    /// <param name="position">Position of object</param>
    /// <param name="visible">Visible object</param>
    /// <returns>Editor of properties of visible object</returns>
    object CreateForm(IPosition position, IVisible visible);

    /// <summary>
    /// Type of camera
    /// </summary>
    Type CameraType
    {
        get;
    }

    /// <summary>
    /// Creates label on desktop
    /// </summary>
    /// <param name="obj">Object for label</param>
    /// <returns>The label</returns>
    IObjectLabel CreateLabel(object obj);

    /// <summary>
    /// Creates label of visible object
    /// </summary>
    /// <param name="position">Position of object</param>
    /// <param name="visible">Visible object</param>
    /// <returns>Editor of properties of visible object</returns>
    object CreateLabel(IPosition position, IVisible visible);

OpenGL and WPF implementations of this interface are developed in the present day. The following class diagram represents these implementations:

Image 2

Every implementation class contains Singleton field as it is presented below:

C#
/// <summary>
/// WPF implementation of 3D Graphics
/// </summary>
public class WpfFactory : PositionObjectFactory
{
    #region Fields

     /// <summary>
    /// Singleton
    /// </summary>
    public static readonly WpfFactory Singleton =
        new WpfFactory();

    #endregion

    #region Ctor

    /// <summary>
    /// Private default constructor
    /// </summary>
    private WpfFactory()
    {
    }

    #endregion

Both these implementations are contained in different dynamic link libraries.

N Technology Implementation class Dynamic link library file
1 OpenGL OpenGLFactory InterfaceOpenGL.dll
2 WPF WpfFactory WpfInterface.UI.dll

The following code snippet represents selection of 3D Graphics interface:

C#
/// <summary>
/// Global factory
/// </summary>
public static IPositionObjectFactory BaseFactory
{
    get
    {
        if (baseFactory == null)
        {
             baseFactory =
                 AssemblyService.StaticExtensionAssemblyService.
                         GetFirstInterfaceObjectFromBaseDirectory<IPositionObjectFactory>();
        }
        return baseFactory;
    }
}

So if we would like use OpenGL technology, then InterfaceOpenGL.dll file should be copied to base directory, etc. More information about applications of 3D Graphics is contained in this article devoted to virtual reality.

3.2 Scientific Data

3.2.1 Scientific Data Processing

Database can be a good warehouse of scientific data. Otherwise, user of software should have a good interface for data access. Let us consider sample, both data access and data processing. In this sample, we have the following two nonlinear functions f1, f2:

Image 3

Parameters a, b, c, d, g of these functions are not known. Values of functions and variables x, y, z are stored in database which have the following scheme:

Image 4

Parameters with "id" prefix are id of values of variables. Meaning of database parameters is clear. Following SQL Query provides retrieving of values of variables and functions.

C#
SELECT x.x, y.y, z.z, f1.f1, f2.f2 FROM f1, f2, x, y, z _
WHERE x.Id = f1.Idx AND y.Id = f1.Idy AND z.Id = f1.Idz AND f1.Idx = f2.Idx _
AND f1.Idy = f2.Idy AND f1.Idz = f2.Idz

Now let us consider the full solution of this task. The following picture contains components of this task:

Image 5.

The Data component performs Database query. Properties of Data are presented below:

Image 6

Properties of this component are clear. The SQL Server driver is used. Other properties are connection string and SQL Query. The Iterator component can be regarded as cursor. The Formula component contains definition of f1, f2. Properties of Formula are presented below:

Image 7

Parameters a, b, c, d, g are constants of formulae. Variables x, y, z correspond to retrieved from database real numbers. The Processor component performs definition of above constants. Properties of Processor are presented below:

Image 8

Left panel of the above picture means that we would like to define constants a, b, c, d, g of Formula component. Right panel means that we would like approximate retrieved from database f1, f2 by Formula_1 and Formula_2 of Formula. Left and right parts of the below picture contain prior and posterior values.

Image 9

3.2.2 Database Drivers

In the above sample, SQL Server has been used. It is clear that scientists can use Oracle for the same purpose. Software should support the following options:

Drivers should be contained in different assemblies. Low coupled software should separate Oracle driver from SQL Server one since good software should support the following options:

  • Support of Oracle
  • Support of SQL Server
  • Support of both Oracle and SQL Server
  • Do not support any database

So software should contain abstract database layer. Following code represent this abstract layer:

C#
/// <summary>
/// Factory for creating data set metadata from connection
/// </summary>
public interface IDataSetFactory
{
    /// <summary>
    /// Name of factory
    /// </summary>
    string FactoryName
    {
        get;
    }

    /// <summary>
    /// Creates connection
    /// </summary>
    DbConnection Connection
    {
        get;
    }

    /// <summary>
    /// Command
    /// </summary>
    DbCommand Command
    {
        get;
    }

    /// <summary>
    /// Gets metadata data set from connection
    /// </summary>
    /// <param name="connection">The connection</param>
    /// <returns>The metadata data set</returns>
    DataSet GetData(DbConnection connection);

    /// <summary>
    /// Gets metadata data set from connection string
    /// </summary>
    /// <param name="connectionString">The connection</param>
    /// <returns>The metadata data set</returns>
    DataSet GetData(string connectionString);

    /// <summary>
    /// Data adapter
    /// </summary>
    IDbDataAdapter Adapter
    {
        get;
    }

    /// <summary>
    /// Creates type from metadata row
    /// </summary>
    /// <param name="row">The metadata row</param>
    /// <returns>The type</returns>
    Type GetTypeFromRow(DataRow row);

    /// <summary>
    /// Table name in metadata
    /// </summary>
    string TableName
    {
        get;
    }

    /// <summary>
    /// Column name in metadata
    /// </summary>
    string ColumnName
    {
        get;
    }

    /// <summary>
    /// Is nullable in metadata
    /// </summary>
    string IsNullable
    {
        get;
    }

    /// <summary>
    /// Gets string representation of type
    /// </summary>
    /// <param name="type">The type</param>
    /// <returns>The string representation</returns>
    string GetStringFromType(Type type);

    /// <summary>
    /// Generates statement from desktop
    /// </summary>
    /// <param name="desktop">The desktop</param>
    /// <returns>The statement</returns>
    string GenerateStatement(IDataSetDesktop desktop);

    /// <summary>
    /// Gets object type
    /// </summary>
    /// <param name="column">Column</param>
    /// <returns>The type</returns>
    object GetObjectType(DataColumn column);

    /// <summary>
    /// Generates script
    /// </summary>
    /// <param name="column">Column</param>
    /// <returns>Script</returns>
    string GenerateScript(IColumn column);

    /// <summary>
    /// Generates create script
    /// </summary>
    /// <param name="table">Table</param>
    /// <returns>Script lines</returns>
    List<string> GenerateScript(ITable table);

    /// <summary>
    /// Generates creation script from metadata
    /// </summary>
    /// <param name="metaData">Meatadata data set</param>
    /// <returns>Creation script</returns>
    List<string> GenerateScript(DataSet metaData);
}

List of database drivers can be extended. Now ODBC, SQL Server and Oracle drivers are already developed. The following picture represents class diagram of these drivers.

Image 10

The following code represents usage of these drivers:

C#
/// <summary>
/// Initialization of database drivers
/// </summary>
/// <param name="path">Path of drivers</param>
void Initialize(string path)
{
    // Gets all database drivers from this directory
    IEnumerable<IDataSetFactory> en = path.GetInterfaces<IDataSetFactory>();
    List<string> l = new List<string>();
    foreach (IDataSetFactory f in en)
    {
        factories[f.FactoryName] = f; // Dictinary of drivers
    }
    List<string> ln = new List<string>(factories.Keys);
    ln.Sort();
    names = ln.ToArray(); // Ordered names of drivers
}

If Oracle driver is used instead of the SQL Server one, then properties of Data would be changed in the following way:

Image 11

In the above picture, driver and connection string are changed. In some cases, change of query is required.

3.3 Other Samples

List of samples can be extended. However, the general idea is already clear. Other samples shall be described in future specific articles.

Points of Interest

I do not know what is more useful, my code or inspiration of you for good work even if you are threatened with a madhouse.

Useful Links

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)