Beispiel #1
0
        public ImportDatabaseForm(
            nHydrateModel model,
            nHydrate.DataImport.Database currentDatabase,
            Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData)
            : this()
        {
            _model = model;
            this.CurrentDatabase = currentDatabase;

            this.DatabaseConnectionControl1.FileName = Path.Combine((new FileInfo(docData.FileName)).DirectoryName, "importconnection.cache");

            tvwAdd.AfterCheck     += new TreeViewEventHandler(treeView1_AfterCheck);
            tvwRefresh.AfterCheck += new TreeViewEventHandler(treeView1_AfterCheck);
            tvwDelete.AfterCheck  += new TreeViewEventHandler(treeView1_AfterCheck);

            //tvwAdd.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);
            //tvwRefresh.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);
            //tvwDelete.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);

            wizard1.BeforeSwitchPages   += new nHydrate.Wizard.Wizard.BeforeSwitchPagesEventHandler(wizard1_BeforeSwitchPages);
            wizard1.AfterSwitchPages    += new nHydrate.Wizard.Wizard.AfterSwitchPagesEventHandler(wizard1_AfterSwitchPages);
            wizard1.Finish              += new EventHandler(wizard1_Finish);
            wizard1.FinishEnabled        = false;
            chkSettingPK.CheckedChanged += new EventHandler(chkSettingPK_CheckedChanged);
            cmdTestConnection.Click     += new EventHandler(cmdTestConnection_Click);

            this.Settings = new ImportModelSettings();
            this.Settings.OverridePrimaryKey = chkSettingPK.Checked;

            DatabaseConnectionControl1.LoadSettings();

            EnableButtons();
        }
Beispiel #2
0
        private List <nHydrateGeneratorProject> BuildModelList(nHydrateModel model, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData)
        {
            var genList = new List <nHydrateGeneratorProject>();

            var genProject = new nHydrateGeneratorProject();

            genList.Add(genProject);
            var root = CreatePOCOModel(model, diagram);

            root.SetKey(model.Id.ToString());
            root.GeneratorProject            = genProject;
            genProject.RootController.Object = root;
            var fi = new System.IO.FileInfo(docData.FileName);

            genProject.FileName = docData.FileName + ".generating";
            var document = new System.Xml.XmlDocument();

            document.LoadXml("<modelRoot guid=\"" + model.Id + "\" type=\"nHydrate.Generator.nHydrateGeneratorProject\" assembly=\"nHydrate.Generator.dll\"><ModelRoot></ModelRoot></modelRoot>");
            ((nHydrate.Generator.Common.GeneratorFramework.IXMLable)root).XmlAppend(document.DocumentElement.ChildNodes[0]);
            System.IO.File.WriteAllText(genProject.FileName, document.ToIndentedString());

            ProcessRenamed(genProject.FileName + ".sql.lastgen", root);

            root.RemovedTables.AddRange(model.RemovedTables);

            //NOTE: This caused diff scripts to be generated EVERY time so removed for now
            //Remove associative tables since they cause issues if they exist
            //root.RemovedTables.AddRange(model.Entities.Where(x => x.IsAssociative && x.IsGenerated).Select(x => x.Name));

            root.RemovedViews.AddRange(model.RemovedViews);
            //Remove EnumOnly type-tables from the project
            root.RemovedTables.AddRange(model.Entities.Where(x => x.TypedEntity == TypedEntityConstants.EnumOnly).Select(x => x.Name));

            return(genList);
        }
        public RefactorCombineTableForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram, nHydrateModel model, Entity entity1, Entity entity2)
            : this()
        {
            _store   = store;
            _model   = model;
            _diagram = diagram;
            _entity1 = entity1;
            _entity2 = entity2;

            lblEntity1.Text = entity1.Name;
            lblEntity2.Text = entity2.Name;

            var fieldList = new List <Field>();

            fieldList.AddRange(entity1.Fields);
            fieldList.AddRange(entity2.Fields);
            fieldList.Remove(x => entity2.PrimaryKeyFields.Contains(x));

            if (fieldList.Select(x => x.Name.ToLower()).Count() != fieldList.Select(x => x.Name.ToLower()).Distinct().Count())
            {
                cmdApply.Enabled = false;
                lblError.Text    = "Duplicate field names are not allowed.";
                lblError.Visible = true;
            }

            fieldList.ForEach(x => lstField.Items.Add(x.Name));
        }
 public ModelUtilitiesForm(nHydrateModel model, Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram)
     : this()
 {
     _model   = model;
     _store   = store;
     _diagram = diagram;
 }
        public UserDefinedScriptOrderForm(nHydrateModel model, Microsoft.VisualStudio.Modeling.Store store)
            : this()
        {
            _model = model;
            _store = store;

            if (_model.UseModules)
            {
                foreach (var module in _model.Modules)
                {
                    cboInstaller.Items.Add(this.DefaultNamespace + "." + module.Name + ".Install");
                }
            }
            else
            {
                cboInstaller.Items.Add(this.DefaultNamespace + ".Install");
            }

            if (cboInstaller.Items.Count > 0)
            {
                cboInstaller.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("There are no modules in this model so no installer project can be selected.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            LoadItems();
        }
        public static void LoadDiagramFiles(nHydrateModel model, string rootFolder, string modelName, nHydrateDiagram diagram)
        {
            if (!model.ModelToDisk)
                return;

            var fileName = Path.Combine(GetModelFolder(rootFolder, modelName), "diagram.xml");
            if (!File.Exists(fileName)) return;
            using (var transaction = model.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
            {
                var document = new XmlDocument();
                var id = Guid.Empty;
                try
                {
                    document.Load(fileName);
                    if (document.DocumentElement == null) throw new Exception("No Root"); //this is thrown away

                    foreach (XmlNode node in document.DocumentElement.ChildNodes)
                    {
                        id = XmlHelper.GetAttributeValue(node, "id", Guid.Empty);
                        var shape = diagram.NestedChildShapes.FirstOrDefault(x => x.ModelElement.Id == id) as Microsoft.VisualStudio.Modeling.Diagrams.NodeShape;
                        if (shape != null)
                            shape.Bounds = Extensions.ConvertRectangleDFromXmlValue(XmlHelper.GetAttributeValue(node, "bounds", string.Empty));
                    }
                }
                catch (Exception ex) { return; }
                transaction.Commit();
            }
        }
        public RelationCollectionForm(
            nHydrateModel model,
            EntityShape entityShape,
            Microsoft.VisualStudio.Modeling.Store store,
            Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram,
            nHydrateDocData docData)
            : this()
        {
            _model       = model;
            _store       = store;
            _diagram     = diagram;
            _docData     = docData;
            _entityShape = entityShape;

            lvwMembers.Columns.Clear();
            lvwMembers.Columns.Add(new ColumnHeader()
            {
                Text = "Parent", Width = 200
            });
            lvwMembers.Columns.Add(new ColumnHeader()
            {
                Text = "Child", Width = 200
            });
            lvwMembers.Columns.Add(new ColumnHeader()
            {
                Text = "Role", Width = 200
            });

            lvwMembers.ListViewItemSorter = new nHydrate.Generator.Common.Forms.CommonLibrary.ListViewItemComparer(0, lvwMembers.Sorting);
            lvwMembers.Sort();

            this.LoadList();
        }
Beispiel #8
0
        public void Generate(nHydrateModel model, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData)
        {
            this.ErrorList    = new List <string>();
            GeneratedFileList = new List <nHydrate.Generator.Common.EventArgs.ProjectItemGeneratedEventArgs>();
            try
            {
                #region Generation

                //Clean up delete tracking
                model.RemovedTables.Remove(x => model.Entities.Select(y => y.PascalName).Contains(x));
                model.RemovedViews.Remove(x => model.Views.Select(y => y.PascalName).Contains(x));

                var g = new nHydrate.Generator.Common.GeneratorFramework.GeneratorHelper();
                g.ProjectItemGenerated += new nHydrate.Generator.Common.GeneratorFramework.ProjectItemGeneratedEventHandler(g_ProjectItemGenerated);

                var genList = BuildModelList(model, diagram, docData);

                var excludeList       = new List <Type>();
                var generatorTypeList = g.GetProjectGenerators(genList.First());
                if (generatorTypeList.Count == 0)
                {
                    return; //add message box
                }
                if (ChooseGenerators(model, genList, generatorTypeList, excludeList, g))
                {
                    //Perform actual generation
                    if (genList.Count > 0)
                    {
                        PerformGeneration(model, genList, diagram.Store, docData, excludeList, g);
                    }

                    model.RemovedTables.Clear();
                    model.RemovedViews.Clear();
                }

                #endregion

                //Remove temp file
                try
                {
                    genList.ForEach(x => System.IO.File.Delete(x.FileName));
                }
                catch { }

#if DEBUG
                if (this.ErrorList.Count > 0)
                {
                    var F = new nHydrate.DslPackage.Forms.ErrorForm();
                    F.SetErrors(this.ErrorList);
                    F.ShowDialog();
                }
#endif
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #9
0
 public IndexesForm(List <Entity> entityList, nHydrateModel model, Store store)
     : this()
 {
     _model      = model;
     _store      = store;
     _entityList = entityList;
     LoadGrid();
     lblHeader.Text = "A list of indexed fields";
 }
Beispiel #10
0
 public StaticDataForm(Entity entity, Microsoft.VisualStudio.Modeling.Store store, nHydrateModel model, Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData)
     : this()
 {
     _entity  = entity;
     _store   = store;
     _model   = model;
     _docData = docData;
     this.LoadData();
 }
Beispiel #11
0
        public TableCompositeColumnForm(Composite composite, nHydrateModel model, Microsoft.VisualStudio.Modeling.Store store)
            : this()
        {
            _composite = composite;
            _model     = model;
            _store     = store;

            this.RefreshForm();
        }
Beispiel #12
0
        private static void LoadFromDisk(IEnumerable <View> list, nHydrateModel model, DiskModel diskModel)
        {
            #region Load other parameter/field information

            foreach (var view in diskModel.Views)
            {
                var item = list.FirstOrDefault(x => x.Id == new Guid(view.id));
                if (item == null)
                {
                    item = new View(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, new Guid(view.id)) });
                    model.Views.Add(item);
                }

                System.Windows.Forms.Application.DoEvents();

                item.Name                   = view.name;
                item.CodeFacade             = view.codefacade;
                item.Schema                 = view.schema;
                item.GeneratesDoubleDerived = view.generatesdoublederived != 0;
                item.Summary                = view.summary;
                item.SQL = view.sql;

                var nameList = new List <string>();
                foreach (var fieldNode in view.fieldset)
                {
                    var subItemID = new Guid(fieldNode.id);
                    var field     = item.Fields.FirstOrDefault(x => x.Id == subItemID);
                    if (field == null)
                    {
                        field = new ViewField(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, subItemID) });
                        item.Fields.Add(field);
                    }

                    field.Name       = fieldNode.name;
                    field.CodeFacade = fieldNode.codefacade;
                    nameList.Add(field.Name.ToLower());
                    field.Nullable = fieldNode.nullable != 0;
                    if (Enum.TryParse <DataTypeConstants>(fieldNode.datatype, true, out var dt))
                    {
                        field.DataType = dt;
                    }
                    field.Default      = fieldNode.@default;
                    field.Length       = fieldNode.length;
                    field.Scale        = fieldNode.scale;
                    field.Summary      = fieldNode.summary;
                    field.IsPrimaryKey = fieldNode.isprimarykey != 0;
                }
                if (item.Fields.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0)
                {
                    item.nHydrateModel.IsDirty = true;
                }
            }

            #endregion
        }
Beispiel #13
0
        public PrecedenseOrderForm(nHydrateModel model, Microsoft.VisualStudio.Modeling.Store store)
            : this()
        {
            _model = model;
            _store = store;

            var list = PrecedenceUtil.GetAllPrecedenceItems(_model).ToList();

            list.Sort(new PrecedenseComparer());
            LoadGrid(list);
        }
Beispiel #14
0
        public IndexColumnOrder(Index index, nHydrateModel model, Store store)
            : this()
        {
            _index = index;
            _model = model;
            _store = store;

            foreach (var indexColumn in index.IndexColumns.OrderBy(x => x.SortOrder))
            {
                lstItem.Items.Add(indexColumn);
            }
        }
        public RefactorPreviewCreateAssociativeForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram, nHydrateModel model, Entity entity1, Entity entity2)
            : this()
        {
            _store   = store;
            _model   = model;
            _diagram = diagram;
            _entity1 = entity1;
            _entity2 = entity2;

            lblEntity1.Text = entity1.Name;
            lblEntity2.Text = entity2.Name;
            txtName.Text    = _entity1.Name + _entity2.Name;
        }
