Beispiel #1
0
        private static List <Dictionary <string, dynamic> > getNMRelations(DatabaseXML db, Table table)
        {
            List <Dictionary <string, dynamic> > res = new List <Dictionary <string, dynamic> >();

            foreach (Table tmp in db.Content)
            {
                if (tmp.Name != table.Name && tmp.Type == "n-m-relation")
                {
                    if (tmp.ForeignKeys.Count == 2)
                    {
                        Dictionary <string, dynamic> dic = new Dictionary <string, dynamic>();
                        ForeignKey fk1 = tmp.ForeignKeys[0];
                        ForeignKey fk2 = tmp.ForeignKeys[1];
                        if (fk1.ExternTableName == table.Name)
                        {
                            dic.Add("n_m_Relations", db.getTableByName(fk2.ExternTableName));
                            dic.Add("inter_n_m_Relations", tmp);
                            dic.Add("inter_n_m_Relation_columnName", fk1.Info[0].ColumnName);
                            dic.Add("inter_n_m_Relation_externColumnName", fk2.Info[0].ColumnName);
                            res.Add(dic);
                        }
                        else if (fk2.ExternTableName == table.Name)
                        {
                            dic.Add("n_m_Relations", db.getTableByName(fk1.ExternTableName));
                            dic.Add("inter_n_m_Relations", tmp);
                            dic.Add("inter_n_m_Relation_columnName", fk2.Info[0].ColumnName);
                            dic.Add("inter_n_m_Relation_externColumnName", fk1.Info[0].ColumnName);
                            res.Add(dic);
                        }
                    }
                }
            }
            return(res);
        }
Beispiel #2
0
        public static string getStructure(DatabaseXML db, Table table)
        {
            string modelAttributes = "";

            for (int i = 0; i < db.Content.Count; i++)
            {
                Table tmp = db.Content[i];
                modelAttributes += @"
        readonly " + FirstCharToUpper(tmp.Name) + "DataAccess " + FirstCharToUpper(tmp.Name) + "Instance = new " + FirstCharToUpper(tmp.Name) + "DataAccess();";
            }
            string res = @"using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Net;
using DataAccess;
using DataAccess.DataAccessObject;

namespace " + db.Name + @".Controllers.Ajax
{
    public class " + FirstCharToUpper(table.Name) + @"Controller : Controller
    {" + modelAttributes + @"
        
        /**/
    }
}
";

            return(res);
        }
Beispiel #3
0
        public string getTableColumns(string tableName, string databaseName)
        {
            UserDatabasesDAO dao       = new UserDatabasesDAO();
            string           matricule = ((User)Session["user"]).Matricule;
            UserDatabases    udb       = dao.findByMatricule(matricule);
            List <Dictionary <string, dynamic> > list = new List <Dictionary <string, dynamic> >();
            DatabaseXML db    = udb.getDatabaseByName(databaseName);
            Table       table = db.getTableByName(tableName);

            foreach (Column column in table.Columns)
            {
                Dictionary <string, dynamic> dic = new Dictionary <string, dynamic>();
                dic.Add("Name", column.Name);
                dic.Add("Type", TypeString.ToString(column.Type));
                dic.Add("Length", column.getLength());
                dic.Add("PK", table.PrimaryKey.IndexOf(column.Name));
                List <ForeignKey> listFK = new List <ForeignKey>();
                foreach (ForeignKey fk in table.ForeignKeys)
                {
                    foreach (ForeignKeyInside fki in fk.Info)
                    {
                        if (fki.ColumnName == column.Name)
                        {
                            listFK.Add(fk);
                        }
                    }
                }
                dic.Add("FK", listFK);
                list.Add(dic);
            }
            return(JsonConvert.SerializeObject(list));
        }
Beispiel #4
0
        public static string getControllerClass(Table table, DatabaseXML db)
        {
            string res  = getStructure(db, table);
            string res2 = getBasicFunctions(db, table);

            res = res.Replace("/**/", res2);
            return(res);
        }
Beispiel #5
0
        public ActionResult AjaxTemplate(string databaseName, string tableName, string matricule)
        {
            initUser();
            UserDatabasesDAO dao = new UserDatabasesDAO();
            UserDatabases    udb = dao.findByMatricule(matricule);
            DatabaseXML      db  = udb.getDatabaseByName(databaseName);

            ViewBag.db = db;
            return(View());
        }
Beispiel #6
0
        public void update(Column column, string previousName, string tableName, string databaseName)
        {
            UserDatabasesDAO dao       = new UserDatabasesDAO();
            string           matricule = ((User)Session["user"]).Matricule;
            UserDatabases    udb       = dao.findByMatricule(matricule);
            DatabaseXML      db        = udb.getDatabaseByName(databaseName);

            db.getTableByName(tableName).updateColumn(previousName, column, db);
            dao.update(udb);
        }
Beispiel #7
0
        public ActionResult addDatabase(DatabaseXML database)
        {
            UserDatabasesDAO dao       = new UserDatabasesDAO();
            string           matricule = ((User)Session["user"]).Matricule;
            UserDatabases    udb       = dao.findByMatricule(matricule);

            udb.Databases.Add(database);
            dao.update(udb);
            return(Json(""));
        }
Beispiel #8
0
        public string getTableForeignKeys(string tableName, string databaseName)
        {
            UserDatabasesDAO dao       = new UserDatabasesDAO();
            string           matricule = ((User)Session["user"]).Matricule;
            UserDatabases    udb       = dao.findByMatricule(matricule);
            List <Dictionary <string, dynamic> > list = new List <Dictionary <string, dynamic> >();
            DatabaseXML db    = udb.getDatabaseByName(databaseName);
            Table       table = db.getTableByName(tableName);

            return(JsonConvert.SerializeObject(table.ForeignKeys));
        }
Beispiel #9
0
        public ActionResult ViewDatasScript(string databaseName, string tableName, string matricule)
        {
            initUser();
            UserDatabasesDAO dao   = new UserDatabasesDAO();
            UserDatabases    udb   = dao.findByMatricule(matricule);
            DatabaseXML      db    = udb.getDatabaseByName(databaseName);
            Table            table = db.getTableByName(tableName);

            ViewBag.database = db;
            ViewBag.table    = table;
            return(View());
        }
Beispiel #10
0
        public static string getRemoveFunction(DatabaseXML db, Table table)
        {
            string tableName = table.Name;
            string res       = @"
        [HttpPost]
        public string Remove" + FirstCharToUpper(tableName) + @"(int Id_" + FirstCharToUpper(tableName) + @")
        {
            MessageModel msg = " + FirstCharToUpper(table.Name) + @"Instance.Remove" + FirstCharToUpper(tableName) + @"(Id_" + FirstCharToUpper(tableName) + @");
            return JsonConvert.SerializeObject(msg);
        }
";

            return(res);
        }
