Click here to Skip to main content
15,896,154 members
Articles / Web Development / ASP.NET

Template-Based Code Generation with SmartCode

Rate me:
Please Sign up or sign in to vote.
4.82/5 (35 votes)
25 Dec 20067 min read 101.1K   3.5K   121  
SmartCode is a template based code generator.This tutorial describes the process of building a templates to SmartCode
/*
 * Copyright � 2005-2006 Danilo Mendez <danilo.mendez@kontac.net>
 * Adolfo Socorro <ajs@esolutionspr.com>
 * www.kontac.net 
 * All rights reserved.
 * Released under both BSD license and Lesser GPL library license.
 * Whenever there is any discrepancy between the two licenses,
 * the BSD license will take precedence.
 */


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SmartCode.Studio.Database;
using SmartCode.Studio.Database.MSSQL;
using SmartCode.Studio.Controls;
using SmartCode.Model;
using System.Collections;
using System.IO;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using SmartCode.Studio.AssemblyCache;
using SmartCode.Studio.Templates;
using SmartCode.Studio.Utils;
using SmartCode.Studio.Engine;
using System.Diagnostics;

namespace SmartCode.Studio
{
    public partial class SmartStudio : Form
    {
        private Driver driver;
        private Project currentProject;

        private static SmartCode.Studio.SmartStudio mainForm;

        private ExplorerTreeNode currentNode;

        public SmartStudio()
        {
            InitializeComponent();
        }


        public Project CurrentProject
        {
            get { return currentProject; }
        }

        internal static SmartCode.Studio.SmartStudio MainForm
        {
            get
            {
                if (SmartCode.Studio.SmartStudio.mainForm == null)
                {
                    SmartCode.Studio.SmartStudio.mainForm = new SmartCode.Studio.SmartStudio();
                }
                return SmartCode.Studio.SmartStudio.mainForm;
            }
        }

        /// <summary>
        /// Create a new Project
        /// </summary>
        private void CreateNewProject()
        {
            DriverDlg dlg = new DriverDlg();
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                this.driver = dlg.SelectedDriver;
                EntitiesDlg entitiesDlg = new EntitiesDlg(this.driver);
                if (entitiesDlg.ShowDialog(this) == DialogResult.OK)
                {
                    string[] selectedTables = entitiesDlg.GetSelectedTables();
                    string[] selectedViews = entitiesDlg.GetSelectedViews();
                    if (this.BuildDomain(selectedTables, selectedViews))
                    {
                        this.currentProject.Domain.Name = dlg.DomainName;
                        this.currentProject.Domain.Code = this.currentProject.Domain.Name.Replace("-", "").Replace("_", "").Replace(" ",String.Empty);
                        DisplayProperties(null);
                        Common.BuildTreeFromDomain(this.uiTvExplorer, this.currentProject.Domain, true);
                        SetControls(true);
                        
                    }
                }
                entitiesDlg.Dispose();

            }
            dlg.Dispose();
        }

        /// <summary>
        /// Build Domain from the tables and views
        /// </summary>
        /// <param name="tables"></param>
        /// <param name="views"></param>
        /// <returns></returns>
        private bool BuildDomain(string[] tables, string[] views)
        {
            BuildDomainDlg dlg = new BuildDomainDlg(this.driver,  tables, views);
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                Domain domain = dlg.GetDomain();
                this.currentProject = new Project(domain);
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="enabled"></param>
        private void SetControls(bool enabled)
        {
            this.saveAsToolStripMenuItem.Enabled = enabled;
            this.saveToolStripMenuItem.Enabled = enabled;
            this.loadLibraryToolStripMenuItem.Enabled = enabled;
            this.viewLibrariesToolStripMenuItem.Enabled = enabled;
            this.generateToolStripMenuItem.Enabled = enabled;
            this.uiBtnSave.Enabled = enabled;
            this.uiBtnSaveAs.Enabled = enabled;
            this.uiBtnAddLibraries.Enabled = enabled;
            this.uiBtnLibrarySetting.Enabled = enabled;
            this.uiBtnGenerate.Enabled = enabled;
            this.refreshProjectToolStripMenuItem.Enabled = enabled;
            this.addControlToolStripMenuItem.Enabled = enabled;
        }

        /// <summary>
        /// Return all tables defined into domain
        /// </summary>
        /// <returns></returns>
        internal ArrayList GetAllTables()
        {
            return this.currentProject.Domain.ConnectionInfo.GetAllTables();
        }

        /// <summary>
        /// Return all views defined into domain
        /// </summary>
        /// <returns></returns>
        internal ArrayList GetAllViews()
        {
            return this.currentProject.Domain.ConnectionInfo.GetAllViews();
        }

        private void SetSelectedPropertyObject(object p)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        private void uiTvExplorer_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.uiTxtCaption.Text = string.Empty;
            this.currentNode = ((TreeView)sender).SelectedNode as ExplorerTreeNode;
            this.CleanPanel();
            if (currentNode == null)
            {
                return;
            }
             
            //this.SetContextMenu(selectedNode);
            this.DisplayProperties(this.currentNode);
            this.SetMainPanel(this.currentNode);
            SetExplorerToolBar(this.currentNode);
        }