Beispiel #16
0
        public static void SaveToDisk(nHydrateModel modelRoot, string rootFolder, string modelName, nHydrateDiagram diagram)
        {
            modelRoot.IsSaving = true;
            try
            {
                var folderName        = modelName.Replace(".nhydrate", ".model");
                var modelFolder       = GetModelFolder(rootFolder, folderName);
                var generatedFileList = new List <string>();
                nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Views, modelFolder, diagram, generatedFileList); //must come before entities
                nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Entities, modelFolder, diagram, generatedFileList);
                nHydrate.Dsl.Custom.SQLFileManagement.SaveDiagramFiles(modelFolder, diagram, generatedFileList);
                RemoveOrphans(modelFolder, generatedFileList);

                try
                {
                    var compressedFile = Path.Combine(rootFolder, modelName + ".zip");
                    if (File.Exists(compressedFile))
                    {
                        File.Delete(compressedFile);
                        System.Threading.Thread.Sleep(300);
                    }

                    //Create ZIP file with entire model folder
                    System.IO.Compression.ZipFile.CreateFromDirectory(modelFolder, compressedFile, System.IO.Compression.CompressionLevel.Fastest, true);

                    //Now add the top level model artifacts
                    var artifacts = Directory.GetFiles(rootFolder, $"{modelName}.*").ToList();
                    artifacts.RemoveAll(x => x == compressedFile);
                    using (var zipToOpen = System.IO.Compression.ZipFile.Open(compressedFile, System.IO.Compression.ZipArchiveMode.Update))
                    {
                        foreach (var ff in artifacts)
                        {
                            var fi = new FileInfo(ff);
                            zipToOpen.CreateEntryFromFile(ff, fi.Name);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Do Nothing
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                modelRoot.IsSaving = false;
            }
        }
Beispiel #17
0
        private static void LoadFromDisk(IEnumerable <View> list, nHydrateModel model, DiskModelYaml diskModel)
        {
            #region Load other parameter/field information

            foreach (var view in diskModel.Views)
            {
                var item = list.FirstOrDefault(x => x.Id == view.Id);
                if (item == null)
                {
                    item = new View(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, view.Id) });
                    model.Views.Add(item);
                }

                System.Windows.Forms.Application.DoEvents();

                item.Name                   = view.Name;
                item.CodeFacade             = view.CodeFacade;
                item.Schema                 = view.Schema;
                item.GeneratesDoubleDerived = view.GeneratesDoubleDerived;
                item.Summary                = view.Summary;
                item.SQL = view.Sql;

                var nameList = new List <string>();
                foreach (var fieldNode in view.Fields)
                {
                    var field = item.Fields.FirstOrDefault(x => x.Id == fieldNode.Id);
                    if (field == null)
                    {
                        field = new ViewField(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, fieldNode.Id) });
                        item.Fields.Add(field);
                    }

                    field.Name       = fieldNode.Name;
                    field.CodeFacade = fieldNode.CodeFacade;
                    nameList.Add(field.Name.ToLower());
                    field.Nullable     = fieldNode.Nullable;
                    field.DataType     = fieldNode.Datatype.Convert <DataTypeConstants>();
                    field.Default      = fieldNode.Default;
                    field.Length       = fieldNode.Length;
                    field.Scale        = fieldNode.Scale;
                    field.Summary      = fieldNode.Summary;
                    field.IsPrimaryKey = fieldNode.IsPrimaryKey;
                }
                if (item.Fields.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0)
                {
                    item.nHydrateModel.IsDirty = true;
                }
            }

            #endregion
        }
Beispiel #18
0
        private bool ChooseGenerators(
            nHydrateModel model,
            List <nHydrateGeneratorProject> genList,
            List <Type> generatorTypeList,
            List <Type> excludeList,
            nHydrate.Generator.Common.GeneratorFramework.GeneratorHelper genHelper)
        {
            if (!genList.Any())
            {
                MessageBox.Show("There are no generators defined", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }

            var cacheFile = new nHydrate.Generator.Common.ModelCacheFile(genList.First());

            if (cacheFile.ModelerVersion > System.Reflection.Assembly.GetExecutingAssembly().GetName().Version)
            {
                if (MessageBox.Show($"This model schema was last generated with a newer modeler version ({cacheFile.ModelerVersion}). Your current version is {System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}. Generating with an older modeler may cause many files to change unexpectedly. Do you wish to proceed with the generation?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                {
                    return(false);
                }
            }

            //Initialize all the model configuration objects
            var modelRoot = genList.First().Model as ModelRoot;

            modelRoot.ModelConfigurations = new Dictionary <string, IModelConfiguration>();
            foreach (var genType in generatorTypeList)
            {
                var generator = genHelper.GetProjectGenerator(genType);
                modelRoot.ModelConfigurations.Add(generator.GetType().Name, generator.ModelConfiguration);
            }

            //Show generator list
            using (var F = new GenerateSettings(genList.First(), generatorTypeList, null))
            {
                if (F.ShowDialog() != DialogResult.OK)
                {
                    return(false);
                }
                excludeList.AddRange(F.ExcludeList);
            }

            return(true);
        }
        public RefactorSplitTableForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram, nHydrateModel model, Entity entity)
            : this()
        {
            _store   = store;
            _model   = model;
            _diagram = diagram;
            _entity  = entity;
            wizard1.FinishEnabled = false;
            lblSourceEntity.Text  = entity.Name;

            foreach (var field in entity.Fields.Where(x => !x.IsPrimaryKey).OrderBy(x => x.Name))
            {
                lstField1.Items.Add(new DisplayFieldItem()
                {
                    Field = field
                });
            }
        }
Beispiel #20
0
        public RefactorRetypePkForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateModel model, Entity entity)
            : this()
        {
            _store  = store;
            _model  = model;
            _entity = entity;

            foreach (var s in Enum.GetNames(typeof(DataTypeConstants)))
            {
                cboType.Items.Add(s);
            }

            cboType.SelectedItem = entity.PrimaryKeyFields.First().DataType.ToString();

            var tree = new Dictionary <EntityHasEntities, Field>();

            BuildRelationTree(entity, tree);

            var used = new List <string>();

            foreach (var r in tree.Keys)
            {
                var otherField = tree[r];
                var c          = r.ParentEntity.Name + "." + otherField.Name;
                var p          = r.ChildEntity.Name + "." + otherField.Name;
                if (!used.Contains(p))
                {
                    lstItem.Items.Add(new RelationDisplay()
                    {
                        Display = p, Relation = r
                    });
                    used.Add(p);
                }
                if (!used.Contains(c))
                {
                    lstItem.Items.Add(new RelationDisplay()
                    {
                        Display = c, Relation = r
                    });
                    used.Add(c);
                }
            }
        }