Beispiel #11
0
        public void resetDatabase(string dbName)
        {
            initUser();
            string           matricule = ((User)Session["user"]).Matricule;
            UserDatabasesDAO dao       = new UserDatabasesDAO();
            UserDatabases    udb       = dao.findByMatricule(matricule);
            DatabaseXML      db        = udb.getDatabaseByName(dbName);

            db = loadDBFromConnectionString(dbName, db.ConnectionString, "");
            for (int i = 0; i < udb.Databases.Count; i++)
            {
                if (udb.Databases[i].Name == dbName)
                {
                    udb.Databases.RemoveAt(i);
                    break;
                }
            }
            udb.Databases.Add(db);
            dao.update(udb);
        }
Beispiel #12
0
        public static string getBasicFunctions(DatabaseXML db, Table table)
        {
            var res = "";

            if (table.Type == "Normal")
            {
                res  = getCreateFunction(db, table);
                res += getRemoveFunction(db, table);
                res += getUpdateFunction(db, table);
                res += getFindByPrimaryKeyFunction(table);
                res += getFindAllFunction(table);
                res += getFindByForeignKey(table);
                //res += getScriptFunction(db, table);
            }
            else
            {
                res += getFindAllFunction(table);
            }
            return(res);
        }
Beispiel #13
0
        public ActionResult loadDatabase(string projectName, string host, string instance, string databaseName, string username, string password)
        {
            initUser();

            string matricule = ((User)Session["user"]).Matricule;

            UserDatabasesDAO dao = new UserDatabasesDAO();
            UserDatabases    udb = dao.findByMatricule(matricule);
            string           connectionString = "Data Source=" + host + "\\" + instance + ";Initial Catalog=" + databaseName + ";Persist Security Info=True;User ID=" + username + ";Password="******"")
            {
                connectionString = "Data Source=" + host + ";Initial Catalog=" + databaseName + ";Persist Security Info=True;User ID=" + username + ";Password="******"")
            {
                if (instance == null || instance == "")
                {
                    connectionString = "Data Source=" + host + ";initial catalog=" + databaseName + ";integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";
                }
                else
                {
                    connectionString = "Data Source=" + host + "\\" + instance + ";initial catalog=" + databaseName + ";integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";
                }
            }

            DatabaseXML db = loadDBFromConnectionString(projectName, connectionString, databaseName);

            for (int i = 0; i < udb.Databases.Count; i++)
            {
                if (udb.Databases[i].Name == databaseName)
                {
                    udb.Databases.RemoveAt(i);
                    break;
                }
            }
            udb.Databases.Add(db);
            dao.update(udb);
            return(RedirectToAction("index"));
        }
Beispiel #14
0
        public static string getAbstractDAOClass(DatabaseXML database)
        {
            string res = @"<?php
if(!defined('AbstractDAO')){
    define('AbstractDAO','AbstractDAO');
    abstract class AbstractDao{
        protected $db = NULL;
        
        public function __construct(){
            if($this->db == NULL) {
                try{
                    $this->db = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'USERNAME', 'PASSWORD');
                }catch (PDOException $e) {
                    echo 'Échec lors de la connexion : ' . $e->getMessage();
                }
            }
        }
    }
}
?>";

            return(res);
        }