        private void SetExplorerToolBar(TreeNode tn)
        {
            bool enabled = false;

            enabled |= tn.Tag is Column;
            enabled |= tn.Tag is Reference;
            enabled |= tn.Tag is ReferenceJoin;
            enabled |= tn.Tag is Table;

            uiTBDeleteObject.Enabled = enabled;
        }

        /// <summary>
        /// Set the main panel
        /// </summary>
        /// <param name="node"></param>
        internal void DisplayProperties(ExplorerTreeNode node)
        {
            if (node == null)
            {
                this.SetSelectedPropertyObject(null);
                this.uiTxtCaption.Text = string.Empty;
            }
            else
            {
                this.uiPGNamedObject.SelectedObject = node.PropertyWrapper;
                this.uiPGNamedObject.Refresh();
                this.uiTxtCaption.Text = node.Text;
            }

        }


        private void SetMainPanel(ExplorerTreeNode node)
        {
            if (node is ExplorerTreeNode)
            {
                this.uiPGNamedObject.Dock = DockStyle.Fill;
                this.uiPGNamedObject.Visible = true;
            }
        }

        private void CleanPanel()
        {
            foreach (Control ctl in this.uiPnlMain.Controls)
            {
                ctl.Visible = false;
            }
        }

        private void SmartStudio_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            this.CleanPanel();
            Splash splash = new Splash();
            splash.ShowDialog(this);
            splash.Dispose();
        }

        private void OpenProject()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "Open Smart Code Project";
            dialog.Filter = "All files(*.scp)|*.scp";
            dialog.FilterIndex = 2;
            dialog.RestoreDirectory = true;
            try
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    this.LoadFilename(dialog.FileName);
                    //TODO: Ask if Save
                    RefreshExplorer();
                    
                }
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                dialog.Dispose();
            }

        }

        private void LoadFilename(string fileName)
        {
            FileStream stream = null;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                stream = File.Open(fileName, FileMode.Open);
                BinaryFormatter formatter = new BinaryFormatter();
                this.currentProject = (Project)formatter.Deserialize(stream);
                this.currentProject.FileName = fileName;
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                this.Cursor = Cursors.Default;
            }

        }

        public void SaveProject(bool saveAs)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = null;
            string fileName = "";
            try
            {
                if (string.IsNullOrEmpty(this.currentProject.FileName) || saveAs)
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Title = "Save Project As...";
                    dialog.Filter = "All files(*.scp)|*.scp";
                    dialog.FilterIndex = 2;
                    dialog.RestoreDirectory = true;
                    if (dialog.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    fileName = dialog.FileName;
                }
                else
                {
                    fileName = this.currentProject.FileName;
                }
                stream = File.Open(fileName, FileMode.Create);
                this.currentProject.FileName = fileName;
                formatter.Serialize(stream, this.currentProject);
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                this.Cursor = Cursors.Default;
            }
        }

        internal void LoadLibrariesFromGAC()
        {
            GACDlg dlg = new GACDlg();
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                ArrayList selectedLibraries = dlg.GetSelectedLibraries();
                TemplatesLoader libraryLoader = new TemplatesLoader();

                foreach (LibraryInfo library in selectedLibraries)
                {
                    try
                    {
                        libraryLoader.LoadTemplates(library);
                        if (! this.currentProject.Libraries.Keys.Contains(library.AssemblyName))
                        {
                            this.currentProject.AddLibrary(library);
                        }
                        else
                        {
                            MessageBox.Show("The Library " + library.AssemblyName + " exists in the project, please Remove from View Libraries Dialog.");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }


        internal void GenerateCode()
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.ShowNewFolderButton = true;
            folderBrowserDialog.SelectedPath = Configuration.SelectedPath;
            folderBrowserDialog.Description = "Select the destination directory for code generation.";
            if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK)
            {
                Configuration.SelectedPath = folderBrowserDialog.SelectedPath;

                ICodeOutput codeOuptut = new FileOutput(folderBrowserDialog.SelectedPath);
                CodeGenerationDlg codeGenerationDlg = new CodeGenerationDlg(codeOuptut);
                codeOuptut.ShowOutput();
                codeGenerationDlg.ShowDialog(this);
                codeGenerationDlg.Dispose();

            }
        }

 
        private void NewProject_Click(object sender, EventArgs e)
        {
            CreateNewProject();
        }

        private void OpenProject_Click(object sender, EventArgs e)
        {
            OpenProject();
        }

        private void SaveProject_Click(object sender, EventArgs e)
        {
            SaveProject(false);
        }

        private void SaveAsProject_Click(object sender, EventArgs e)
        {
            SaveProject(true);
        }

        private void CloseProject_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void LoadLibrary_Click(object sender, EventArgs e)
        {
            LoadLibrariesFromGAC();
        }

        private void ViewLibraries_Click(object sender, EventArgs e)
        {
            LibrariesDlg dlg = new LibrariesDlg();
            dlg.ShowDialog(this);
        }

        private void Generate_Click(object sender, EventArgs e)
        {
            if (this.CurrentProject.Libraries.Count == 0)
            {
                string message = "There are not templates libraries loaded." + System.Environment.NewLine ;
                message += "All code generation is based on templates assigned to entities." + System.Environment.NewLine;
                message += "In the next windows please load templates libraries. They are localizated in the Global Assembly Cache.";
                MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadLibrariesFromGAC();
            }
            else
            {
                GenerationDlg dlg = new GenerationDlg();
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    this.GenerateCode();
                }
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutDlg dlg = new AboutDlg();
            dlg.ShowDialog(this);
        }

        private void helpToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.kontac.net/WebSite/smartcodeforum.aspx");
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("The method or operation is not implemented.");
        }


        private void OnDeleteObject_Click(object sender, EventArgs e)
        {
            if (this.currentNode != null)
            {
                uiTBDeleteObject.Enabled = false;

                Column column = this.currentNode.Tag as Column;
                if (column != null)
                {
                    Table table = this.currentNode.Parent.Tag as Table;
                    if (table.RemoveColumn(column))
                    {
                        return;
                    }
                }

                Reference reference = this.currentNode.Tag as Reference;
                if (reference != null)
                {
                    Table table = this.currentNode.Parent.Tag as Table;
                    if (table.RemoveOutReference(reference))
                    {
                        return;
                    }
                }
                ReferenceJoin join = this.currentNode.Tag as ReferenceJoin;
                if (join != null)
                {
                    Reference refe = this.currentNode.Parent.Tag as Reference;
                    if (refe.RemoveJoin(join))
                    {
                        return;
                    }
                }

                Table selectedTable = this.currentNode.Tag as Table;
                if (selectedTable != null)
                {
                    if (this.CurrentProject.Domain.RemoveTable(selectedTable))
                    {
                        return;
                    }
                }
            }
        }

        private void RefreshExplorer()
        {
            this.uiTvExplorer.Nodes.Clear();
            this.CleanPanel();
            DisplayProperties(null);
            Common.BuildTreeFromDomain(this.uiTvExplorer, this.currentProject.Domain, true);
            SetControls(true);
        }

        private void AddControl()
        {
            ControlsDlg dlg = new ControlsDlg();
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                TreeNode controlsNode = this.uiTvExplorer.Nodes[0].Nodes[2];
                ExplorerTreeNode controlNode = new ExplorerTreeNode(dlg.control.Name, 7, 7, dlg.control, controlsNode);
                controlsNode.Nodes.Add(controlNode);
            }
        }

        private void refreshProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Driver tempDriver = DriverFactory.GetDriver(this.currentProject.Domain.ConnectionInfo.Location);

            EntitiesDlg entitiesDlg = new EntitiesDlg(tempDriver);
            if (entitiesDlg.ShowDialog(this) == DialogResult.OK)
            {
                string[] selectedTables = entitiesDlg.GetSelectedTables();
                string[] selectedViews = entitiesDlg.GetSelectedViews();

                BuildDomainDlg dlg = new BuildDomainDlg(tempDriver, selectedTables, selectedViews);
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    RefreshProjectDlg refreshDlg = new RefreshProjectDlg(CurrentProject.Domain, dlg.GetDomain());
                    if (refreshDlg.ShowDialog(this) == DialogResult.OK )
                    {
                        RefreshExplorer();
                    }
                }
            }

            
        }

        private void addControlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.AddControl();
        }
 
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
Danilo is the creator of SmartRules, a Business Rules Engine. He is an industry consultant working primarily with companies interested in implementing dynamic rules programming concepts to add flexibility to their architectures on web, CE, and desktop platforms. He operates his own website, Kontac, where you will find more information.

To contact Danilo, email him at danilo.mendez@gmail.com.

Comments and Discussions