Beispiel #21
0
        public RefactorPreviewChangeVarcharForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateModel model, List <Microsoft.VisualStudio.Modeling.ModelElement> list)
            : this()
        {
            _store = store;
            _model = model;
            _list  = list;

            //If the list is null then this use the whole model
            if (_list == null)
            {
                _list = new List <Microsoft.VisualStudio.Modeling.ModelElement>();
                _list.AddRange(_model.Entities);
                _list.AddRange(_model.Views);
                _list.AddRange(_model.StoredProcedures);
                _list.AddRange(_model.Functions);
            }

            this.Populate();
        }
Beispiel #22
0
        public RefreshItemFromDatabase(
            nHydrateModel model,
            nHydrate.Dsl.IDatabaseEntity modelElement,
            Microsoft.VisualStudio.Modeling.Store store,
            Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData)
            : this()
        {
            if (modelElement == null)
            {
                throw new Exception("Model element canot be null.");
            }

            _model        = model;
            _store        = store;
            _modelElement = modelElement;
            _importDomain = new nHydrate.DataImport.SqlClient.ImportDomain();

            this.DatabaseConnectionControl1.FileName = Path.Combine((new FileInfo(docData.FileName)).DirectoryName, "importconnection.cache");
            DatabaseConnectionControl1.LoadSettings();

            //Setup new model
            _auditFields.Add(new SpecialField {
                Name = _model.CreatedByColumnName, Type = SpecialFieldTypeConstants.CreatedBy
            });
            _auditFields.Add(new SpecialField {
                Name = _model.CreatedDateColumnName, Type = SpecialFieldTypeConstants.CreatedDate
            });
            _auditFields.Add(new SpecialField {
                Name = _model.ModifiedByColumnName, Type = SpecialFieldTypeConstants.ModifiedBy
            });
            _auditFields.Add(new SpecialField {
                Name = _model.ModifiedDateColumnName, Type = SpecialFieldTypeConstants.ModifedDate
            });
            _auditFields.Add(new SpecialField {
                Name = _model.TimestampColumnName, Type = SpecialFieldTypeConstants.Timestamp
            });
            _auditFields.Add(new SpecialField {
                Name = _model.TenantColumnName, Type = SpecialFieldTypeConstants.Tenant
            });

            wizard1.FinishEnabled = false;
        }
Beispiel #23
0
        public static void LoadFromDisk(nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store, string modelName)
        {
            model.IsSaving = true;
            try
            {
                var modelFile = Path.Combine(rootFolder, modelName);
                var fi        = new FileInfo(modelFile);
                var showError = (fi.Length > 10); //New file is small so show no error if creating new

                var folderName  = modelName.Replace(".nhydrate", ".model");
                var modelFolder = GetModelFolder(rootFolder, folderName);

                //If the model folder does NOT exist
                if (showError && !Directory.Exists(modelFolder))
                {
                    //Try to use the ZIP file
                    var compressedFile = Path.Combine(rootFolder, modelName + ".zip");
                    if (!File.Exists(compressedFile))
                    {
                        MessageBox.Show("The model folder was not found and the ZIP file is missing. One of these must exist to continue.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    //Unzip the whole file
                    //System.IO.Compression.ZipFile.ExtractToDirectory(compressedFile, rootFolder);
                    ExtractToDirectory(compressedFile, rootFolder, false);
                }

                nHydrate.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Views, model, modelFolder, store); //must come before entities
                nHydrate.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Entities, model, modelFolder, store);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                model.IsSaving = false;
            }
        }
        public RelationshipDialog(nHydrateModel model, Microsoft.VisualStudio.Modeling.Store store, EntityHasEntities connector, bool allowConfigure)
            : this()
        {
            try
            {
                _connector         = connector;
                _model             = model;
                _store             = store;
                _allowConfigure    = allowConfigure;
                chkEnforce.Visible = !model.UseModules;

                //Load the Form
                var parent = connector.ParentEntity;
                lblPrimaryTable.Text = parent.Name;

                if (!allowConfigure)
                {
                    lblSecondaryTable.Text = connector.ChildEntity.Name;
                }

                LoadRelation();

                if (_allowConfigure)
                {
                    cboChildTable.Items.Clear();
                    foreach (var entity in _model.Entities.OrderBy(x => x.Name))
                    {
                        cboChildTable.Items.Add(entity.Name);
                    }

                    lblSecondaryTable.Visible = false;
                    cboChildTable.Visible     = true;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #25
0
        public static void SaveToDisk(nHydrateModel model, string rootFolder, string modelName, nHydrateDiagram diagram)
        {
            var diskModel = new DiskModel();

            model.IsSaving = true;
            try
            {
                diskModel.ModelProperties.EmitChangeScripts = model.EmitChangeScripts;
                diskModel.ModelProperties.CompanyName       = model.CompanyName;
                diskModel.ModelProperties.EmitSafetyScripts = model.EmitSafetyScripts;
                diskModel.ModelProperties.DefaultNamespace  = model.DefaultNamespace;
                diskModel.ModelProperties.ProjectName       = model.ProjectName;
                diskModel.ModelProperties.UseUTCTime        = model.UseUTCTime;
                diskModel.ModelProperties.Version           = model.Version;
                diskModel.ModelProperties.Id = model.Id.ToString();
                diskModel.ModelProperties.TenantColumnName           = model.TenantColumnName;
                diskModel.ModelProperties.CreatedByColumnName        = model.CreatedByColumnName;
                diskModel.ModelProperties.CreatedDateColumnName      = model.CreatedDateColumnName;
                diskModel.ModelProperties.ModifiedByColumnName       = model.ModifiedByColumnName;
                diskModel.ModelProperties.ModifiedDateColumnName     = model.ModifiedDateColumnName;
                diskModel.ModelProperties.ConcurrencyCheckColumnName = model.ConcurrencyCheckColumnName;
                diskModel.ModelProperties.GrantExecUser = model.GrantUser;

                var folderName  = modelName.Replace(".nhydrate", ".model");
                var modelFolder = GetModelFolder(rootFolder, folderName);
                nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(diskModel, model.Views);
                nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(diskModel, model.Entities);
                FileManagement.Save(rootFolder, modelName, diskModel);
                nHydrate.Dsl.Custom.SQLFileManagement.SaveDiagramFiles(modelFolder, diagram);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                model.IsSaving = false;
            }
        }
Beispiel #26
0
        public static void LoadFromDisk(nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store, string modelName)
        {
            model.IsSaving = true;
            try
            {
                bool wasLoaded;
                var  diskModel = FileManagement.Load(rootFolder, modelName, out wasLoaded);
                if (wasLoaded)
                {
                    model.EmitChangeScripts = diskModel.ModelProperties.EmitChangeScripts;
                    model.CompanyName       = diskModel.ModelProperties.CompanyName;
                    model.EmitSafetyScripts = diskModel.ModelProperties.EmitSafetyScripts;
                    model.DefaultNamespace  = diskModel.ModelProperties.DefaultNamespace;
                    model.ProjectName       = diskModel.ModelProperties.ProjectName;
                    model.UseUTCTime        = diskModel.ModelProperties.UseUTCTime;
                    model.Version           = diskModel.ModelProperties.Version;
                    //model.Id = new Guid(diskModel.ModelProperties.Id);
                    model.TenantColumnName           = diskModel.ModelProperties.TenantColumnName;
                    model.CreatedByColumnName        = diskModel.ModelProperties.CreatedByColumnName;
                    model.CreatedDateColumnName      = diskModel.ModelProperties.CreatedDateColumnName;
                    model.ModifiedByColumnName       = diskModel.ModelProperties.ModifiedByColumnName;
                    model.ModifiedDateColumnName     = diskModel.ModelProperties.ModifiedDateColumnName;
                    model.ConcurrencyCheckColumnName = diskModel.ModelProperties.ConcurrencyCheckColumnName;
                    model.GrantUser = diskModel.ModelProperties.GrantExecUser;

                    nHydrate.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Views, model, diskModel); //must come before entities
                    nHydrate.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Entities, model, diskModel);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                model.IsSaving = false;
            }
        }
Beispiel #27
0
        public static void LoadDiagramFiles(nHydrateModel model, string rootFolder, string modelName, nHydrateDiagram diagram)
        {
            if (!model.ModelToDisk)
            {
                return;
            }

            var fileName = Path.Combine(GetModelFolder(rootFolder, modelName), "diagram.xml");

            if (!File.Exists(fileName))
            {
                return;
            }
            using (var transaction = model.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
            {
                var document = new XmlDocument();
                var id       = Guid.Empty;
                try
                {
                    document.Load(fileName);
                    if (document.DocumentElement == null)
                    {
                        throw new Exception("No Root");                                   //this is thrown away
                    }
                    foreach (XmlNode node in document.DocumentElement.ChildNodes)
                    {
                        id = XmlHelper.GetAttributeValue(node, "id", Guid.Empty);
                        var shape = diagram.NestedChildShapes.FirstOrDefault(x => x.ModelElement.Id == id) as Microsoft.VisualStudio.Modeling.Diagrams.NodeShape;
                        if (shape != null)
                        {
                            shape.Bounds = Extensions.ConvertRectangleDFromXmlValue(XmlHelper.GetAttributeValue(node, "bounds", string.Empty));
                        }
                    }
                }
                catch (Exception ex) { return; }
                transaction.Commit();
            }
        }
 public static void SaveToDisk(nHydrateModel modelRoot, string rootFolder, string modelName, nHydrateDiagram diagram)
 {
     modelRoot.IsSaving = true;
     try
     {
         var modelFolder = GetModelFolder(rootFolder, modelName);
         var generatedFileList = new List<string>();
         nHydrate2.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.ModelMetadata, modelFolder, diagram, generatedFileList);
         nHydrate2.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Modules, modelFolder, diagram, generatedFileList);
         nHydrate2.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Views, modelFolder, diagram, generatedFileList); //must come before entities (view relations)
         nHydrate2.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Entities, modelFolder, diagram, generatedFileList);
         nHydrate2.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.StoredProcedures, modelFolder, diagram, generatedFileList);
         nHydrate2.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Functions, modelFolder, diagram, generatedFileList);
         nHydrate2.Dsl.Custom.SQLFileManagement.SaveDiagramFiles(modelFolder, diagram, generatedFileList);
         RemoveOrphans(modelFolder, generatedFileList);
     }
     catch (Exception ex)
     {
         throw;
     }
     finally
     {
         modelRoot.IsSaving = false;
     }
 }
