Ejemplo n.º 1
0
        public IActionResult Upload(IFormFile fupFile, string name, string uniquekey)
        {
            // Import Stats
            DateTime startImport = DateTime.Now;
            long     lineCreated = 0;
            // end stats


            Project thisProject = new Project()
            {
                Key = uniquekey
            };
            List <ProjectFile> thisFiles = new List <ProjectFile>();

            string uploadFolder  = Path.GetFullPath("Uploads") + "\\" + uniquekey + "\\";
            string filePath      = uploadFolder + fupFile.FileName;
            string nameSpaceName = getCleanNameSpace(fupFile.FileName);

            // create directory for upload
            Directory.CreateDirectory(uploadFolder);
            //
            string saveFolderPath = Path.GetFullPath("Projects") + @"\" + thisProject.Key;

            // copy uploaded file to upload directory.
            using (FileStream fs = new FileStream(filePath, FileMode.Create)) {
                fupFile.CopyTo(fs);
                fs.Close();
            }
            List <string>       messages        = new List <string>();
            List <ProjectClass> classes         = SQLScriptConversion.generateObjects(filePath, ref messages);
            ProjectVariable     nameSpaceObject = new ProjectVariable(1, nameSpaceName);

            StaticVariables.Instance.NameSpaceNames.Append(nameSpaceObject);
            DALClass dalClassObject = getNewDAL(nameSpaceObject);

            if (!Directory.Exists(saveFolderPath))
            {
                // no directory; create it
                Directory.CreateDirectory(saveFolderPath);
            }
            StringBuilder sprocScripts = new StringBuilder();
            StringBuilder dalFunctions = new StringBuilder();

            foreach (ProjectClass pClass in classes)
            {
                String fileName = pClass.Name.Capitalized() + ".cs";
                pClass.DALClassVariable  = dalClassObject;
                pClass.NameSpaceVariable = nameSpaceObject;
                string classContent = ClassGenerator.getEntireClass(pClass, name, CodeGeneration.Language.CSharp, CodeGeneration.Format.ASPX, ref messages);
                // save file to project folder.
                using (StreamWriter sw = new StreamWriter(saveFolderPath + @"\" + fileName, false)) {
                    lineCreated += classContent.Count('\n');
                    sw.Write(classContent);
                }

                thisFiles.Add(new ProjectFile()
                {
                    Name    = fileName, PhysicalPath = saveFolderPath + @"\",
                    Project = thisProject
                });

                sprocScripts.Append(StoredProcsGenerator.getSprocText(pClass, name, ref messages));
                dalFunctions.Append(DALGenerator.getDALFunctions(pClass, CodeGeneration.Language.CSharp));
            }

            // Save SProcs file
            string sprocFileName = "StoredProcedures.sql";

            using (StreamWriter sw = new StreamWriter(saveFolderPath + @"\" + sprocFileName, false)) {
                string sprocString = sprocScripts.ToString();
                lineCreated += sprocString.Count('\n');
                sw.Write(sprocString);
                thisFiles.Add(new ProjectFile()
                {
                    Name    = sprocFileName, PhysicalPath = saveFolderPath + @"\",
                    Project = thisProject
                });
            }

            // Save DAL file
            string dalContent  = DALGenerator.getDALText("ReadOnlyConnectionString", "EditOnlyConnectionString", dalClassObject, dalFunctions, CodeGeneration.Language.CSharp);
            string dalFileName = dalClassObject.Name + ".cs";

            using (StreamWriter sw = new StreamWriter(saveFolderPath + @"\" + dalFileName, false)) {
                lineCreated += dalContent.Count('\n');
                sw.Write(dalContent);
                thisFiles.Add(new ProjectFile()
                {
                    Name    = dalFileName, PhysicalPath = saveFolderPath + @"\",
                    Project = thisProject
                });
            }

            TimeSpan timeTaken = DateTime.Now - startImport;

            thisProject.Files = thisFiles;
            thisProject.ConversionMessages = messages;
            thisProject.LinesGenerated     = lineCreated;
            thisProject.TimeTaken          = timeTaken;
            string projName = nameSpaceName + ".proj";

            using (StreamWriter sw = new StreamWriter(saveFolderPath + @"\" + projName, false)) {
                string projJSON = System.Text.Json.JsonSerializer.Serialize(thisProject);
                sw.Write(projJSON);
            }
            //return View(thisProject);

            //https://stackoverflow.com/questions/13510204/json-net-self-referencing-loop-detected
            TempData["CurrentProject"] = Newtonsoft.Json.JsonConvert.SerializeObject(thisProject,
                                                                                     new Newtonsoft.Json.JsonSerializerSettings()
            {
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            });
            return(RedirectToAction("List", new { uniquekey = thisProject.Key }));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Generates Data Access, Mapping and Transfer Code from the Database
        /// </summary>
        /// <param name="FolderPath"></param>
        /// <param name="ServerName"></param>
        /// <param name="DatabaseName"></param>
        public static void GenerateFromDatabase(GenerationInfo GenInfo)
        {
            DirectoryInfo d = new DirectoryInfo(GenInfo.FolderPath);

            Microsoft.SqlServer.Management.Common.ServerConnection svrCon = new Microsoft.SqlServer.Management.Common.ServerConnection(GenInfo.ServerName);
            Server svr = new Server(svrCon);

            String DbScriptsPath = GenInfo.FolderPath + @"\Procedures";

            foreach (Microsoft.SqlServer.Management.Smo.Database datab in svr.Databases)
            {
                if (datab.IsAccessible)
                {
                    if (!(DatabasesToIgnore().Contains(datab.Name)))
                    {
                        if (datab.Name.ToLower() == GenInfo.DataBase.ToLower())
                        {
                            Console.Write("Generating Code for Database: " + datab.Name + "\n");
                            String RepositoryPath     = GenInfo.FolderPath + @"\" + datab.Name; // The Current Repository
                            String DataLayerNamespace = String.Format("{0}.{1}.{2}", GenInfo.CompanyName, GenInfo.DataNameSpace, datab.Name);

                            #region [ Clean / Create Directory ]
                            if (Directory.Exists(RepositoryPath))
                            {
                                // Directory Exists clean it out
                                DirectoryInfo dRepository = new DirectoryInfo(RepositoryPath);
                                foreach (FileInfo f in dRepository.GetFiles("*.*", SearchOption.AllDirectories))
                                {
                                    f.Delete();
                                }
                            }
                            else
                            {
                                Directory.CreateDirectory(RepositoryPath);
                            }
                            #endregion

                            #region [ Tables ]
                            String RepositoryPathProcedures = RepositoryPath + @"\Procedures";

                            if (Directory.Exists(RepositoryPathProcedures))
                            {
                                Directory.Delete(RepositoryPathProcedures);
                            }
                            Directory.CreateDirectory(RepositoryPathProcedures);
                            Int32         GenerationStep = 0;
                            DALGenerator  dg             = new DALGenerator();
                            POCOGenerator pg             = new POCOGenerator();

                            foreach (Table t in datab.Tables)
                            {
                                GenerationStep = 0;
                                try
                                {
                                    if (t.Name == "Loan")
                                    {
                                        "$".IsNormalized();
                                    }
                                    if (!(t.IsSystemObject))
                                    {
                                        // Check if the table has a primary key, if not then dont generate anything. Table muist be normalized
                                        if (ValidateSqlTable(t))
                                        {
                                            #region [ Generation Root ]
                                            String cpFilename     = RepositoryPathProcedures + @"\\" + "cp_" + t.Name + ".sql";
                                            String sspFileName    = RepositoryPathProcedures + @"\\" + "ssp_" + t.Name + ".sql";
                                            String EntityFileName = RepositoryPath + @"\\" + t.Name + ".cs";
                                            String DALFileName    = RepositoryPath + @"\\" + t.Name + "DAL.cs";
                                            String DOMFileName    = RepositoryPath + @"\\" + t.Name + "DomainObject.cs";

                                            GenerationStep = 1;
                                            // [0]  Stored Procedures
                                            MGenerator.Tools.SqlGeneration.CrudProcedureGenerator gen = new SqlGeneration.CrudProcedureGenerator(datab, t);
                                            gen.Generate(RepositoryPathProcedures, MGenerator.Tools.SqlGeneration.ProcedureGenerationType.Alter);
                                            GenerationStep = 2;

                                            ObjectiveSearchProcedureGenerator ospgen = new ObjectiveSearchProcedureGenerator(datab, t);
                                            ospgen.Generate(RepositoryPathProcedures);
                                            GenerationStep = 3;


                                            // [1]  Data Access Classes
                                            WriteCsharpFile(GenInfo.CompanyName, GenInfo.DataNameSpace, datab.Name, RepositoryPath, dg.BuildDalClass(String.Format("{0}.{1}", GenInfo.CompanyName, GenInfo.DataNameSpace), datab.Name, t));
                                            GenerationStep = 4;

                                            // [2] Entity / Structure Class
                                            WriteCsharpFile(GenInfo.CompanyName, GenInfo.DataNameSpace, datab.Name, RepositoryPath, pg.BuildPoc(t));
                                            GenerationStep = 5;

                                            // [3]  Service Layer
                                            DomainServiceGraph svcgen = new DomainServiceGraph();
                                            WriteCsharpFile(GenInfo.CompanyName, GenInfo.DataNameSpace, datab.Name, RepositoryPath, svcgen.BuildDomainObject(String.Format("{0}.{1}", GenInfo.CompanyName, GenInfo.DataNameSpace), datab.Name, t));
                                            GenerationStep = 6;

                                            // [4] API
                                            ApiGraph api      = new ApiGraph();
                                            string   api_name =
                                                api.WriteApiStation(GenInfo, datab, t, RepositoryPath);
                                            #endregion

                                            Console.Write(t.Name + "....COMPLETE" + "\n");
                                        }
                                    }
                                }
                                catch (Exception x)
                                {
                                    Console.Write(t.Name + "....ERROR" + "\n");
                                    // File.WriteAllText(RepositoryPath + t.Name + ".txt", x.Message + "\n Generation Step:" + GenerationStep.ToString() );
                                    continue;
                                }
                            }
                            #endregion

                            #region [ Views ]
                            foreach (View view in datab.Views)
                            {
                                try
                                {
                                    if (view.Name == "vwLOLicense")
                                    {
                                        String fd = "";
                                    }
                                    if (!(view.IsSystemObject))
                                    {
                                        if (ValidateSqlView(view))
                                        {
                                            ObjectiveSearchProcedureGenerator ospgen = new ObjectiveSearchProcedureGenerator(datab, view);
                                            DomainServiceGraph svcgen = new DomainServiceGraph();
                                            ospgen.Generate(RepositoryPathProcedures);
                                            WriteCsharpFile(GenInfo.CompanyName, GenInfo.DataNameSpace, datab.Name, RepositoryPath, dg.BuildDalClass(String.Format("{0}.{1}", GenInfo.CompanyName, GenInfo.DataNameSpace), datab.Name, view));
                                            WriteCsharpFile(GenInfo.CompanyName, GenInfo.DataNameSpace, datab.Name, RepositoryPath, pg.BuildPoco(view));
                                            WriteCsharpFile(GenInfo.CompanyName, GenInfo.DataNameSpace, datab.Name, RepositoryPath, svcgen.BuildDomainObject(String.Format("{0}.{1}", GenInfo.CompanyName, GenInfo.DataNameSpace), datab.Name, view));
                                            Console.Write(view.Name + "....COMPLETE" + "\n");
                                        }
                                    }
                                }
                                catch (Exception x)
                                {
                                    Console.Write(view.Name + "....ERROR" + "\n");
                                    continue;
                                }
                            }
                            #endregion
                        }
                    }
                }
            }
        }