ArtinSoft's Blogs

Software Migration Experts
Welcome to ArtinSoft's Blogs Sign in | Join | Help
in Search

Mauricio Rojas Blog

August 2008 - Posts

  • Using C# or VB.NET collection in your VB6 Applications

    If you have some .NET code that you want to share with VB6, COM has always been a nice option. You just add couple of ComVisible tags and that's all.

    But...

    Collections can be a little tricky.

    This is a simple example of how to expose your Collections To VB6.

    Here I create an ArrayList descendant that you can use to expose your collections.
    Just create a new C# class library project and add the code below.
    Remember to check the Register for ComInterop setting.

     
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.InteropServices;
    
    namespace CollectionsInterop
    {
        
        [Guid("0490E147-F2D2-4909-A4B8-3533D2F264D0")]
        [ComVisible(true)]
        public interface IMyCollectionInterface 
        {
    
            int Add(object value);
            void Clear();
            bool Contains(object value);
            int IndexOf(object value);
            void Insert(int index, object value);
            void Remove(object value);
            void RemoveAt(int index);
    
            [DispId(-4)]
            System.Collections.IEnumerator GetEnumerator();
          
            [DispId(0)]
            [System.Runtime.CompilerServices.IndexerName("_Default")]
            object this[int index]
            {
                get;
            }
        }
    
        
        [ComVisible(true)]
        [ClassInterface(ClassInterfaceType.None)]
        [ComDefaultInterface(typeof(IMyCollectionInterface))]
        [ProgId("CollectionsInterop.VB6InteropArrayList")]
        public class VB6InteropArrayList : System.Collections.ArrayList, IMyCollectionInterface
        {
    
            #region IMyCollectionInterface Members
    
    
            // COM friendly strong typed GetEnumerator
    
            [DispId(-4)]
            public System.Collections.IEnumerator GetEnumerator()
            {
                return base.GetEnumerator();
            }
    
    
    
            #endregion
        }
    
    
    
        /// <summary>
        /// Simple object for example 
        /// </summary>
        [ComVisible(true)]
        [ClassInterface(ClassInterfaceType.AutoDual)]
        [ProgId("CollectionsInterop.MyObject")]
        public class MyObject
        {
            String value1 = "nulo";
    
            public String Value1
            {
                get { return value1; }
                set { value1 = value; }
            }
            String value2 = "nulo";
    
            public String Value2
            {
                get { return value2; }
                set { value2 = value; }
            }
        }
    
    
    }
    
     
    To test this code you can use this VB6 code. Remember to add a reference to this class library.
    Private Sub Form_Load()
        Dim simpleCollection As New CollectionsInterop.VB6InteropArrayList
        Dim value As New CollectionsInterop.MyObject
        value.Value1 = "Mi valor1"
        value.Value2 = "Autre valeur"
        simpleCollection.Add value
        
        For Each c In simpleCollection
          MsgBox value.Value1
        Next
    End Sub
  • Natural Languages and Programming Languages

    I am a firm believer in program understanding and in that our computer skills will allow us to develop programs that will understand programs and maybe in the future even write some of them :).

     I also belive that natural languages ans programming languages are two things with a lot in common.

    These are just some ideas about this subject. 

    "A language convertion translates one languate to another language, while a language-level upgrade moves an application from an older version of a language to a modern or more standardized version of that same language. In both cases, the goal is to improve portability and understanbility of an application and position that application for subsequent transformation", Legacy Systems, Transformation Strategies by  William M. Ulrich.

    An natural language convertion is exactly that. Translating one language to another language.

    Natural language processing and transformation have a lot in common with automated source code migration. There is a lot of grammar studies on both areas, and a lot of common algorithms.

    I keep quoting:

    "Comparing artificial language and natural language it is very helpful to our understanding of semantics of programming languages since programming languages are artificial. We can see much similarity between these two kinds of languages:

    Both of them must explain "given'" languages.
    The goal of research on semantics of programming languages is the same as that of natural language: explanation of the meanings of given language. This is unavoidable for natural language but undesirable for programming language. The latter one has often led to post-design analysis of the semantics of programming languages wherein the syntax and informal meaning of the language is treated as given( such as PL/I, Fortran and C ). Then the research on the semantics is to understand the semantics of the language in another way or to sort out anomalies, ommisions, or defects in the given semantics-which hasn't had much impact on the language design. We have another kind of programming languages that have formal definitions, such as Pascal, Ada, SML. The given semantics allow this kind of programming language to be more robust than the previous ones.

    Both of them separate "syntax'" and "semantics'".
    Despite these similarities, the difference between the studies of natural and artificial language is profound. First of all, natural language existed for thousands of years, nobody knows who designed the language; but artificial languages are synthesized by logicians and computer scientists to meet some specific design criteria. Thus, `` the most basic characteritic of the distinction is the fact that an artificial language can be fully circumscribed and studied in its entirety.''

    We already have developed a mature system for SYNTAX. In 1950's, linguist Chomsky first proposed formal language theory for English, thus came up with Formal Language Theory, Grammar, Regular Grammar, CFG etc. The ``first'' application of this theory was to define syntax for Algol and to build parser for it. The landmarks in the development of formal language theory are: Knuth's  parser, and YACC-which is a successful and ``final''application of formal language theory.
    "

    from Cornell university http://www.cs.cornell.edu/info/projects/nuprl/cs611/fall94notes/cn2/cn2.html
    Jing Huang


    I also will like to add a reference from an interesting work related to pattern recognition a technique used both in natural language processing (see for example http://prhlt.iti.es/) and reverse engineering.
    This work is from Francesca Arcelli and Claudia Raibulet from Italy and they are working with the NASA Automated Software EngineeringResearch Center
    http://smallwiki.unibe.ch/woor2006/woor2006paper3/?action=MimeView

     

  • Scripting your applications in .NET

    In VB6 it was very simple to add scripting capabilities to your application.
    Just by using the Microsoft Script Control Library
    You can still use this library in .NET just as Roy Osherove' Bloc show in
    http://weblogs.asp.net/rosherove/articles/dotnetscripting.aspx

    However there are some minor details that must be taken care of:

    * Objects must be exposed thru COM (Add the [ComVisible(true)] attribute to the class
    * Add the ComVisible(true) attribute to the AssemblyInfo file
    * Make these objects public
    * Recommended (put your calls to Eval or ExecuteStatement inside try-catch blocks).

    And here's an example:

    using System;
    using System.Windows.Forms;
     
    namespace ScriptingDotNetTest
    {
        [System.Runtime.InteropServices.ComVisible(true)]
        public partial class frmTestVBScript  : Form
        {
            public int MyBackColor
            {
                get { return System.Drawing.ColorTranslator.ToOle(this.BackColor); }
                set { this.BackColor = System.Drawing.ColorTranslator.FromOle(value); }
            }
     
            MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
            private void RunScript(Object eventSender, EventArgs eventArgs)
            {
                try
                {
                    sc.Language = "VbScript";
                    sc.Reset();
                    sc.AddObject("myform", this, true);
                    sc.ExecuteStatement("myform.MyBackColor = vbRed");
                }
                catch 
                {
                    MSScriptControl.IScriptControl iscriptControl = sc as MSScriptControl.IScriptControl;
                    lblError.Text = "ERROR" + iscriptControl.Error.Description + " | Line of error: " + iscriptControl.Error.Line + " | Code error: " + iscriptControl.Error.Text;
                }
            }
     
            [STAThread]
            static void Main()
            {
                Application.Run(new frmTestVBScript());
            }
        }
    }


    TIP: If you don find the reference in the COM tab, just browse to c:\windows\system32\msscript.ocx

     

  • Vb Migration (not for the weak of mind) Post 2

    When people decide to migrate their VB6 applications they eventually end up questioning where they should go. Is VB.NET or C# a good choice?

    I have my personal preference, but my emphasis is in developing the technology to take where YOU want to go.

    VB.NET is a VB dialect very similar to VB6. It supports several constructs and it makes the changes easier.
    C# has several differences from VB6, but it has it a growing language with lots of enthusiasts in its community.
    Obviously migrating VB6 to VB dialect is a task far more easier than migrating to a different language.
    However we are a research company with years of work in this area and challenges is just what we love.

    Let's use a methaphor here.

    My beautiful wife, was born in Moscow, Russia. Like her, I really enjoy reading a good book. Some of my favorite authors are
    russian authors like Dostoievsky, Tolstoi and Chejov. However I still do not speak russian. I have tried, and I will keep trying but
    I still don't know russian. I have read only translations of their books, and I really enjoy them.
    As a native speaker my wife always tells me, that it is not the same to read those books in another language besides russian.
    And they are phrases (specially in Chejov books that I might not completely understand) but I really got the author
    message and enjoyed it.
    Translating a book from russian to a more similar language like Ucranian is easier than translating it to English or Spanish.
    But I think everybody agrees that is a task than can be done.

    You can use terrible works case scenarios, but these scenarios must be analized.
    Let see (I took these example from the link in that Francesco put in my previous post http://blogs.artinsoft.net/mrojas/archive/2008/08/07/vb-migration-not-for-the-weak-of-mind.aspx)

    If you have code like this:

    Sub CopyFiles(ByVal throwIfError As Boolean)
        If Not throwIfError Then On Error Resume Next
        Dim fso As New FileSystemObject
        fso.CopyFile "sourcefile1", "destfile1"
        fso.CopyFile "sourcefile2", "destfile2"
        fso.CopyFile "sourcefile3", "destfile3"
        ' seven more CopyFile method calls …
    End Sub


    and you translate it to:

    void CopyFiles(bool throwIfError)
    {
        Scripting.FileSystemObject fso = new Scripting.FileSystemObjectClass();
        try
        {
            fso.CopyFile("sourcefile1", "destfile1", true);
        }
        catch
        {
            if (throwIfError)
            {
                throw;
            }
        }
        try
        {
            fso.CopyFile("sourcefile1", "destfile1", true);
        }
        catch
        {
            if (throwIfError)
            {
                throw;
            }
        }
        try
        {
            fso.CopyFile("sourcefile1", "destfile1", true);
        }
        catch
        {
            if (throwIfError)
            {
                throw;
            }
        }
        // seven more try-catch blocks
    }

    I think that the russian is really keep in this translation.

    First of all. When you do a translation, you should try to make it as native as possible. So why will you keep using a COM function when there is an
    equivalent in .NET. So why not use System.IO.File.CopyFile("sourcefile1", "destfile1", true); instead?

    Second of all. The On Error Resume Next, I agree is a not a natural statement in C#. I really think that using it could provide results that are less predictable.
    Why? Becuase after executing it, are you sure that all the CopyFile occurred successfully? I would prefer wrapping the whole code inside a try-catch instead of trying
    to provide an implementation that is not natural in C#, will Aspect Oriented programming provide a clean solution for this cases. Maybe?

    RPG and COBOL to Object Oriented Programming, PowerBuilder to C#, Hierarquical Databases to Relational Databases are just the kind of challenges we have faced in our research project.
    Not everything is easy, and we might not be able to automate all the tasks (commonly due to the cost of implementing the automation not becuase of feasability).

    But at the end Could you understand the whole novel?, even if you didn't understand the joke in the one of the paragraphs in the page?

    My years of reading make be belive that you can.


     

  • C# Console Applications and Ctrl-C

    Console applications are still very useful for me.
    I write like 125 console applications in the morning and like 4 or 5 in the afternoon.
    In one of these applications that was running a long process I just started wandering:
    what will happen with Lost? Will ABC ever finish this series?
    And If someone presses Ctrl-C will I be able to catch it?
    And indeed, the greate C# provides a very easi way to do it:

     static void Main(string[] args)
            {
                Console.CancelKeyPress += 
                delegate(object sender, ConsoleCancelEventArgs e)
                {
                    Artinsoft.VBUMKernel.Implementations.UpgradeCommand.StopAllUpgradeProcess(true);
                    Console.WriteLine("Process aborted by user!");
                };
                //Long running process
            }
  • VB Migration (not for the weak of mind)

    Motivation: 

    I hate to be disappointed. Specially if it is by a person you had respect for. And that's exactly what Francisco Balena from VB Migration Partner, has done. I have respected him for his books and all his VB6 experience. In terms of legacy VB6 code he is a monster. He is the man.

    But in terms of code migration...

    I'm not saying this because I work on code migration or maybe I'm biased a little by the fact that I work almost 10 years with a company that has done source code migration research on a big number of legacy languages such as COBOL, RPG, PL\1, Algol, Progress, PowerBuilder and also VB6.

    I can tell the difference between a "compiler" and a system that rewrites a expression to the closest equivalent in the target language. We are aware of limitations. We are aware of paradigm differences and functional equivalence, but we talk from experience. We talk about our results. And we have proven those things we talk about.

     Let's says you create a Cobol Library with a "MOVE" function, and a COBOLPicture Type and add minus, divide, and add operators. And I write something like:

    CobolPicture x = new CobolPicture("XXXX");

    x.move(10);

    x.add(10);

    We have things like that, and it works. It's feasible and maybe there are cases where that is a solution. But we are also proud of have researchers that have been able to detect pattern to rewrite something like that like:

    int x = 0;

    x = 10;

    x+=10;

    And saying, that something is not possible just because you can't or you dont like it, just seem uneducated to me.

     All of this has motivated me to start a series of chapters I for a small blog book I will call VB Migration (not for the weak of mind).

    For those of you, who really are tecnology savvy and are in the process of a VB Migration, this is YOUR book.

This Blog

Syndication

Powered by Community Server (Non-Commercial Edition), by Telligent Systems