Beispiel #29
0
        private static void LoadFromDisk(IEnumerable <Entity> list, nHydrateModel model, DiskModelYaml diskModel)
        {
            #region Load other parameter/field information
            foreach (var entity in diskModel.Entities)
            {
                var item = list.FirstOrDefault(x => x.Id == entity.Id);
                if (item == null)
                {
                    item = new Entity(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, entity.Id) });
                    model.Entities.Add(item);
                }

                System.Windows.Forms.Application.DoEvents();

                #region Properties

                item.Name                   = entity.Name;
                item.AllowCreateAudit       = entity.AllowCreateAudit;
                item.AllowModifyAudit       = entity.AllowModifyAudit;
                item.AllowTimestamp         = entity.AllowTimestamp;
                item.CodeFacade             = entity.CodeFacade;
                item.Immutable              = entity.Immutable;
                item.IsAssociative          = entity.IsAssociative;
                item.GeneratesDoubleDerived = entity.GeneratesDoubleDerived;
                item.IsTenant               = entity.IsTenant;
                item.TypedEntity            = entity.TypedTable.Convert <TypedEntityConstants>();
                item.Schema                 = entity.Schema;
                item.Summary                = entity.Summary;

                #endregion

                #region Fields

                var nameList  = new List <string>();
                var loopIndex = 0;
                foreach (var fieldNode in entity.Fields)
                {
                    var field = item.Fields.FirstOrDefault(x => x.Id == fieldNode.Id);
                    if (field == null)
                    {
                        field = new Field(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, fieldNode.Id) });
                        item.Fields.Add(field);
                    }
                    field.Name       = fieldNode.Name;
                    field.CodeFacade = fieldNode.CodeFacade;
                    nameList.Add(field.Name.ToLower());
                    field.Nullable         = fieldNode.Nullable;
                    field.DataType         = fieldNode.Datatype.Convert <DataTypeConstants>();
                    field.Identity         = fieldNode.Identity.Convert <IdentityTypeConstants>();
                    field.DataFormatString = fieldNode.DataFormatString;
                    field.Default          = fieldNode.Default;
                    field.DefaultIsFunc    = fieldNode.DefaultIsFunc;
                    field.Formula          = fieldNode.Formula;
                    field.IsIndexed        = fieldNode.IsIndexed;
                    field.IsPrimaryKey     = fieldNode.IsPrimaryKey;
                    field.IsCalculated     = fieldNode.IsCalculated;
                    field.IsUnique         = fieldNode.IsUnique;
                    field.Length           = fieldNode.Length;
                    field.Scale            = fieldNode.Scale;
                    field.SortOrder        = loopIndex++;
                    field.IsReadOnly       = fieldNode.IsReadonly;
                    field.Obsolete         = fieldNode.Obsolete;
                    field.Summary          = fieldNode.Summary;
                }
                if (item.Fields.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0)
                {
                    item.nHydrateModel.IsDirty = true;
                }

                #endregion

                LoadEntityIndexes(item, diskModel);

                //Order fields (skip for model that did not have sort order when saved)
                var fc = new FieldOrderComparer();
                if (item.Fields.Count(x => x.SortOrder > 0) > 0)
                {
                    item.Fields.Sort(fc.Compare);
                }
            }

            //Must load relations AFTER ALL entities are loaded
            foreach (var item in model.Entities)
            {
                LoadEntityRelations(item, diskModel);
                LoadEntityStaticData(item, diskModel);
            }

            #endregion
        }
        private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<ModelMetadata> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList)
        {
            if (!list.Any())
                return;

            var document = new XmlDocument();
            document.LoadXml(@"<configuration type=""model.metadata""></configuration>");

            XmlHelper.AddLineBreak((XmlElement)document.DocumentElement);
            foreach (var metadata in list)
            {
                var metaDataNode = XmlHelper.AddElement(document.DocumentElement, "metadata");
                XmlHelper.AddAttribute(metaDataNode, "key", metadata.Key);
                XmlHelper.AddAttribute(metaDataNode, "value", metadata.Value);
                XmlHelper.AddLineBreak((XmlElement)document.DocumentElement);
            }

            var f = Path.Combine(rootFolder, "metadata.configuration.xml");
            WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList);
        }
        /// <summary>
        /// Saves Modules to disk
        /// </summary>
        private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<Module> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList)
        {
            var folder = rootFolder;
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

            var document = new XmlDocument();
            document.LoadXml(@"<configuration type=""module""></configuration>");

            foreach (var item in list)
            {
                var moduleNode = XmlHelper.AddElement(document.DocumentElement, "module") as XmlElement;
                XmlHelper.AddLineBreak(moduleNode);
                XmlHelper.AddCData(moduleNode, "summary", item.Summary);
                XmlHelper.AddAttribute(moduleNode, "id", item.Id);
                XmlHelper.AddAttribute(moduleNode, "name", item.Name);
                XmlHelper.AddLineBreak(moduleNode);

                var rulesNodes = XmlHelper.AddElement(moduleNode, "ruleset") as XmlElement;
                XmlHelper.AddLineBreak((XmlElement)rulesNodes);

                foreach (var rule in item.ModuleRules.OrderBy(x => x.Name))
                {
                    var fieldNode = XmlHelper.AddElement(rulesNodes, "rule");

                    XmlHelper.AddLineBreak((XmlElement)fieldNode);
                    XmlHelper.AddCData((XmlElement)fieldNode, "summary", rule.Summary);
                    XmlHelper.AddLineBreak((XmlElement)fieldNode);

                    XmlHelper.AddAttribute(fieldNode, "status", rule.Status.ToString("d"));
                    XmlHelper.AddAttribute(fieldNode, "dependentmodule", rule.DependentModule);
                    XmlHelper.AddAttribute(fieldNode, "name", rule.Name);
                    XmlHelper.AddAttribute(fieldNode, "inclusion", rule.Inclusion);
                    XmlHelper.AddAttribute(fieldNode, "enforced", rule.Enforced);

                    XmlHelper.AddLineBreak((XmlElement)rulesNodes);
                }

            }

            var f = Path.Combine(folder, "modules.configuration.xml");
            WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList);
            WriteReadMeFile(folder, generatedFileList);
        }
        /// <summary>
        /// Saves Functions to disk
        /// </summary>
        private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<Function> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList)
        {
            var folder = Path.Combine(rootFolder, FOLDER_FC);
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
            foreach (var item in list)
            {
                var f = Path.Combine(folder, item.Name + ".sql");
                WriteFileIfNeedBe(f, item.SQL, generatedFileList);
            }

            #region Save other parameter/field information
            foreach (var item in list)
            {
                var document = new XmlDocument();
                document.LoadXml(@"<configuration type=""function"" name=""" + item.Name + @"""></configuration>");

                XmlHelper.AddLineBreak(document.DocumentElement);
                XmlHelper.AddCData(document.DocumentElement, "summary", item.Summary);
                XmlHelper.AddLineBreak(document.DocumentElement);

                XmlHelper.AddAttribute(document.DocumentElement, "id", item.Id);
                XmlHelper.AddAttribute(document.DocumentElement, "precedenceorder", item.PrecedenceOrder);
                XmlHelper.AddAttribute(document.DocumentElement, "codefacade", item.CodeFacade);
                XmlHelper.AddAttribute(document.DocumentElement, "isgenerated", item.IsGenerated);
                XmlHelper.AddAttribute(document.DocumentElement, "schema", item.Schema);
                XmlHelper.AddAttribute(document.DocumentElement, "istable", item.IsTable);
                XmlHelper.AddAttribute(document.DocumentElement, "returnvariable", item.ReturnVariable);

                var fieldsNodes = XmlHelper.AddElement(document.DocumentElement, "fieldset") as XmlElement;
                XmlHelper.AddLineBreak((XmlElement)fieldsNodes);

                foreach (var field in item.Fields.OrderBy(x => x.Name))
                {
                    var fieldNode = XmlHelper.AddElement(fieldsNodes, "field");

                    XmlHelper.AddLineBreak((XmlElement)fieldNode);
                    XmlHelper.AddCData((XmlElement)fieldNode, "summary", field.Summary);
                    XmlHelper.AddLineBreak((XmlElement)fieldNode);

                    XmlHelper.AddAttribute(fieldNode, "id", field.Id);
                    XmlHelper.AddAttribute(fieldNode, "name", field.Name);
                    XmlHelper.AddAttribute(fieldNode, "nullable", field.Nullable);
                    XmlHelper.AddAttribute(fieldNode, "datatype", field.DataType.ToString());
                    XmlHelper.AddAttribute(fieldNode, "codefacade", field.CodeFacade);
                    XmlHelper.AddAttribute(fieldNode, "default", field.Default);
                    XmlHelper.AddAttribute(fieldNode, "isgenerated", field.IsGenerated);
                    XmlHelper.AddAttribute(fieldNode, "length", field.Length);
                    XmlHelper.AddAttribute(fieldNode, "scale", field.Scale);

                    XmlHelper.AddLineBreak((XmlElement)fieldsNodes);
                }

                var parametersNodes = XmlHelper.AddElement(document.DocumentElement, "parameterset") as XmlElement;
                XmlHelper.AddLineBreak((XmlElement)parametersNodes);

                foreach (var parameter in item.Parameters.OrderBy(x => x.Name))
                {
                    var parameterNode = XmlHelper.AddElement(parametersNodes, "parameter");

                    XmlHelper.AddLineBreak((XmlElement)parameterNode);
                    XmlHelper.AddCData((XmlElement)parameterNode, "summary", parameter.Summary);
                    XmlHelper.AddLineBreak((XmlElement)parameterNode);

                    XmlHelper.AddAttribute(parameterNode, "id", parameter.Id);
                    XmlHelper.AddAttribute(parameterNode, "name", parameter.Name);
                    XmlHelper.AddAttribute(parameterNode, "nullable", parameter.Nullable);
                    XmlHelper.AddAttribute(parameterNode, "datatype", parameter.DataType.ToString());
                    XmlHelper.AddAttribute(parameterNode, "codefacade", parameter.CodeFacade);
                    XmlHelper.AddAttribute(parameterNode, "default", parameter.Default);
                    XmlHelper.AddAttribute(parameterNode, "isgenerated", parameter.IsGenerated);
                    XmlHelper.AddAttribute(parameterNode, "length", parameter.Length);
                    XmlHelper.AddAttribute(parameterNode, "scale", parameter.Scale);

                    XmlHelper.AddLineBreak((XmlElement)parametersNodes);
                }

                XmlHelper.AddLineBreak(document.DocumentElement);
                var f = Path.Combine(folder, item.Name + ".configuration.xml");
                WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList);

                //Save other files
                SaveModules(folder, item, generatedFileList);

            }
            #endregion

            WriteReadMeFile(folder, generatedFileList);
        }
        private static void LoadFromDisk(IEnumerable<Entity> list, nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store)
        {
            var folder = Path.Combine(rootFolder, FOLDER_ET);
            if (!Directory.Exists(folder)) return;

            #region Load other parameter/field information
            var fList = Directory.GetFiles(folder, "*.configuration.xml");
            foreach (var f in fList)
            {
                var document = new XmlDocument();
                try
                {
                    document.Load(f);
                }
                catch (Exception ex)
                {
                    //Do Nothing
                    MessageBox.Show("The file '" + f + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var fi = new FileInfo(f);
                var name = fi.Name.Substring(0, fi.Name.Length - ".configuration.xml".Length).ToLower();
                var itemID = XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.Empty);
                var item = list.FirstOrDefault(x => x.Id == itemID);
                if (item == null)
                {
                    item = new Entity(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.NewGuid())) });
                    model.Entities.Add(item);
                }

                System.Windows.Forms.Application.DoEvents();

                #region Properties

                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                item.Name = XmlHelper.GetAttributeValue(document.DocumentElement, "name", item.Name);
                item.AllowAuditTracking = XmlHelper.GetAttributeValue(document.DocumentElement, "allowaudittracking", item.AllowAuditTracking);
                item.AllowCreateAudit = XmlHelper.GetAttributeValue(document.DocumentElement, "allowcreateaudit", item.AllowCreateAudit);
                item.AllowModifyAudit = XmlHelper.GetAttributeValue(document.DocumentElement, "allowmodifyaudit", item.AllowModifyAudit);
                item.AllowTimestamp = XmlHelper.GetAttributeValue(document.DocumentElement, "allowtimestamp", item.AllowTimestamp);
                item.CodeFacade = XmlHelper.GetAttributeValue(document.DocumentElement, "codefacade", item.CodeFacade);
                item.Immutable = XmlHelper.GetAttributeValue(document.DocumentElement, "immutable", item.Immutable);
                item.EnforcePrimaryKey = XmlHelper.GetAttributeValue(document.DocumentElement, "enforceprimarykey", item.EnforcePrimaryKey);
                item.IsAssociative = XmlHelper.GetAttributeValue(document.DocumentElement, "isassociative", item.IsAssociative);
                item.GeneratesDoubleDerived = XmlHelper.GetAttributeValue(document.DocumentElement, "generatesdoublederived", item.GeneratesDoubleDerived);
                item.IsGenerated = XmlHelper.GetAttributeValue(document.DocumentElement, "isgenerated", item.IsGenerated);
                item.IsTenant = XmlHelper.GetAttributeValue(document.DocumentElement, "isTenant", item.IsTenant);

                var tev = XmlHelper.GetAttributeValue(document.DocumentElement, "typedentity", item.TypedEntity.ToString());
                TypedEntityConstants te;
                if (Enum.TryParse<TypedEntityConstants>(tev, true, out te))
                    item.TypedEntity = te;

                item.Schema = XmlHelper.GetAttributeValue(document.DocumentElement, "schema", item.Schema);
                item.Summary = XmlHelper.GetNodeValue(document.DocumentElement, "summary", item.Summary);
                item.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);

                #endregion

                #region Fields

                var fieldsNodes = document.DocumentElement.SelectSingleNode("//fieldset");
                if (fieldsNodes != null)
                {
                    var nameList = new List<string>();
                    foreach (XmlNode n in fieldsNodes.ChildNodes)
                    {
                        var subItemID = XmlHelper.GetAttributeValue(n, "id", Guid.Empty);
                        var field = item.Fields.FirstOrDefault(x => x.Id == subItemID);
                        if (field == null)
                        {
                            field = new Field(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid())) });
                            item.Fields.Add(field);
                        }
                        field.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                        field.Name = XmlHelper.GetAttributeValue(n, "name", string.Empty);
                        field.CodeFacade = XmlHelper.GetAttributeValue(n, "codefacade", field.CodeFacade);
                        nameList.Add(field.Name.ToLower());
                        field.Nullable = XmlHelper.GetAttributeValue(n, "nullable", field.Nullable);

                        var dtv = XmlHelper.GetAttributeValue(n, "datatype", field.DataType.ToString());
                        DataTypeConstants dt;
                        if (Enum.TryParse<DataTypeConstants>(dtv, true, out dt))
                            field.DataType = dt;

                        var itv = XmlHelper.GetAttributeValue(n, "identity", field.Identity.ToString());
                        IdentityTypeConstants it;
                        if (Enum.TryParse<IdentityTypeConstants>(itv, true, out it))
                            field.Identity = it;

                        field.DataFormatString = XmlHelper.GetNodeValue(n, "dataformatstring", field.DataFormatString);
                        field.Default = XmlHelper.GetAttributeValue(n, "default", field.Default);
                        field.DefaultIsFunc = XmlHelper.GetAttributeValue(n, "defaultisfunc", field.DefaultIsFunc);
                        field.Formula = XmlHelper.GetAttributeValue(n, "formula", field.Formula);
                        field.IsGenerated = XmlHelper.GetAttributeValue(n, "isgenerated", field.IsGenerated);
                        field.IsIndexed = XmlHelper.GetAttributeValue(n, "isindexed", field.IsIndexed);
                        field.IsPrimaryKey = XmlHelper.GetAttributeValue(n, "isprimarykey", field.IsPrimaryKey);
                        field.IsCalculated = XmlHelper.GetAttributeValue(n, "Iscalculated", field.IsCalculated);
                        field.IsUnique = XmlHelper.GetAttributeValue(n, "isunique", field.IsUnique);
                        field.Length = XmlHelper.GetAttributeValue(n, "length", field.Length);
                        field.Scale = XmlHelper.GetAttributeValue(n, "scale", field.Scale);
                        field.SortOrder = XmlHelper.GetAttributeValue(n, "sortorder", field.SortOrder);
                        field.IsReadOnly = XmlHelper.GetAttributeValue(n, "isreadonly", field.IsReadOnly);
                        field.Category = XmlHelper.GetAttributeValue(n, "category", field.Category);
                        field.Collate = XmlHelper.GetAttributeValue(n, "collate", field.Collate);
                        field.FriendlyName = XmlHelper.GetAttributeValue(n, "friendlyname", field.FriendlyName);
                        field.IsBrowsable = XmlHelper.GetAttributeValue(n, "isbrowsable", field.IsBrowsable);
                        field.Max = XmlHelper.GetAttributeValue(n, "max", field.Max);
                        field.Min = XmlHelper.GetAttributeValue(n, "min", field.Min);
                        field.ValidationExpression = XmlHelper.GetAttributeValue(n, "validationexpression", field.ValidationExpression);
                        field.Summary = XmlHelper.GetNodeValue(n, "summary", field.Summary);
                        field.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                    }
                    if (item.Fields.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0)
                        item.nHydrateModel.IsDirty = true;
                }

                #endregion

                LoadEntityIndexes(folder, item);

                //Order fields (skip for model that did not have sort order when saved)
                var fc = new FieldOrderComparer();
                if (item.Fields.Count(x => x.SortOrder > 0) > 0)
                    item.Fields.Sort(fc.Compare);
            }

            //Must load relations AFTER ALL entities are loaded
            foreach (var item in model.Entities)
            {
                LoadEntityRelations(folder, item);
                LoadModules(folder, item);
                LoadEntityStaticData(folder, item);
                LoadEntityMetaData(folder, item);
                LoadEntityComposites(folder, item);
            }

            #endregion
        }
 public RelationshipDialog(nHydrateModel model, Microsoft.VisualStudio.Modeling.Store store, EntityHasEntities connector)
     : this(model, store, connector, false)
 {
 }
 public static void LoadFromDisk(nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store, string modelName)
 {
     model.IsSaving = true;
     try
     {
         var modelFolder = GetModelFolder(rootFolder, modelName);
         nHydrate2.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.ModelMetadata, model, modelFolder, store);
         nHydrate2.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Modules, model, modelFolder, store);
         nHydrate2.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Views, model, modelFolder, store); //must coem before entities (view relations)
         nHydrate2.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Entities, model, modelFolder, store);
         nHydrate2.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.StoredProcedures, model, modelFolder, store);
         nHydrate2.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Functions, model, modelFolder, store);
     }
     catch (Exception ex)
     {
         throw;
     }
     finally
     {
         model.IsSaving = false;
     }
 }
        private static void LoadFromDisk(IEnumerable<Function> list, nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store)
        {
            var folder = Path.Combine(rootFolder, FOLDER_FC);
            if (!Directory.Exists(folder)) return;

            #region Load other parameter/field information
            var fList = Directory.GetFiles(folder, "*.configuration.xml");
            foreach (var f in fList)
            {
                var document = new XmlDocument();
                try
                {
                    document.Load(f);
                }
                catch (Exception ex)
                {
                    //Do Nothing
                    MessageBox.Show("The file '" + f + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var fi = new FileInfo(f);
                var name = fi.Name.Substring(0, fi.Name.Length - ".configuration.xml".Length).ToLower();
                var itemID = XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.Empty);
                var item = list.FirstOrDefault(x => x.Id == itemID);
                if (item == null)
                {
                    item = new Function(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.NewGuid())) });
                    model.Functions.Add(item);
                }

                System.Windows.Forms.Application.DoEvents();

                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                item.Name = XmlHelper.GetAttributeValue(document.DocumentElement, "name", item.Name);
                item.PrecedenceOrder = XmlHelper.GetAttributeValue(document.DocumentElement, "precedenceorder", item.PrecedenceOrder);
                item.IsGenerated = XmlHelper.GetAttributeValue(document.DocumentElement, "isgenerated", item.IsGenerated);
                item.CodeFacade = XmlHelper.GetAttributeValue(document.DocumentElement, "codefacade", item.CodeFacade);
                item.Schema = XmlHelper.GetAttributeValue(document.DocumentElement, "schema", item.Schema);
                item.IsTable = XmlHelper.GetAttributeValue(document.DocumentElement, "istable", item.IsTable);
                item.ReturnVariable = XmlHelper.GetAttributeValue(document.DocumentElement, "returnvariable", item.ReturnVariable);
                item.Summary = XmlHelper.GetNodeValue(document.DocumentElement, "summary", item.Summary);
                item.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);

                //Fields
                var fieldsNodes = document.DocumentElement.SelectSingleNode("//fieldset");
                if (fieldsNodes != null)
                {
                    var nameList = new List<string>();
                    foreach (XmlNode n in fieldsNodes.ChildNodes)
                    {
                        var subItemID = XmlHelper.GetAttributeValue(n, "id", Guid.Empty);
                        var field = item.Fields.FirstOrDefault(x => x.Id == subItemID);
                        if (field == null)
                        {
                            field = new FunctionField(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid())) });
                            item.Fields.Add(field);
                        }

                        field.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                        field.Name = XmlHelper.GetAttributeValue(n, "name", field.Name);
                        field.CodeFacade = XmlHelper.GetAttributeValue(n, "codefacade", field.CodeFacade);
                        nameList.Add(field.Name.ToLower());
                        field.Nullable = XmlHelper.GetAttributeValue(n, "nullable", field.Nullable);
                        var dtv = XmlHelper.GetAttributeValue(n, "datatype", field.DataType.ToString());
                        DataTypeConstants dt;
                        if (Enum.TryParse<DataTypeConstants>(dtv, true, out dt))
                            field.DataType = dt;
                        field.Default = XmlHelper.GetAttributeValue(n, "default", field.Default);
                        field.IsGenerated = XmlHelper.GetAttributeValue(n, "isgenerated", field.IsGenerated);
                        field.Length = XmlHelper.GetAttributeValue(n, "length", field.Length);
                        field.Scale = XmlHelper.GetAttributeValue(n, "scale", field.Scale);
                        field.Summary = XmlHelper.GetNodeValue(n, "summary", field.Summary);
                        field.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                    }
                    if (item.Fields.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0)
                        item.nHydrateModel.IsDirty = true;
                }

                //Parameters
                var parametersNodes = document.DocumentElement.SelectSingleNode("//parameterset");
                if (parametersNodes != null)
                {
                    var nameList = new List<string>();
                    foreach (XmlNode n in parametersNodes.ChildNodes)
                    {
                        var subItemID = XmlHelper.GetAttributeValue(n, "id", Guid.Empty);
                        var parameter = item.Parameters.FirstOrDefault(x => x.Id == subItemID);
                        if (parameter == null)
                        {
                            parameter = new FunctionParameter(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid())) });
                            item.Parameters.Add(parameter);
                        }

                        parameter.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                        parameter.CodeFacade = XmlHelper.GetAttributeValue(n, "codefacade", parameter.CodeFacade);
                        parameter.Name = XmlHelper.GetAttributeValue(n, "name", parameter.Name);
                        nameList.Add(parameter.Name.ToLower());
                        parameter.Nullable = XmlHelper.GetAttributeValue(n, "nullable", parameter.Nullable);
                        var dtv = XmlHelper.GetAttributeValue(n, "datatype", parameter.DataType.ToString());
                        DataTypeConstants dt;
                        if (Enum.TryParse<DataTypeConstants>(dtv, true, out dt))
                            parameter.DataType = dt;
                        parameter.Default = XmlHelper.GetAttributeValue(n, "default", parameter.Default);
                        parameter.IsGenerated = XmlHelper.GetAttributeValue(n, "isgenerated", parameter.IsGenerated);
                        parameter.Length = XmlHelper.GetAttributeValue(n, "length", parameter.Length);
                        parameter.Scale = XmlHelper.GetAttributeValue(n, "scale", parameter.Scale);
                        parameter.Summary = XmlHelper.GetNodeValue(n, "summary", parameter.Summary);
                        parameter.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                    }
                    if (item.Parameters.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0)
                        item.nHydrateModel.IsDirty = true;
                }

                LoadModules(folder, item);
            }
            #endregion

            #region Load SQL
            fList = Directory.GetFiles(folder, "*.sql");
            foreach (var f in fList)
            {
                var fi = new FileInfo(f);
                if (fi.Name.ToLower().EndsWith(".sql"))
                {
                    var name = fi.Name.Substring(0, fi.Name.Length - 4).ToLower();
                    var item = list.FirstOrDefault(x => x.Name.ToLower() == name);
                    if (item != null)
                    {
                        item.SQL = File.ReadAllText(f);
                        System.Windows.Forms.Application.DoEvents();
                    }
                }
            }
            #endregion
        }
        private static void LoadFromDisk(IEnumerable<ModelMetadata> list, nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store)
        {
            var folder = rootFolder;
            if (!Directory.Exists(folder)) return;

            #region Load other parameter/field information
            var fileName = Path.Combine(folder, "metadata.configuration.xml");
            if (!File.Exists(fileName)) return;
            XmlDocument document = null;
            try
            {
                document = new XmlDocument();
                document.Load(fileName);
            }
            catch (Exception ex)
            {
                //Do Nothing
                MessageBox.Show("The file '" + fileName + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (XmlNode n in document.DocumentElement.ChildNodes)
            {
                var item = new ModelMetadata(model.Partition);
                model.ModelMetadata.Add(item);
                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                item.Key = XmlHelper.GetAttributeValue(n, "key", item.Key);
                item.Value = XmlHelper.GetAttributeValue(n, "value", item.Value);
                item.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
            }
            #endregion
        }
        private static void LoadFromDisk(IEnumerable<Module> list, nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store)
        {
            var folder = rootFolder;
            if (!Directory.Exists(folder)) return;

            #region Load other parameter/field information
            var fileName = Path.Combine(folder, "modules.configuration.xml");
            if (!File.Exists(fileName)) return;
            XmlDocument document = null;
            try
            {
                document = new XmlDocument();
                document.Load(fileName);
            }
            catch (Exception ex)
            {
                //Do Nothing
                MessageBox.Show("The file '" + fileName + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (XmlNode n in document.DocumentElement.ChildNodes)
            {
                var id = XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid());
                var item = model.Modules.FirstOrDefault(x => x.Id == id);
                if (item == null)
                {
                    item = new Module(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                    model.Modules.Add(item);
                }

                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                item.Name = XmlHelper.GetAttributeValue(n, "name", item.Name);
                item.Summary = XmlHelper.GetNodeValue(n, "summary", item.Summary);
                item.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);

                //Rules
                var rulesNodes = n.SelectSingleNode("ruleset");
                if (rulesNodes != null)
                {
                    var nameList = new List<string>();
                    foreach (XmlNode m in rulesNodes.ChildNodes)
                    {
                        var rule = new ModuleRule(item.Partition);
                        item.ModuleRules.Add(rule);
                        rule.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                        rule.Name = XmlHelper.GetAttributeValue(m, "name", rule.Name);
                        rule.Status = (ModuleRuleStatusTypeConstants)int.Parse(XmlHelper.GetAttributeValue(m, "status", rule.Status.ToString("d")));
                        rule.DependentModule = XmlHelper.GetAttributeValue(m, "dependentmodule", rule.DependentModule);
                        rule.Inclusion = XmlHelper.GetAttributeValue(m, "inclusion", rule.Inclusion);
                        rule.Enforced = XmlHelper.GetAttributeValue(m, "enforced", rule.Enforced);
                        rule.Summary = XmlHelper.GetNodeValue(m, "summary", rule.Summary);
                        rule.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                    }
                }

            }
            #endregion
        }
        /// <summary>
        /// Saves Stored Procedures to disk
        /// </summary>
        private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<Entity> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList)
        {
            var folder = Path.Combine(rootFolder, FOLDER_ET);
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

            #region Save other parameter/field information
            foreach (var item in list)
            {
                var document = new XmlDocument();
                document.LoadXml(@"<configuration type=""entity"" name=""" + item.Name + @"""></configuration>");

                XmlHelper.AddLineBreak(document.DocumentElement);
                XmlHelper.AddCData(document.DocumentElement, "summary", item.Summary);
                XmlHelper.AddLineBreak(document.DocumentElement);

                XmlHelper.AddAttribute(document.DocumentElement, "id", item.Id);
                XmlHelper.AddAttribute(document.DocumentElement, "allowaudittracking", item.AllowAuditTracking);
                XmlHelper.AddAttribute(document.DocumentElement, "allowcreateaudit", item.AllowCreateAudit);
                XmlHelper.AddAttribute(document.DocumentElement, "allowmodifyaudit", item.AllowModifyAudit);
                XmlHelper.AddAttribute(document.DocumentElement, "allowtimestamp", item.AllowTimestamp);
                XmlHelper.AddAttribute(document.DocumentElement, "codefacade", item.CodeFacade);
                XmlHelper.AddAttribute(document.DocumentElement, "immutable", item.Immutable);
                XmlHelper.AddAttribute(document.DocumentElement, "enforceprimarykey", item.EnforcePrimaryKey);
                XmlHelper.AddAttribute(document.DocumentElement, "isassociative", item.IsAssociative);
                XmlHelper.AddAttribute(document.DocumentElement, "typedentity", item.TypedEntity.ToString());
                XmlHelper.AddAttribute(document.DocumentElement, "schema", item.Schema);
                XmlHelper.AddAttribute(document.DocumentElement, "generatesdoublederived", item.GeneratesDoubleDerived);
                XmlHelper.AddAttribute(document.DocumentElement, "isgenerated", item.IsGenerated);
                XmlHelper.AddAttribute(document.DocumentElement, "isTenant", item.IsTenant);

                #region Fields
                {
                    var fieldsNodes = XmlHelper.AddElement(document.DocumentElement, "fieldset") as XmlElement;
                    XmlHelper.AddLineBreak((XmlElement)fieldsNodes);
                    foreach (var field in item.Fields.OrderBy(x => x.Name))
                    {
                        var fieldNode = XmlHelper.AddElement(fieldsNodes, "field");

                        XmlHelper.AddLineBreak((XmlElement)fieldNode);
                        XmlHelper.AddCData((XmlElement)fieldNode, "summary", field.Summary);
                        XmlHelper.AddLineBreak((XmlElement)fieldNode);

                        XmlHelper.AddAttribute(fieldNode, "id", field.Id);
                        XmlHelper.AddAttribute(fieldNode, "name", field.Name);
                        XmlHelper.AddAttribute(fieldNode, "nullable", field.Nullable);
                        XmlHelper.AddAttribute(fieldNode, "datatype", field.DataType.ToString());
                        XmlHelper.AddAttribute(fieldNode, "identity", field.Identity.ToString());
                        XmlHelper.AddAttribute(fieldNode, "codefacade", field.CodeFacade);
                        XmlHelper.AddAttribute(fieldNode, "dataformatstring", field.DataFormatString);
                        XmlHelper.AddAttribute(fieldNode, "default", field.Default);
                        XmlHelper.AddAttribute(fieldNode, "defaultisfunc", field.DefaultIsFunc);
                        XmlHelper.AddAttribute(fieldNode, "formula", field.Formula);
                        XmlHelper.AddAttribute(fieldNode, "isgenerated", field.IsGenerated);
                        XmlHelper.AddAttribute(fieldNode, "isindexed", field.IsIndexed);
                        XmlHelper.AddAttribute(fieldNode, "isprimarykey", field.IsPrimaryKey);
                        XmlHelper.AddAttribute(fieldNode, "Iscalculated", field.IsCalculated);
                        XmlHelper.AddAttribute(fieldNode, "isunique", field.IsUnique);
                        XmlHelper.AddAttribute(fieldNode, "length", field.Length);
                        XmlHelper.AddAttribute(fieldNode, "scale", field.Scale);
                        XmlHelper.AddAttribute(fieldNode, "sortorder", field.SortOrder);
                        XmlHelper.AddAttribute(fieldNode, "isreadonly", field.IsReadOnly);
                        XmlHelper.AddAttribute(fieldNode, "category", field.Category);
                        XmlHelper.AddAttribute(fieldNode, "collate", field.Collate);
                        XmlHelper.AddAttribute(fieldNode, "friendlyname", field.FriendlyName);
                        XmlHelper.AddAttribute(fieldNode, "isbrowsable", field.IsBrowsable);
                        XmlHelper.AddAttribute(fieldNode, "max", field.Max);
                        XmlHelper.AddAttribute(fieldNode, "min", field.Min);
                        XmlHelper.AddAttribute(fieldNode, "validationexpression", field.ValidationExpression);

                        XmlHelper.AddLineBreak((XmlElement)fieldsNodes);
                    }
                    XmlHelper.AddLineBreak((XmlElement)document.DocumentElement);
                }
                #endregion

                XmlHelper.AddLineBreak(document.DocumentElement);
                var f = Path.Combine(folder, item.Name + ".configuration.xml");
                WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList);

                //Save other files
                SaveEntityIndexes(folder, item, generatedFileList);
                SaveModules(folder, item, generatedFileList);
                SaveRelations(folder, item, generatedFileList);
                SaveEntityStaticData(folder, item, generatedFileList);
                SaveEntityMetaData(folder, item, generatedFileList);
                SaveEntityComposites(folder, item, generatedFileList);

            }
            #endregion

            WriteReadMeFile(folder, generatedFileList);
        }
Beispiel #40
0
        private nHydrate.Generator.Models.ModelRoot CreatePOCOModel(nHydrateModel model, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram)
        {
            try
            {
                var root = new nHydrate.Generator.Models.ModelRoot(null);
                root.EnableCustomChangeEvents = model.EmitChangeScripts;
                root.CompanyName               = model.CompanyName;
                root.EmitSafetyScripts         = model.EmitSafetyScripts;
                root.DefaultNamespace          = model.DefaultNamespace;
                root.ProjectName               = model.ProjectName;
                root.SupportLegacySearchObject = false;
                root.UseUTCTime = model.UseUTCTime;
                root.Version    = model.Version;
                root.Database.ResetKey(model.Id.ToString());
                root.OutputTarget = string.Empty; //model.OutputTarget;
                //These have the same mapping values flags so we need convert to int and then convert to the other enumeration
                root.TenantColumnName                = model.TenantColumnName;
                root.TenantPrefix                    = model.TenantPrefix;
                root.Database.CreatedByColumnName    = model.CreatedByColumnName;
                root.Database.CreatedDateColumnName  = model.CreatedDateColumnName;
                root.Database.ModifiedByColumnName   = model.ModifiedByColumnName;
                root.Database.ModifiedDateColumnName = model.ModifiedDateColumnName;
                root.Database.TimestampColumnName    = model.TimestampColumnName;
                root.Database.GrantExecUser          = model.GrantUser;

                #region Load the entities
                foreach (var entity in model.Entities)
                {
                    #region Table Info
                    var newTable = root.Database.Tables.Add();
                    newTable.ResetKey(entity.Id.ToString());
                    newTable.ResetId(HashString(newTable.Key));
                    newTable.AllowCreateAudit   = entity.AllowCreateAudit;
                    newTable.AllowModifiedAudit = entity.AllowModifyAudit;
                    newTable.AllowTimestamp     = entity.AllowTimestamp;
                    newTable.AssociativeTable   = entity.IsAssociative;
                    newTable.CodeFacade         = entity.CodeFacade;
                    newTable.DBSchema           = entity.Schema;
                    newTable.Description        = entity.Summary;
                    newTable.Immutable          = entity.Immutable;
                    newTable.TypedTable         = (nHydrate.Generator.Models.TypedTableConstants)Enum.Parse(typeof(nHydrate.Generator.Models.TypedTableConstants), entity.TypedEntity.ToString(), true);
                    newTable.Name = entity.Name;
                    newTable.GeneratesDoubleDerived = entity.GeneratesDoubleDerived;
                    newTable.IsTenant = entity.IsTenant;
                    #endregion

                    #region Load the fields for this entity
                    var fieldList = entity.Fields.ToList();
                    foreach (var field in fieldList.OrderBy(x => x.SortOrder))
                    {
                        var newColumn = root.Database.Columns.Add();
                        newColumn.ResetKey(field.Id.ToString());
                        newColumn.ResetId(HashString(newColumn.Key));
                        newColumn.AllowNull      = field.Nullable;
                        newColumn.CodeFacade     = field.CodeFacade;
                        newColumn.ComputedColumn = field.IsCalculated;
                        newColumn.DataType       = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), field.DataType.ToString());
                        newColumn.Default        = field.Default;
                        newColumn.DefaultIsFunc  = field.DefaultIsFunc;
                        newColumn.Description    = field.Summary;
                        newColumn.Formula        = field.Formula;
                        newColumn.Identity       = (nHydrate.Generator.Models.IdentityTypeConstants)Enum.Parse(typeof(nHydrate.Generator.Models.IdentityTypeConstants), field.Identity.ToString());
                        newColumn.IsIndexed      = field.IsIndexed;
                        newColumn.IsReadOnly     = field.IsReadOnly;
                        newColumn.IsUnique       = field.IsUnique;
                        newColumn.Length         = field.Length;
                        newColumn.Name           = field.Name;
                        newColumn.ParentTableRef = newTable.CreateRef(newTable.Key);
                        newColumn.PrimaryKey     = field.IsPrimaryKey;
                        newColumn.Scale          = field.Scale;
                        newColumn.SortOrder      = field.SortOrder;
                        newColumn.Obsolete       = field.Obsolete;
                        newTable.Columns.Add(newColumn.CreateRef(newColumn.Key));
                    }
                    #endregion

                    #region Indexes

                    var indexList = entity.Indexes.ToList();
                    foreach (var index in indexList)
                    {
                        var indexColumns = index.IndexColumns.Where(x => x.GetField() != null).ToList();
                        if (indexColumns.Count > 0)
                        {
                            var newIndex = new nHydrate.Generator.Models.TableIndex(newTable.Root)
                            {
                                Description = index.Summary,
                                IsUnique    = index.IsUnique,
                                Clustered   = index.Clustered,
                                PrimaryKey  = (index.IndexType == IndexTypeConstants.PrimaryKey)
                            };
                            newTable.TableIndexList.Add(newIndex);
                            newIndex.ResetKey(index.Id.ToString());
                            newIndex.ResetId(HashString(newIndex.Key));
                            newIndex.ImportedName = index.ImportedName;

                            //Add index columns
                            foreach (var ic in indexColumns.OrderBy(x => x.SortOrder).ThenBy(x => x.GetField().Name))
                            {
                                var field     = ic.GetField();
                                var newColumn = new nHydrate.Generator.Models.TableIndexColumn(newTable.Root)
                                {
                                    Ascending = ic.Ascending, FieldID = field.Id
                                };
                                newIndex.IndexColumnList.Add(newColumn);
                            }
                        }
                    }

                    #endregion

                    #region Static Data
                    //Determine how many rows there are
                    var orderKeyList = entity.StaticDatum.Select(x => x.OrderKey).Distinct().ToList();
                    var rowCount     = orderKeyList.Count;

                    //Create a OLD static data row for each one
                    for (var ii = 0; ii < rowCount; ii++)
                    {
                        //For each row create N cells one for each column
                        var rowEntry            = new nHydrate.Generator.Models.RowEntry(newTable.Root);
                        var staticDataFieldList = fieldList.Where(x => !x.DataType.IsBinaryType() && x.DataType != DataTypeConstants.Timestamp).ToList();
                        for (var jj = 0; jj < staticDataFieldList.Count; jj++)
                        {
                            var cellEntry = new nHydrate.Generator.Models.CellEntry(newTable.Root);
                            var column    = newTable.GetColumns().ToList()[jj];
                            cellEntry.ColumnRef = column.CreateRef(column.Key);

                            var currentColumn = fieldList.FirstOrDefault(x => x.Id == new Guid(column.Key));
                            if (currentColumn != null)
                            {
                                var dataum = entity.StaticDatum.FirstOrDefault(x =>
                                                                               x.ColumnKey == currentColumn.Id &&
                                                                               x.OrderKey == orderKeyList[ii]);

                                if (dataum != null)
                                {
                                    cellEntry.Value = dataum.Value;
                                    cellEntry.ResetKey(dataum.Id.ToString());
                                }

                                //Add the cell to the row
                                rowEntry.CellEntries.Add(cellEntry);
                            }
                        }
                        newTable.StaticData.Add(rowEntry);
                    }
                    #endregion
                }

                #endregion

                #region Relations
                {
                    var relationConnectors = diagram.NestedChildShapes.Where(x => x is EntityAssociationConnector).Cast <EntityAssociationConnector>().ToList();
                    foreach (var shape in relationConnectors)
                    {
                        if (shape is EntityAssociationConnector)
                        {
                            var connector = shape as EntityAssociationConnector;
                            var parent    = connector.FromShape.ModelElement as Entity;
                            var child     = connector.ToShape.ModelElement as Entity;

                            var relation  = connector.ModelElement as EntityHasEntities;
                            var fieldList = model.RelationFields.Where(x => x.RelationID == relation.Id);

                            var parentTable = root.Database.Tables.FirstOrDefault(x => x.Name == parent.Name);
                            var childTable  = root.Database.Tables.FirstOrDefault(x => x.Name == child.Name);

                            //If we found both parent and child tables...
                            if (parentTable != null && childTable != null && !childTable.IsInheritedFrom(parentTable))
                            {
                                var isValidRelation = true;
                                if (isValidRelation)
                                {
                                    var newRelation = root.Database.Relations.Add();
                                    newRelation.ResetKey((connector.ModelElement as nHydrate.Dsl.EntityHasEntities).InternalId.ToString());
                                    newRelation.ResetId(HashString(newRelation.Key));
                                    newRelation.ParentTableRef = parentTable.CreateRef(parentTable.Key);
                                    newRelation.ChildTableRef  = childTable.CreateRef(childTable.Key);
                                    newRelation.RoleName       = ((EntityHasEntities)connector.ModelElement).RoleName;
                                    switch (relation.DeleteAction)
                                    {
                                    case DeleteActionConstants.Cascade:
                                        newRelation.DeleteAction = Relation.DeleteActionConstants.Cascade;
                                        break;

                                    case DeleteActionConstants.NoAction:
                                        newRelation.DeleteAction = Relation.DeleteActionConstants.NoAction;
                                        break;

                                    case DeleteActionConstants.SetNull:
                                        newRelation.DeleteAction = Relation.DeleteActionConstants.SetNull;
                                        break;
                                    }

                                    newRelation.Enforce = relation.IsEnforced;

                                    //Create the column links
                                    foreach (var columnSet in fieldList)
                                    {
                                        var field1 = parent.Fields.FirstOrDefault(x => x.Id == columnSet.SourceFieldId);
                                        var field2 = child.Fields.FirstOrDefault(x => x.Id == columnSet.TargetFieldId);

                                        var column1 = parentTable.GetColumnsFullHierarchy().FirstOrDefault(x => x.Name == field1.Name);
                                        var column2 = childTable.GetColumnsFullHierarchy().FirstOrDefault(x => x.Name == field2.Name);

                                        newRelation.ColumnRelationships.Add(new nHydrate.Generator.Models.ColumnRelationship(root)
                                        {
                                            ParentColumnRef = column1.CreateRef(column1.Key),
                                            ChildColumnRef  = column2.CreateRef(column2.Key),
                                        }
                                                                            );
                                    }

                                    //Actually add the relation to the collection
                                    if (newRelation.ColumnRelationships.Count > 0)
                                    {
                                        parentTable.Relationships.Add(newRelation.CreateRef(newRelation.Key));
                                    }
                                }
                            }
                        }
                    }
                } //inner block

                #endregion

                #region Views
                foreach (var view in model.Views)
                {
                    var newView = root.Database.CustomViews.Add();
                    newView.ResetKey(view.Id.ToString());
                    newView.ResetId(HashString(newView.Key));
                    newView.CodeFacade             = view.CodeFacade;
                    newView.DBSchema               = view.Schema;
                    newView.Description            = view.Summary;
                    newView.Name                   = view.Name;
                    newView.SQL                    = view.SQL;
                    newView.GeneratesDoubleDerived = view.GeneratesDoubleDerived;

                    foreach (var field in view.Fields)
                    {
                        var newField = root.Database.CustomViewColumns.Add();
                        newField.ResetKey(field.Id.ToString());
                        newField.ResetId(HashString(newField.Key));
                        newField.AllowNull    = field.Nullable;
                        newField.CodeFacade   = field.CodeFacade;
                        newField.DataType     = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), field.DataType.ToString());
                        newField.Default      = field.Default;
                        newField.Description  = field.Summary;
                        newField.IsPrimaryKey = field.IsPrimaryKey;
                        newField.Length       = field.Length;
                        newField.Name         = field.Name;
                        newField.Scale        = field.Scale;
                        newView.Columns.Add(newField.CreateRef(newField.Key));
                        newField.ParentViewRef = newView.CreateRef(newView.Key);
                    }
                }
                #endregion

                return(root);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #41
0
        public static bool Validate(nHydrateDocData docData, Microsoft.VisualStudio.Modeling.Store store, nHydrateModel model)
        {
            var key = ProgressHelper.ProgressingStarted("Verifying Model...");

            try
            {
                var validationController = docData.ValidationController;
                validationController.Validate(model.Entities, Microsoft.VisualStudio.Modeling.Validation.ValidationCategories.Custom);
                return(validationController.Validate(store, Microsoft.VisualStudio.Modeling.Validation.ValidationCategories.Custom |
                                                     Microsoft.VisualStudio.Modeling.Validation.ValidationCategories.Load |
                                                     Microsoft.VisualStudio.Modeling.Validation.ValidationCategories.Menu |
                                                     Microsoft.VisualStudio.Modeling.Validation.ValidationCategories.Open |
                                                     Microsoft.VisualStudio.Modeling.Validation.ValidationCategories.Save));
            }
            catch (Exception ex)
            {
                ProgressHelper.ProgressingComplete(key);
                throw;
            }
            finally
            {
                ProgressHelper.ProgressingComplete(key);
            }
        }