Beispiel #15
0
        private void generateCode(string databaseName, string codeType, string path, string zipPath, string matricule)
        {
            UserDatabasesDAO dao = new UserDatabasesDAO();
            UserDatabases    udb = dao.findByMatricule(matricule);
            DatabaseXML      db  = udb.getDatabaseByName(databaseName);

            emptyUserTmp(path, zipPath);
            string abstractDao = "";

            if (codeType == "CS")
            {
                //abstractDao = CRUDGenerator.Templates.Classes.CS.AbstractDAOGenerator.getAbstractDAOClass(db);
                //System.IO.File.WriteAllText(path + "DAO"+Path.DirectorySeparatorChar+"AbstractDao.cs", abstractDao);
            }
            else if (codeType == "PHP")
            {
                abstractDao = CRUDGenerator.Templates.Classes.PHP.AbstractDAOGenerator.getAbstractDAOClass(db);
                System.IO.File.WriteAllText(path + "DAO" + Path.DirectorySeparatorChar + "AbstractDao.php", abstractDao);
            }
            foreach (Table table in db.Content)
            {
                //string entity = "";
                string daoString = "";
                if (codeType == "CS")
                {
                    if (table.Type == "Normal")
                    {
                        Directory.CreateDirectory(path + "Views" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + table.Name + "" + Path.DirectorySeparatorChar);
                        Directory.CreateDirectory(path + "Views" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + table.Name + "" + Path.DirectorySeparatorChar + "Scripts");
                        //Directory.CreateDirectory(path + "Scripts" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + table.Name + "" + Path.DirectorySeparatorChar);
                        //entity = CRUDGenerator.Templates.Classes.CS.EntityGenerator.getEntityClassString(table, db.Name);
                        daoString = CRUDGenerator.Templates.Classes.CS.DAOGenerator.getDAOClass(table, db.Name).Replace("&lt;", "<").Replace("&gt;", ">");;
                        //System.IO.File.WriteAllText(path + "DAO"+Path.DirectorySeparatorChar+"Entity"+Path.DirectorySeparatorChar + FirstCharToUpper(table.Name) + ".cs", entity);
                        string controller = CRUDGenerator.Templates.Classes.CS.ControllerGenerator.getControllerClass(table, db).Replace("&lt;", "<").Replace("&gt;", ">").Replace("é", "é");
                        System.IO.File.WriteAllText(path + "DataAccessObject" + Path.DirectorySeparatorChar + FirstCharToUpper(table.Name) + "DataAccess.cs", daoString);
                        System.IO.File.WriteAllText(path + "Controllers" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + FirstCharToUpper(table.Name) + "Controller.cs", controller);

                        /*string InsertForm = getHtml(db.Name, table.Name, "InsertForm", matricule).Replace("&lt;", "<").Replace("&gt;", ">").Replace("é", "é");
                         * string ModifyForm = getHtml(db.Name, table.Name, "ModifyForm", matricule).Replace("&lt;", "<").Replace("&gt;", ">").Replace("é", "é");
                         * string ViewDatas = getHtml(db.Name, table.Name, "ViewDatas", matricule).Replace("&lt;", "<").Replace("&gt;", ">").Replace("é", "é");
                         * string InsertFormScript = getHtml(db.Name, table.Name, "InsertFormScript", matricule).Replace("&lt;", "<").Replace("&gt;", ">").Replace("é", "é");
                         * string ModifyFormScript = getHtml(db.Name, table.Name, "ModifyFormScript", matricule).Replace("&lt;", "<").Replace("&gt;", ">").Replace("é", "é");
                         * string ViewDatasScript = getHtml(db.Name, table.Name, "ViewDatasScript", matricule).Replace("&lt;", "<").Replace("&gt;", ">").Replace("é", "é");
                         * System.IO.File.WriteAllText(path + "Views" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + table.Name + "" + Path.DirectorySeparatorChar + "create.cshtml", InsertForm);
                         * System.IO.File.WriteAllText(path + "Views" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + table.Name + "" + Path.DirectorySeparatorChar + "modify.cshtml", ModifyForm);
                         * System.IO.File.WriteAllText(path + "Views" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + table.Name + "" + Path.DirectorySeparatorChar + "list.cshtml", ViewDatas);
                         * System.IO.File.WriteAllText(path + "Views" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + table.Name + "" + Path.DirectorySeparatorChar + "Scripts" + Path.DirectorySeparatorChar + "createScript.cshtml", InsertFormScript);
                         * System.IO.File.WriteAllText(path + "Views" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + table.Name + "" + Path.DirectorySeparatorChar + "Scripts" + Path.DirectorySeparatorChar + "modifyScript.cshtml", ModifyFormScript);
                         * System.IO.File.WriteAllText(path + "Views" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + table.Name + "" + Path.DirectorySeparatorChar + "Scripts" + Path.DirectorySeparatorChar + "listScript.cshtml", ViewDatasScript);
                         */
                    }
                    else
                    {
                        daoString = CRUDGenerator.Templates.Classes.CS.DAOGenerator.getDAOClass(table, db.Name).Replace("&lt;", "<").Replace("&gt;", ">");;
                        System.IO.File.WriteAllText(path + "DataAccessObject" + Path.DirectorySeparatorChar + FirstCharToUpper(table.Name) + "DataAccess.cs", daoString);
                        string controller = CRUDGenerator.Templates.Classes.CS.ControllerGenerator.getControllerClass(table, db).Replace("&lt;", "<").Replace("&gt;", ">").Replace("é", "é");
                        System.IO.File.WriteAllText(path + "Controllers" + Path.DirectorySeparatorChar + "Ajax" + Path.DirectorySeparatorChar + FirstCharToUpper(table.Name) + "Controller.cs", controller);
                    }
                }
                else if (codeType == "PHP")
                {
                    //entity = CRUDGenerator.Templates.Classes.PHP.EntityGenerator.getEntityClassString(table, db.Name);
                    daoString = CRUDGenerator.Templates.Classes.PHP.DAOGenerator.getDAOClass(table, db.Name);
                    //System.IO.File.WriteAllText(path + "DAO"+Path.DirectorySeparatorChar+"Entity"+Path.DirectorySeparatorChar + FirstCharToUpper(table.Name) + ".php", entity);
                    System.IO.File.WriteAllText(path + "DAO" + Path.DirectorySeparatorChar + FirstCharToUpper(table.Name) + "Dao.php", daoString);
                }
            }

            if (codeType == "CS")
            {
                System.IO.File.WriteAllText(path + "addToBundleConfig.txt", @"
            var ajaxCssBundle = new Bundle(""~/bundles/AjaxCss"", new CssMinify());
            ajaxCssBundle.Include(
                ""~/Content/lib/bootstrap.css"",
                ""~/Content/lib/font-awesome.css"",
                ""~/Content/lib/jquery.dataTables.css"",
                ""~/Content/lib/fixedHeader.dataTables.css"",
                ""~/Content/lib/jquery-ui-smoothness.css"",
                ""~/Content/lib/jquery-ui-smoothness.theme.css"",
                ""~/Content/lib/jquery-ui-timepicker-addon.css"",
                ""~/Content/lib/chosen.css"",
                ""~/Content/lib/sweetalert2.css"",
                ""~/Content/app/Site.css""
                );
            var ajaxJsBundle = new Bundle(""~/bundles/AjaxJs"", new JsMinify());
            ajaxJsBundle.Include(
                ""~/Scripts/lib/jquery-2.2.4.js"",
                ""~/Scripts/lib/bootstrap.js"",
                ""~/Scripts/lib/jquery.dataTables.js"",
                ""~/Scripts/lib/jquery-ui.js"",
                ""~/Scripts/lib/datepicker-fr.js"",
                ""~/Scripts/lib/jquery-ui-timepicker-addon.js"",
                ""~/Scripts/lib/chosen.jquery.js"",
                ""~/Scripts/lib/chosen.proto.js"",
                ""~/Scripts/lib/sweetalert2.js"",
                ""~/Scripts/lib/date.format.js"",
                ""~/Scripts/app/globalUtils.js""
                ); 
            bundles.Add(ajaxCssBundle);
            bundles.Add(ajaxJsBundle);");
                string AjaxTemplate = getHtml(db.Name, "truc", "AjaxTemplate", matricule);
                System.IO.File.WriteAllText(path + "Views" + Path.DirectorySeparatorChar + "Shared" + Path.DirectorySeparatorChar + "AjaxTemplate.cshtml", AjaxTemplate);
            }

            string SourcePath      = System.AppDomain.CurrentDomain.BaseDirectory + "tmp" + Path.DirectorySeparatorChar + "addToArchive";
            string DestinationPath = path + "";

            //Now Create all of the directories
            foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
                                                                SearchOption.AllDirectories))
            {
                Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
            }

            //Copy all the files & Replaces any files with the same name
            foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
                                                          SearchOption.AllDirectories))
            {
                System.IO.File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
            }

            /*SourcePath = System.AppDomain.CurrentDomain.BaseDirectory + "tmp"+Path.DirectorySeparatorChar+"Fonts";
             * DestinationPath = path + "Fonts";
             *
             * //Now Create all of the directories
             * foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
             *  SearchOption.AllDirectories))
             *  Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
             *
             * //Copy all the files & Replaces any files with the same name
             * foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
             *  SearchOption.AllDirectories))
             *  System.IO.File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
             *
             * SourcePath = System.AppDomain.CurrentDomain.BaseDirectory + "tmp"+Path.DirectorySeparatorChar+"Images";
             * DestinationPath = path + "Images";
             *
             * //Now Create all of the directories
             * foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
             *  SearchOption.AllDirectories))
             *  Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
             *
             * //Copy all the files & Replaces any files with the same name
             * foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
             *  SearchOption.AllDirectories))
             *  System.IO.File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
             */
        }
Beispiel #16
0
        public static string getAbstractDAOClass(DatabaseXML database)
        {
            string res = @"using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.Entity;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using " + FirstCharToUpper(database.Name) + @".Models;

namespace " + FirstCharToUpper(database.Name) + @".Dao
{
    public class AbstractDao
    {
        public static " + FirstCharToUpper(database.Name) + @"Entities db = new " + FirstCharToUpper(database.Name) + @"Entities();
        public static object dbLock = new object();
        public static string ConnectionString;
        public AbstractDao()
        {
            //this.ConnectionString = ConfigurationManager.ConnectionStrings[""" + database.Name + @"""].ConnectionString;
        }

        public static void init()
        {
            if(AbstractDao.ConnectionString == null || AbstractDao.ConnectionString == """")
            {
                var tmp = ConfigurationManager.ConnectionStrings;
                foreach (ConnectionStringSettings connectionString in tmp)
                {
                    if (connectionString.ConnectionString.Contains(""connection string"")) 
                    {
                        AbstractDao.ConnectionString = connectionString.ConnectionString;
                        AbstractDao.ConnectionString = AbstractDao.ConnectionString.Substring(AbstractDao.ConnectionString.IndexOf('""') + 1, AbstractDao.ConnectionString.LastIndexOf('""') - AbstractDao.ConnectionString.IndexOf('""') - 1);
                    }
                }
            }
        }

        public static List<Dictionary<string, string>> query(string query, Dictionary<string, string> dic = null)
        {
            init();
            SqlConnection connection = new SqlConnection(AbstractDao.ConnectionString);
            connection.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = connection;
            cmd.CommandText = query;
            cmd.Prepare();
            if (dic != null)
            {
                foreach (KeyValuePair<string, string> entry in dic)
                {
                    double d;
                    if (Double.TryParse(entry.Value, out d))
                        cmd.Parameters.AddWithValue(entry.Key, d);
                    else
                        cmd.Parameters.AddWithValue(entry.Key, entry.Value);
                }
            }
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                list.Add(readerToDic(reader));
            }
            return list;
        }

        public static void exec(string query, Dictionary<string, string> dic = null)
        {
            init();
            SqlConnection connection = new SqlConnection(AbstractDao.ConnectionString);
            connection.Open();
            SqlTransaction transaction = connection.BeginTransaction(""SampleTransaction"");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = connection;
            cmd.Transaction = transaction;
            try
            {
                cmd.CommandText = query;
                if (dic != null)
                {
                    cmd.Prepare();
                    foreach (KeyValuePair<string, string> entry in dic)
                    {
                        double d;
                        if (Double.TryParse(entry.Value, out d))
                            cmd.Parameters.AddWithValue(entry.Key, d);
                        else
                            cmd.Parameters.AddWithValue(entry.Key, entry.Value);
                    }
                }
                cmd.ExecuteNonQuery();
                transaction.Commit();
            }
            catch (Exception e1)
            {
                try
                {
                    transaction.Rollback();
                }
                catch (Exception e2)
                {
                    throw;
                }
            }
        }

        
        public static Dictionary<string, string> readerToDic(SqlDataReader reader)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            CultureInfo culture = new CultureInfo(""fr-FR"");
            int count = reader.FieldCount;
            for (int i = 0; i < count; i++)
            {
                string key = reader.GetName(i);
                string value = """";
                bool isNull = reader.IsDBNull(i);
                if (isNull == true)
                {
                    value = null;
                }
                else
                {
                    string type = reader.GetDataTypeName(i);
                    switch (type)
                    {
                        case ""datetime"":
                            value = reader.GetDateTime(i).ToString(culture);
                            break;
                        case ""varchar"":
                            value = reader.GetString(i);
                            break;
                        case ""int"":
                            value = reader.GetInt32(i).ToString();
                            break;
                        case ""smallint"":
                            value = reader.GetInt16(i).ToString();
                            break;
                        case ""bigint"":
                            value = reader.GetInt64(i).ToString();
                            break;
                        case ""decimal"":
                            value = reader.GetDecimal(i).ToString();
                            break;
                        case ""text"":
                            value = reader.GetString(i).ToString();
                            break;
                        case ""float"":
                            value = reader.GetDouble(i).ToString();
                            break;
                        case ""date"":
                            value = reader.GetDateTime(i).ToString(culture);
                            break;
                        case ""bit"":
                            value = reader.GetBoolean(i).ToString();
                            break;
                        default:
                            break;
                    }
                    if (value == """")
                    {
                        try
                        {
                            value = reader.GetString(i);
                        }
                        catch (Exception)
                        {
                            try
                            {
                                value = reader.GetInt32(i).ToString();
                            }
                            catch (Exception)
                            {
                                try
                                {
                                    value = reader.GetDouble(i).ToString();
                                }
                                catch (Exception)
                                {
                                    try
                                    {
                                        value = reader.GetByte(i).ToString();
                                    }
                                    catch (Exception)
                                    {
                                        try
                                        {
                                            value = reader.GetDateTime(i).ToString(culture);
                                        }
                                        catch (Exception)
                                        {
                                            try
                                            {
                                                value = reader.GetDecimal(i).ToString();
                                            }
                                            catch (Exception)
                                            {

                                                throw;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                dic[key] = value;
            }
            return dic;
        }
    }
}

";

            return(res);
        }
Beispiel #17
0
        private void generateScript(string databaseName, string scriptType, string scriptPath, string matricule)
        {
            UserDatabasesDAO dao = new UserDatabasesDAO();
            UserDatabases    udb = dao.findByMatricule(matricule);
            DatabaseXML      db  = udb.getDatabaseByName(databaseName);


            List <int>   list   = new List <int>();
            List <Table> tables = db.Content;

            /*for (int i = 0; i < tables.Count; i++)
             * {
             *  for (int j = 0; j < tables.Count; j++)
             *  {
             *      if(j == 2 || j == 8 || j == 9 || j == 10 || j == 16)
             *      {
             *
             *      }
             *      if (!list.Contains(j))
             *      {
             *          bool isOk = true;
             *          if (tables[j].ForeignKeys.Count == 0)
             *              isOk = true;
             *          foreach (ForeignKey fk in tables[j].ForeignKeys)
             *          {
             *              if(fk.ExternTableName != tables[j].Name)
             *              {
             *                  bool tmp = false;
             *                  for (int k = 0; k < list.Count && tmp == false; k++)
             *                  {
             *                      if (tables[list[k]].Name == fk.ExternTableName)
             *                      {
             *                          tmp = true;
             *                      }
             *                  }
             *                  if (tmp == false)
             *                      isOk = false;
             *              }
             *          }
             *          if (isOk == true)
             *          {
             *              list.Add(j);
             *          }
             *      }
             *  }
             * }*/
            string script   = "";
            string fkString = "";

            for (int i = 0; i < tables.Count; i++)
            {
                string tableFK = "";
                if (i == 0)
                {
                    if (scriptType == "SQLServer")
                    {
                        script = CRUDGenerator.Templates.Scripts.SQLServer.TableScriptGenerator.getTableScript(tables[i], out tableFK);
                    }
                    else if (scriptType == "MySQL")
                    {
                        script = CRUDGenerator.Templates.Scripts.MySQL.TableScriptGenerator.getTableScript(tables[i]);
                    }
                }
                else
                {
                    if (scriptType == "SQLServer")
                    {
                        script += "\n\n\n" + CRUDGenerator.Templates.Scripts.SQLServer.TableScriptGenerator.getTableScript(tables[i], out tableFK);
                    }
                    else if (scriptType == "MySQL")
                    {
                        script += "\n\n\n" + CRUDGenerator.Templates.Scripts.MySQL.TableScriptGenerator.getTableScript(tables[i]);
                    }
                }
                fkString += "\n\n\n" + tableFK;
            }
            System.IO.File.WriteAllText(scriptPath, script + fkString);
        }
Beispiel #18
0
        public static string getScriptFunction(DatabaseXML db, Table table)
        {
            string generateAllTableScript = "";

            for (int i = 0; i < db.Content.Count; i++)
            {
                Table tmp = db.Content[i];
                generateAllTableScript += @"
            " + FirstCharToUpper(tmp.Name) + "Controller " + FirstCharToLower(tmp.Name) + "Controller = new " + FirstCharToUpper(tmp.Name) + @"Controller();
            " + FirstCharToLower(tmp.Name) + "Controller.generateTableScript2(Request.Url.Authority);";
            }
            return(@"
        [HttpGet]
        public void generateTableScript()
        {
            WebRequest createRequest = WebRequest.Create(""http://"" + Request.Url.Authority + ""/" + table.Name + @"/getCreateScript""); 
            createRequest.Method = ""Get"";
            createRequest.Credentials = CredentialCache.DefaultCredentials;
            var createResponse = (HttpWebResponse)createRequest.GetResponse();
            string createString = new System.IO.StreamReader(createResponse.GetResponseStream()).ReadToEnd();
            System.IO.File.WriteAllText(System.AppDomain.CurrentDomain.BaseDirectory+""/Scripts/Ajax/" + table.Name + @"/create.js"", createString);

            WebRequest modifyRequest = WebRequest.Create(""http://"" + Request.Url.Authority + ""/" + table.Name + @"/getModifyScript""); 
            modifyRequest.Method = ""Get"";
            modifyRequest.Credentials = CredentialCache.DefaultCredentials;
            var modifyResponse = (HttpWebResponse)modifyRequest.GetResponse();
            string modifyString = new System.IO.StreamReader(modifyResponse.GetResponseStream()).ReadToEnd();
            System.IO.File.WriteAllText(System.AppDomain.CurrentDomain.BaseDirectory+""/Scripts/Ajax/" + table.Name + @"/modify.js"", modifyString);

            WebRequest listRequest = WebRequest.Create(""http://"" + Request.Url.Authority + ""/" + table.Name + @"/getListScript""); 
            listRequest.Method = ""Get"";
            listRequest.Credentials = CredentialCache.DefaultCredentials;
            var listResponse = (HttpWebResponse)listRequest.GetResponse();
            string listString = new System.IO.StreamReader(listResponse.GetResponseStream()).ReadToEnd();
            System.IO.File.WriteAllText(System.AppDomain.CurrentDomain.BaseDirectory+""/Scripts/Ajax/" + table.Name + @"/list.js"", listString);
        }


        public void generateTableScript2(string authority)
        {
            WebRequest createRequest = WebRequest.Create(""http://"" + authority + ""/" + table.Name + @"/getCreateScript""); 
            createRequest.Method = ""Get"";
            createRequest.Credentials = CredentialCache.DefaultCredentials;
            var createResponse = (HttpWebResponse)createRequest.GetResponse();
            string createString = new System.IO.StreamReader(createResponse.GetResponseStream()).ReadToEnd();
            System.IO.File.WriteAllText(System.AppDomain.CurrentDomain.BaseDirectory+""/Scripts/Ajax/" + table.Name + @"/create.js"", createString);

            WebRequest modifyRequest = WebRequest.Create(""http://"" + authority + ""/" + table.Name + @"/getModifyScript""); 
            modifyRequest.Method = ""Get"";
            modifyRequest.Credentials = CredentialCache.DefaultCredentials;
            var modifyResponse = (HttpWebResponse)modifyRequest.GetResponse();
            string modifyString = new System.IO.StreamReader(modifyResponse.GetResponseStream()).ReadToEnd();
            System.IO.File.WriteAllText(System.AppDomain.CurrentDomain.BaseDirectory+""/Scripts/Ajax/" + table.Name + @"/modify.js"", modifyString);

            WebRequest listRequest = WebRequest.Create(""http://"" + authority + ""/" + table.Name + @"/getListScript""); 
            listRequest.Method = ""Get"";
            listRequest.Credentials = CredentialCache.DefaultCredentials;
            var listResponse = (HttpWebResponse)listRequest.GetResponse();
            string listString = new System.IO.StreamReader(listResponse.GetResponseStream()).ReadToEnd();
            System.IO.File.WriteAllText(System.AppDomain.CurrentDomain.BaseDirectory+""/Scripts/Ajax/" + table.Name + @"/list.js"", listString);
        }



        [HttpGet]
        public void generateAllTablesScript()
        {" + generateAllTableScript + @"
        }


        [HttpGet]
        public ActionResult getCreateScript()
        {
            return View(""~/Views/Ajax/" + FirstCharToUpper(table.Name) + @"/Scripts/createScript.cshtml"");
        }

        [HttpGet]
        public ActionResult getModifyScript()
        {
            return View(""~/Views/Ajax/" + FirstCharToUpper(table.Name) + @"/Scripts/modifyScript.cshtml"");
        }

        [HttpGet]
        public ActionResult getListScript()
        {
            return View(""~/Views/Ajax/" + FirstCharToUpper(table.Name) + @"/Scripts/listScript.cshtml"");
        }");
        }
Beispiel #19
0
        //
        // GET: /SQLManagement/Home/

        public ActionResult Index()
        {
            string        connectionString = ConfigurationManager.ConnectionStrings["mssqlConnection"].ConnectionString;
            SqlConnection connection       = new SqlConnection(connectionString);

            connection.Open();
            DataTable dt = connection.GetSchema("Columns");

            StringWriter stringWriter = new StringWriter();

            dt.WriteXml(stringWriter);
            string      xml     = stringWriter.ToString();
            XElement    element = XElement.Parse(xml);
            DatabaseXML db      = new DatabaseXML();

            foreach (XElement elem1 in element.Elements())
            {
                string isNull     = elem1.Element("IS_NULLABLE").Value;
                string tableName  = elem1.Element("TABLE_NAME").Value;
                string columnName = elem1.Element("COLUMN_NAME").Value;
                string Type       = elem1.Element("DATA_TYPE").Value;
                int    Length     = 0;
                if (Type == "int")
                {
                    Length = Int32.Parse(elem1.Element("NUMERIC_PRECISION").Value);
                }
                else if (Type == "varchar")
                {
                    Length = Int32.Parse(elem1.Element("CHARACTER_MAXIMUM_LENGTH").Value);
                }

                Table table = db.getTableByName(tableName);
                if (table == null)
                {
                    table      = new Table();
                    table.Name = tableName;
                    db.Content.Add(table);
                }
                Column column = new Column {
                    Name   = columnName,
                    Length = Length,
                    Type   = Database.TypeString.toType(Type)
                };
                if (isNull == "NO")
                {
                    column.isNull = 0;
                }
                else
                {
                    column.isNull = 1;
                }
                db.getTableByName(tableName).Columns.Add(column);
                if (columnName == "col7")
                {
                    Console.WriteLine("youpi");
                }
            }

            string primaryKeys = @"SELECT
    TableName = i1.TABLE_NAME,
    ColumnName = i2.COLUMN_NAME,
	Position = i2.ORDINAL_POSITION,
	PrimaryKeyName = i1.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
    ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE
    i1.CONSTRAINT_TYPE = 'PRIMARY KEY'";

            string foreignKeys = @"SELECT
    TableName = FK.TABLE_NAME,
    ColumnName = CU.COLUMN_NAME,
    ExternTableName = PK.TABLE_NAME,
    ExternColumnName = PT.COLUMN_NAME,
	ForeignKeyName = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME";

            string identities = @"select ColumnName = COLUMN_NAME, TableName = TABLE_NAME
    from INFORMATION_SCHEMA.COLUMNS
    where COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
    order by TableName";

            string indexes = @"SELECT 
     TableName = t.name,
     IndexName = ind.name,
     IndexId = ind.index_id,
     ColumnId = ic.index_column_id,
     ColumnName = col.name
FROM 
     sys.indexes ind 
INNER JOIN 
     sys.index_columns ic ON  ind.object_id = ic.object_id and ind.index_id = ic.index_id 
INNER JOIN 
     sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id 
INNER JOIN 
     sys.tables t ON ind.object_id = t.object_id 
ORDER BY 
     t.name, ind.name, ind.index_id, ic.index_column_id ";
            List <Dictionary <string, string> > primaryKeysList = query(primaryKeys);
            List <Dictionary <string, string> > foreignKeysList = query(foreignKeys);
            List <Dictionary <string, string> > identitiesList  = query(identities);
            List <Dictionary <string, string> > indexesList     = query(indexes);

            Dictionary <string, List <Dictionary <string, string> > > primaryKeyDic  = getDic(primaryKeysList);
            Dictionary <string, List <Dictionary <string, string> > > foreignKeysDic = getDic(foreignKeysList);
            Dictionary <string, List <Dictionary <string, string> > > identitiesDic  = getDic(identitiesList);
            Dictionary <string, List <Dictionary <string, string> > > indexesDic     = getDic(indexesList);

            foreach (KeyValuePair <string, List <Dictionary <string, string> > > kvp in primaryKeyDic)
            {
                string tableName = kvp.Key;
                for (int i = 0; i < kvp.Value.Count; i++)
                {
                    db.getTableByName(tableName).PrimaryKey.Add("youpi");
                }
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    int index = Int32.Parse(dic["Position"]) - 1;
                    db.getTableByName(tableName).PrimaryKey[index] = dic["ColumnName"];
                }
            }


            foreach (KeyValuePair <string, List <Dictionary <string, string> > > kvp in foreignKeysDic)
            {
                string tableName = kvp.Key;
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    string           fkName = dic["ForeignKeyName"];
                    ForeignKey       fk     = db.getTableByName(tableName).getForeignKeyByName(fkName);
                    ForeignKeyInside fki    = new ForeignKeyInside
                    {
                        ColumnName       = dic["ColumnName"],
                        ExternColumnName = dic["ExternColumnName"]
                    };
                    if (fk == null)
                    {
                        db.getTableByName(tableName).addForeignKey(new ForeignKey
                        {
                            ExternTableName = dic["ExternTableName"],
                            Name            = fkName,
                            Info            = new List <ForeignKeyInside>
                            {
                                fki
                            }
                        });
                    }
                    else
                    {
                        db.getTableByName(tableName).getForeignKeyByName(fkName).Info.Add(fki);
                    }
                }
            }


            foreach (KeyValuePair <string, List <Dictionary <string, string> > > kvp in indexesDic)
            {
                string tableName = kvp.Key;
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    string indexName  = dic["IndexName"];
                    Index  index      = db.getTableByName(tableName).getIndexByName(indexName);
                    string ColumnName = dic["ColumnName"];

                    if (index == null)
                    {
                        db.getTableByName(tableName).Indexes.Add(new Index
                        {
                            Name = indexName,
                            List = new List <string>
                            {
                                ColumnName
                            }
                        });
                    }
                    else
                    {
                        db.getTableByName(tableName).getIndexByName(indexName).List.Add(ColumnName);
                    }
                }
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    string indexName  = dic["IndexName"];
                    string ColumnName = dic["ColumnName"];
                    int    i          = Int32.Parse(dic["ColumnId"]) - 1;
                    db.getTableByName(tableName).getIndexByName(indexName).List[i] = indexName;
                }
            }

            foreach (KeyValuePair <string, List <Dictionary <string, string> > > kvp in indexesDic)
            {
                string tableName = kvp.Key;
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    string columnName = dic["ColumnName"];
                    db.getTableByName(tableName).getColumnByName(columnName).Type = Database.Type.Int_AI;
                }
            }


            /*
             * TABLE_NAME
             * COLUMN_NAME
             * IS_NULLABLE
             * DATA_TYPE
             *  (int) => NUMERIC_PRECISION,
             *  (varchar) => CHARACTER_MAXIMUM_LENGTH
             *  (float) ,
             *  (datetime) => DATETIME_PRECISION,
             *  (text),
             *  (decimal) => NUMERIC_PRECISION = *.NUMERIC_SCALE  (5.05 => {NUMERIC_PRECISION = 3, NUMERIC_SCALE = 2})
             *
             */
            return(View());
        }
Beispiel #20
0
        private DatabaseXML loadDBFromConnectionString(string projectName, string connectionString, string databaseName)
        {
            SQL.HelperSQL.ConnectionString = connectionString;
            SqlConnection connection = new SqlConnection(connectionString);

            connection.Open();
            DataTable dt = connection.GetSchema("Columns");

            StringWriter stringWriter = new StringWriter();

            dt.WriteXml(stringWriter);
            string      xml     = stringWriter.ToString();
            XElement    element = XElement.Parse(xml);
            DatabaseXML db      = new DatabaseXML
            {
                Name             = projectName,
                ConnectionString = connectionString
            };
            string getColumnScript = @"
            SELECT [type], TABLE_NAME, COLUMN_NAME, IS_NULLABLE, DATA_TYPE, NUMERIC_PRECISION, CHARACTER_MAXIMUM_LENGTH, NUMERIC_SCALE
            FROM sysobjects as so
	        right join INFORMATION_SCHEMA.COLUMNS on so.name = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME
            WHERE ([type] = 'U' OR [type] = 'V') AND category = 0";
            List <Dictionary <string, string> > columnList = SQL.HelperSQL.query(getColumnScript);

            foreach (Dictionary <string, string> columnDic in columnList)
            {
                string isNull                   = columnDic["IS_NULLABLE"];
                string tableName                = columnDic["TABLE_NAME"];
                string columnName               = columnDic["COLUMN_NAME"];
                string Type                     = columnDic["DATA_TYPE"];
                string NUMERIC_PRECISION        = columnDic["NUMERIC_PRECISION"];
                string CHARACTER_MAXIMUM_LENGTH = columnDic["CHARACTER_MAXIMUM_LENGTH"];
                string NUMERIC_SCALE            = columnDic["NUMERIC_SCALE"];
                string tableType                = columnDic["type"];
                if (tableType.Contains("U"))
                {
                    tableType = "Normal";
                }
                if (tableType.Contains("V"))
                {
                    tableType = "Vue";
                }
                int Length        = 0;
                int DecimalLength = 0;
                if (Type == "varchar" || Type == "nvarchar")
                {
                    Length = int.Parse(CHARACTER_MAXIMUM_LENGTH);
                }
                if (Type == "decimal")
                {
                    Length        = int.Parse(NUMERIC_PRECISION);
                    DecimalLength = int.Parse(NUMERIC_SCALE);
                }
                Table table = db.getTableByName(tableName);
                if (table == null)
                {
                    table      = new Table();
                    table.Name = tableName;
                    table.Type = tableType;
                    db.Content.Add(table);
                }
                Column column = new Column
                {
                    Name          = columnName,
                    Length        = Length,
                    Type          = Database.TypeString.toType(Type),
                    DecimalLength = DecimalLength
                };
                if (isNull == "NO")
                {
                    column.isNull = 0;
                }
                else
                {
                    column.isNull = 1;
                }
                db.getTableByName(tableName).Columns.Add(column);
            }
            string primaryKeys = @"SELECT
    TableName = i1.TABLE_NAME,
    ColumnName = i2.COLUMN_NAME,
	Position = i2.ORDINAL_POSITION,
	PrimaryKeyName = i1.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
    ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE
    i1.CONSTRAINT_TYPE = 'PRIMARY KEY'";

            string foreignKeys = @"SELECT
    TableName = FK.TABLE_NAME,
    ColumnName = CU.COLUMN_NAME,
    ExternTableName = PK.TABLE_NAME,
    ExternColumnName = PT.COLUMN_NAME,
	ForeignKeyName = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME";

            string identities = @"select ColumnName = COLUMN_NAME, TableName = TABLE_NAME
    from INFORMATION_SCHEMA.COLUMNS
    where COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
    order by TableName";

            string indexes = @"SELECT 
     TableName = t.name,
     IndexName = ind.name,
     IndexId = ind.index_id,
     ColumnId = ic.index_column_id,
     ColumnName = col.name
FROM 
     sys.indexes ind 
INNER JOIN 
     sys.index_columns ic ON  ind.object_id = ic.object_id and ind.index_id = ic.index_id 
INNER JOIN 
     sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id 
INNER JOIN 
     sys.tables t ON ind.object_id = t.object_id 
ORDER BY 
     t.name, ind.name, ind.index_id, ic.index_column_id ";

            string uniqueKeys = @"SELECT
    TableName = i1.TABLE_NAME,
    ColumnName = i2.COLUMN_NAME,
	Position = i2.ORDINAL_POSITION,
	UniqueKeyName = i1.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
    ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE
    i1.CONSTRAINT_TYPE = 'UNIQUE'";
            List <Dictionary <string, string> > primaryKeysList = SQL.HelperSQL.query(primaryKeys);
            List <Dictionary <string, string> > foreignKeysList = SQL.HelperSQL.query(foreignKeys);
            List <Dictionary <string, string> > identitiesList  = SQL.HelperSQL.query(identities);
            //List<Dictionary<string, string>> indexesList = SQL.HelperSQL.query(indexes);
            List <Dictionary <string, string> > uniqueKeysList = SQL.HelperSQL.query(uniqueKeys);

            //
            Dictionary <string, List <Dictionary <string, string> > > primaryKeyDic  = listToDic(primaryKeysList);
            Dictionary <string, List <Dictionary <string, string> > > foreignKeysDic = listToDic(foreignKeysList);
            Dictionary <string, List <Dictionary <string, string> > > identitiesDic  = listToDic(identitiesList);
            //Dictionary<string, List<Dictionary<string, string>>> indexesDic = listToDic(indexesList);
            Dictionary <string, List <Dictionary <string, string> > > UniqueKeysDic = listToDic(uniqueKeysList);

            foreach (KeyValuePair <string, List <Dictionary <string, string> > > kvp in primaryKeyDic)
            {
                string tableName = kvp.Key;
                // Rempli pour mettre les index dans les bonnes positions
                for (int i = 0; i < kvp.Value.Count; i++)
                {
                    db.getTableByName(tableName).PrimaryKey.Add("youpi");
                }
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    int index = Int32.Parse(dic["Position"]) - 1;
                    db.getTableByName(tableName).PrimaryKey[index] = dic["ColumnName"];
                }
            }


            foreach (KeyValuePair <string, List <Dictionary <string, string> > > kvp in foreignKeysDic)
            {
                string tableName = kvp.Key;
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    string           fkName = dic["ForeignKeyName"];
                    ForeignKey       fk     = db.getTableByName(tableName).getForeignKeyByName(fkName);
                    ForeignKeyInside fki    = new ForeignKeyInside
                    {
                        ColumnName       = dic["ColumnName"],
                        ExternColumnName = dic["ExternColumnName"]
                    };
                    if (fk == null)
                    {
                        db.getTableByName(tableName).addForeignKey(new ForeignKey
                        {
                            ExternTableName = dic["ExternTableName"],
                            Name            = fkName,
                            Info            = new List <ForeignKeyInside>
                            {
                                fki
                            }
                        });
                    }
                    else
                    {
                        db.getTableByName(tableName).getForeignKeyByName(fkName).Info.Add(fki);
                    }
                }
            }


            /*foreach (KeyValuePair<string, List<Dictionary<string, string>>> kvp in indexesDic)
             * {
             *  string tableName = kvp.Key;
             *  foreach (Dictionary<string, string> dic in kvp.Value)
             *  {
             *      string indexName = dic["IndexName"];
             *      Index index = db.getTableByName(tableName).getIndexByName(indexName);
             *      string ColumnName = dic["ColumnName"];
             *
             *      if (index == null)
             *      {
             *          db.getTableByName(tableName).Indexes.Add(new Index
             *          {
             *              Name = indexName,
             *              List = new List<string>
             *              {
             *                  ColumnName
             *              }
             *          });
             *      }
             *      else
             *      {
             *          db.getTableByName(tableName).getIndexByName(indexName).List.Add(ColumnName);
             *      }
             *  }
             *  foreach (Dictionary<string, string> dic in kvp.Value)
             *  {
             *      string indexName = dic["IndexName"];
             *      string ColumnName = dic["ColumnName"];
             *      int i = Int32.Parse(dic["ColumnId"]) - 1;
             *      db.getTableByName(tableName).getIndexByName(indexName).List[i] = ColumnName;
             *  }
             * }*/


            foreach (KeyValuePair <string, List <Dictionary <string, string> > > kvp in UniqueKeysDic)
            {
                string tableName = kvp.Key;
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    string    ukName     = dic["UniqueKeyName"];
                    UniqueKey uk         = db.getTableByName(tableName).getUniqueKeyByName(ukName);
                    string    ColumnName = dic["ColumnName"];

                    if (uk == null)
                    {
                        db.getTableByName(tableName).UniqueKeys.Add(new UniqueKey
                        {
                            Name = ukName,
                            List = new List <string>
                            {
                                ColumnName
                            }
                        });
                    }
                    else
                    {
                        db.getTableByName(tableName).getUniqueKeyByName(ukName).List.Add(ColumnName);
                    }
                }
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    string ukName     = dic["UniqueKeyName"];
                    string ColumnName = dic["ColumnName"];
                    int    i          = Int32.Parse(dic["Position"]) - 1;
                    db.getTableByName(tableName).getUniqueKeyByName(ukName).List[i] = ColumnName;
                }
            }

            foreach (KeyValuePair <string, List <Dictionary <string, string> > > kvp in identitiesDic)
            {
                string tableName = kvp.Key;
                foreach (Dictionary <string, string> dic in kvp.Value)
                {
                    string columnName = dic["ColumnName"];
                    db.getTableByName(tableName).getColumnByName(columnName).Type = Database.Type.Int_AI;
                }
            }
            return(db);
        }
Beispiel #21
0
        public static string getUpdateFunction(DatabaseXML db, Table table)
        {
            string tableName = table.Name;
            List <Dictionary <string, dynamic> > n_m_relations = getNMRelations(db, table);
            string n_m_add_parameters    = "";
            string n_m_add_init          = "";
            string n_m_remove_parameters = "";
            string n_m_remove_init       = "";
            string tableIdName           = table.PrimaryKey[0];

            for (int i = 0; i < n_m_relations.Count; i++)
            {
                //@(n_m_Relations[i].Name)_list
                string addParameterName              = ((Table)n_m_relations[i]["inter_n_m_Relations"]).Name + "_list";
                string removeParameterName           = ((Table)n_m_relations[i]["inter_n_m_Relations"]).Name + "_remove_list";
                Table  interTable                    = (Table)n_m_relations[i]["inter_n_m_Relations"];
                string inter_n_m_Relation_columnName = (string)n_m_relations[i]["inter_n_m_Relation_columnName"];
                n_m_add_parameters    += ", List<" + interTable.Name + "> " + addParameterName;
                n_m_remove_parameters += ", List<int> " + removeParameterName;
                n_m_add_init          += @"
                if(" + addParameterName + @" != null)
                {
                    for (int i = 0; i < " + addParameterName + @".Count; i++)
                    {
                        " + FirstCharToUpper(interTable.Name) + @"  " + FirstCharToLower(interTable.Name) + @" = " + addParameterName + @"[i];
                        " + FirstCharToLower(interTable.Name) + @"." + inter_n_m_Relation_columnName + @" = " + FirstCharToLower(tableName) + @"." + tableIdName + @";
                        msg = " + FirstCharToUpper(interTable.Name) + @"Instance.Add" + FirstCharToUpper(interTable.Name) + @"(ref " + FirstCharToLower(interTable.Name) + @");
                    }
                }
";
                n_m_remove_init       += @"
                if(" + removeParameterName + @" != null)
                {
                    for (int i = 0; i < " + removeParameterName + @".Count; i++)
                    {
                        msg = " + FirstCharToUpper(interTable.Name) + @"Instance.Remove" + FirstCharToUpper(interTable.Name) + @"(" + removeParameterName + @"[i]);
                    }
                }
";
            }
            string res = "";

            if (n_m_add_parameters == "")
            {
                res = @"
        [HttpPost]
        public string Update" + FirstCharToUpper(tableName) + @"(" + FirstCharToUpper(tableName) + " " + FirstCharToLower(tableName) + n_m_add_parameters + n_m_remove_parameters + @")
        {
            MessageModel msg = null;
            MessageModel updateMsg = " + FirstCharToUpper(tableName) + @"Instance.Update" + FirstCharToUpper(tableName) + @"(" + FirstCharToLower(tableName) + @");
            " + n_m_add_init + @"
            " + n_m_remove_init + @"
            return JsonConvert.SerializeObject(updateMsg);
        }
";
            }
            else
            {
                res = @"
        [HttpPost]
        public string Update" + FirstCharToUpper(tableName) + @"(" + FirstCharToUpper(tableName) + " " + FirstCharToLower(tableName) + @")
        {
            MessageModel msg = null;
            MessageModel updateMsg = " + FirstCharToUpper(tableName) + @"Instance.Update" + FirstCharToUpper(tableName) + @"(" + FirstCharToLower(tableName) + @");
            return JsonConvert.SerializeObject(updateMsg);
        }
        [HttpPost]
        public string Update" + FirstCharToUpper(tableName) + @"(" + FirstCharToUpper(tableName) + " " + FirstCharToLower(tableName) + n_m_add_parameters + n_m_remove_parameters + @")
        {
            MessageModel msg = null;
            MessageModel updateMsg = " + FirstCharToUpper(tableName) + @"Instance.Update" + FirstCharToUpper(tableName) + @"(" + FirstCharToLower(tableName) + @");
            " + n_m_add_init + @"
            " + n_m_remove_init + @"
            return JsonConvert.SerializeObject(updateMsg);
        }
";
            }

            return(res);
        }