public ActionResult EditChapterDetails(Chapter chap, string selectedSemester, string selectedDepartment,
                                               string selectedUnit)
        {
            var dbChapter = _context.Chapters.FirstOrDefault(u => u.Id == chap.Id);

            var semesterId = DatabaseData.GetSemesterInfo(selectedSemester).Id;

            var departmentId = DatabaseData.GetDepartmentInfo(selectedDepartment).Id;

            chap.DepartmentId = departmentId;
            chap.SemesterId   = semesterId;
            chap.UnitNo       = Convert.ToInt32(selectedUnit);

            dbChapter.ChapterName  = chap.ChapterName;
            dbChapter.DepartmentId = chap.DepartmentId;
            dbChapter.SemesterId   = chap.SemesterId;
            dbChapter.UnitNo       = chap.UnitNo;
            dbChapter.ChapterNo    = chap.ChapterNo;
            _context.SaveChangesAsync();


            TempData["ChapterDetailsEditedSuccessfully"] = "Chapter details edited successfully";

            return(RedirectToAction("ViewChapters"));
        }
Ejemplo n.º 2
0
 public void RemoveDatabase(DatabaseData databaseData)
 {
     if (model.RemoveDatabase(databaseData))
     {
         TreeForm.RemoveDatabaseDefinition(databaseData.Definition.Path);
     }
 }
        public IPwmDbContext Create()
        {
            DatabaseData config = configuration
                                  .SetPath()
                                  .Create()
                                  .Load();


            var contextOptions = new DbContextOptionsBuilder <Context>();

            switch (config.Type)
            {
            case DataBaseType.Mssql:
                var connectionStringSql = sqlConnectionStringBuilder.Create();
                contextOptions.UseSqlServer(connectionStringSql);
                break;

            case DataBaseType.SqLite:
                var connectionStringSqLite = sqLiteConnectionStringBuilder.Create();
                contextOptions.UseSqlite(connectionStringSqLite);
                break;

            case DataBaseType.AccessDatabase:

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var context = new Context(contextOptions.Options);

            return(new PwmDbContext(context));
        }
Ejemplo n.º 4
0
 public void BroadcastReturnDataFromDatabase(DatabaseData databaseData)
 {
     if (OnReturnDataFromDatabase != null)
     {
         OnReturnDataFromDatabase(databaseData);
     }
 }
Ejemplo n.º 5
0
        public void StartEditDatabase(DatabaseData srcDatabaseData)
        {
            DatabaseData dstDatabaseData = model.SetDatabaseAsEdit(srcDatabaseData);

            TreeForm.SetDatabaseDefinition(dstDatabaseData);
            TreeForm.SetEditMode(true);
        }
        private void SaveActualDataOfDatabase()
        {
            DatabaseData db             = ImportExportEngine.TableToFile();
            ImportExportFileGenerator f = new ImportExportFileGenerator(db);

            f.Generate();
        }
Ejemplo n.º 7
0
        private void rrdDbTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //importDataToolStripMenuItem1.Enabled = false;
            //editToolStripMenuItem1.Enabled = false;
            object           selectedObject;
            SelectedNodeType selectedNodeType = GetSelectedNodeObject(e.Node, out selectedObject);

            switch (selectedNodeType)
            {
            case SelectedNodeType.database:
                controller.DatabaseSelected((DatabaseData)selectedObject);
                return;

            case SelectedNodeType.datasources:
                controller.DatasourcesSelected((DatabaseData)selectedObject);
                return;

            case SelectedNodeType.archives:
                selectedObject = e.Node.Parent.Tag;
                controller.ArchivesSelected(selectedObject as DatabaseData);
                return;

            case SelectedNodeType.datasource:
                return;

            case SelectedNodeType.datasourcearchive:
                Application.UseWaitCursor = true;
                DatabaseData databaseData = e.Node.Parent.Parent.Parent.Tag as DatabaseData;
                controller.DatasourceArchiveSelected(databaseData, e.Node.Parent.Tag, e.Node.Tag);
                Application.UseWaitCursor = false;
                return;
            }
        }
Ejemplo n.º 8
0
        public void DatabaseCreated()
        {
            DatabaseData databaseData = model.GetDatabasedata();

            TreeForm.SetDatabaseDefinition(databaseData);
            TreeForm.SetEditMode(true);
            rrdDbForm.SetDatabaseDefinition(databaseData);
        }
Ejemplo n.º 9
0
 public bool DatabaseUnsaved(DatabaseData databaseData)
 {
     if (model.EditingDatabaseData == null)
     {
         return(false);
     }
     return(databaseData.Definition.Path == model.EditingDatabaseData.Definition.Path);
 }
Ejemplo n.º 10
0
        public ActionResult QuestionFileUpload(string selectedFileType, HttpPostedFileBase fileControl,
                                               string selectedSemester, string selectedDepartment, string selectedSubject, string selectedUnit,
                                               string ExamType, string chapterName)
        {
            var extension = Path.GetExtension(fileControl.FileName);

            var subjectId = _context.Courses.FirstOrDefault(u => u.CourseName == selectedSubject)?.Courseid;

            var departmentId = DatabaseData.GetDepartmentInfo(selectedDepartment)?.Id;

            var semesterId = DatabaseData.GetSemesterInfo(selectedSemester)?.Id;

            var unit = Convert.ToInt32(selectedUnit);

            var type = (int)Enum.Parse(typeof(ExamType), ExamType);

            var chapterId = _context.Chapters.FirstOrDefault(x =>
                                                             x.SemesterId == semesterId && x.DepartmentId == departmentId && x.CourseId == subjectId &&
                                                             x.UnitNo == unit && x.ChapterName == chapterName)?.Id;

            // Word file
            if (extension == ".docx" || extension == ".doc")
            {
                ProcessFile.WordFile(fileControl);
            }

            // CSV file
            else if (extension == ".csv" || extension == ".CSV")
            {
                var data = ProcessFile.CsvFile(fileControl);
                if (data.questions == null)
                {
                    TempData["UploadError"] = data.error;
                    return(View("Index"));
                }

                foreach (var q in data.questions)
                {
                    _context.Questions.Add(new Question
                    {
                        ChapterId       = chapterId,
                        CourseId        = subjectId,
                        DepartmentId    = Convert.ToString(departmentId),
                        DifficultyLevel = q.Level,
                        QuestionText    = q.Question,
                        QuestionType    = type,
                        SemesterId      = Convert.ToString(semesterId),
                        UnitId          = unit
                    });
                }
                _context.SaveChangesAsync();

                Alert("Success", "Question set added successfully", Enums.NotificationType.success);

                return(RedirectToAction("Index", "Question"));
            }
            return(null);
        }
Ejemplo n.º 11
0
        public bool OpenDatabase(string databasePath)
        {
            DatabaseData databaseData = model.AddDatabase(databasePath);

            TreeForm.SetDatabaseDefinition(databaseData);
            rrdDbForm.SetDatabaseDefinition(databaseData);
            TreeForm.SetEditMode(false);
            return(true);
        }
        public DatabaseSettingsViewModel(ISettingService <DatabaseData> settings)
        {
            this.settings = settings;
            DatabaseData data = this.settings.Load().Result;

            DatabaseName       = data.DatabaseName;
            ServerName         = data.ServerName;
            Password           = data.Password;
            Username           = data.Username;
            IntegratedSecurity = data.IntegratedSecurity;
        }
 public bool AddListObjectEntry(PurchaseEntry inObject)
 {
     try
     {
         DatabaseData.AddListObjectEntry(inObject);
         return(true);
     }
     catch (Exception exc)
     {
         return(false);
     }
 }
Ejemplo n.º 14
0
        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            object           nodeData;
            SelectedNodeType nodeType = GetSelectedNodeObject(out nodeData);

            if (nodeType != SelectedNodeType.database)
            {
                return;
            }

            DatabaseData databaseData = nodeData as DatabaseData;
        }
 public bool UpdateListObjectEntryAtId(PurchaseEntry inObject)
 {
     try
     {
         DatabaseData.UpdateListObjectEntryAtId(inObject);
         return(true);
     }
     catch (Exception exc)
     {
         return(false);
     }
 }
Ejemplo n.º 16
0
		public DatabaseData Parse(IList<Table> tables, string excludedTablesRegex)
		{
			var tableDataList = new List<TableData>();
			foreach (var table in tables)
			{
				tableDataList.Add(Parse(table, excludedTablesRegex));
			}
			var ret = new DatabaseData
			{
				Tables = tableDataList
			};
			return ret;
		}
Ejemplo n.º 17
0
        public void DatasourceArchiveSelected(DatabaseData database, object datasource, object archiveDefinition)
        {
            if (!model.IsDatabase(database.Definition.Path))
            {
                return;
            }
            DsDef dsDef = datasource as DsDef;

            ArcDef    selectedArchive = archiveDefinition as ArcDef;
            FetchData fetchedData     = model.GetArchiveData(database, dsDef.DsName, selectedArchive);

            rrdDbForm.SetArchiveDumpData(fetchedData);
            rrdDbForm.SetDocumentName(Path.GetFileNameWithoutExtension(database.Definition.getPath()));
        }
Ejemplo n.º 18
0
        private static DatabaseData GetDB()
        {
            if (!File.Exists(dbPath))
            {
                // Create a file to write to.
                string createText = File.ReadAllText(emptyDBPath);
                File.WriteAllText(dbPath, createText);
            }

            string       readText = File.ReadAllText(dbPath);
            DatabaseData dbData   = JsonConvert.DeserializeObject <DatabaseData>(readText);

            return(dbData);
        }
        public DatabaseData TableToFile()
        {
            DatabaseData databaseData = new DatabaseData();

            databaseData.ieContraints   = importExportCon.ExportConstraints();
            databaseData.ieconstraintts = importExportCon.ExportConstraintt();
            databaseData.iecourse       = importExportCon.ExportCourse();
            databaseData.iecurricula    = importExportCon.ExportCurricula();
            databaseData.iecurriculum   = importExportCon.ExportCurriculum();
            databaseData.ieroom         = importExportCon.ExportRoom();
            databaseData.ieteacher      = importExportCon.ExportTeacher();

            return(databaseData);
        }
Ejemplo n.º 20
0
        public void ImportData(string dataPath, DatabaseData databaseData, TimeSpan expectedTick)
        {
            if (model.ReadOnly)
            {
                throw new ApplicationException("Can't import data. Database readonly");
            }


            List <string>      columns     = new List <string>();
            List <FetchedData> unifiedData = ReadAndUnifyData(dataPath, out columns);

            string databasePath = databaseData.Definition.Path;
            RrdDb  database     = new RrdDb(databasePath, false);

            int[] dsIndexes = new int[columns.Count];
            for (int i = 0; i < columns.Count; i++)
            {
                dsIndexes[i] = database.getDsIndex(columns[i]);
            }


            string[] dsNames = database.getDsNames();
            rrd4n.DataAccess.Data.Sample sample = new rrd4n.DataAccess.Data.Sample(databasePath, dsNames, 0);

            foreach (var data in unifiedData)
            {
                sample.setDateTime(data.TimeStamp);
                for (int i = 0; i < data.Values.Count; i++)
                {
                    sample.setValue(dsIndexes[i], data.Values[i]);
                }

                try
                {
                    // When using file access abstraction
                    //dbAccess.StoreData(sample);

                    //Without abstraction
                    database.store(sample);
                    sample.clearValues();
                }
                catch (ArgumentException)
                {
                }
                model.DatabaseDirty = true;
            }
            database.close();
            OpenDatabase(databasePath);
        }
Ejemplo n.º 21
0
        public void DatabaseUpdated(DatabaseData srcDatabaseData)
        {
            DatabaseData reloadedData;

            if (srcDatabaseData != null)
            {
                reloadedData = model.ReloadDatabase(srcDatabaseData);
            }
            else
            {
                reloadedData = model.EditingDatabaseData;
            }
            rrdDbForm.SetDatabaseDefinition(reloadedData);
            TreeForm.SetDatabaseDefinition(reloadedData);
        }
        public ActionResult GetChapterList(string semester, string department, string subject, string unit)
        {
            var semesterId = DatabaseData.GetSemesterInfo(semester)?.Id;

            var departmentId = DatabaseData.GetDepartmentInfo(department)?.Id;

            var subjectId = DatabaseData.GetCourseInfo(subject)?.Courseid;

            var unitInt = Convert.ToInt32(unit);

            var chapters = _context.Chapters
                           .Where(x => x.SemesterId == semesterId && x.DepartmentId == departmentId && x.CourseId == subjectId &&
                                  x.UnitNo == unitInt).Select(x => x.ChapterName).ToList();

            return(Json(chapters, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 23
0
        public SetupTestData()
        {
            _ctx = new ProjectContext();
            var dd = new DatabaseData
            {
                KeywordName          = "Key Word 01",
                ProjectLocation      = "Project Location 01",
                ProjectName          = "Project Name 01",
                ReferenceDescription = "Ref Description 01",
                ReferenceUrl         = "Ref URL 01",
                SolutionLocation     = "Solution Location 01",
                SolutionName         = "Solution Name 01"
            };

            InsertNewData(dd);
        }
Ejemplo n.º 24
0
        private void importDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            object nodeData;

            SelectedNodeType nodeType = GetSelectedNodeObject(out nodeData);

            //if (nodeType == SelectedNodeType.datasource)
            //{
            //   DataSourceController dsController = kernel[typeof(DataSourceController)] as DataSourceController;
            //   dsController.DataSourceDef = nodeData as DsDef;
            //   DatabaseData srcDatabaseData = GetSrcDatabase();
            //   dsController.SrcDatabase = srcDatabaseData;
            //   if (dsController.Run())
            //      controller.DatabaseUpdated(srcDatabaseData);
            //   return;

            //}
            //if (nodeType == SelectedNodeType.datasourcearchive)
            //{
            //   ArchiveController archController = kernel[typeof(ArchiveController)] as ArchiveController;
            //   archController.ArchiveDef = nodeData as ArcDef;
            //   if (archController.Run())
            //      controller.DatabaseUpdated(GetSrcDatabase());
            //   return;
            //}

            if (nodeType == SelectedNodeType.database)
            {
                openFileDialog1.DefaultExt = "csv";
                openFileDialog1.FileName   = "*.csv";
                //            openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (openFileDialog1.ShowDialog(this) == DialogResult.Cancel)
                {
                    return;
                }

                try
                {
                    DatabaseData dd = nodeData as DatabaseData;
                    controller.ImportData(openFileDialog1.FileName, dd, new TimeSpan(7, 0, 0, 0));
                }
                catch (ApplicationException ex)
                {
                    MessageBox.Show("Fail to import data." + ex.Message);
                }
            }
        }
Ejemplo n.º 25
0
        public ActionResult GetDetails(string selectedSemester, string selectedStaff, string selectedDepartment,
                                       string selectedSubject)
        {
            if (string.IsNullOrEmpty(selectedSemester) || string.IsNullOrEmpty(selectedStaff) ||
                string.IsNullOrEmpty(selectedDepartment) || selectedSubject.Contains("---Select---"))
            {
                TempData["AllocatedErrorMessage"] = "Please fill all of the fields";

                return(RedirectToAction("Index"));
            }

            var staffId = 0;

            // Get a selected Semester Id
            var semesterId = DatabaseData.GetSemesterInfo(selectedSemester).Id;

            // Get a selected staff Id
            var staff = _context.Staffs.FirstOrDefault(u => u.Name == selectedStaff);

            if (staff != null)
            {
                staffId = staff.Id;
            }

            // Get a selected department Id
            var departmentId = DatabaseData.GetDepartmentInfo(selectedDepartment).Id;

            // Get a selected subject id
            var subjectId = DatabaseData.GetCourseInfo(selectedSubject).Courseid;


            var newAllocatedCourse = new StaffCourse
            {
                CourseId     = subjectId,
                SemesterId   = semesterId,
                StaffId      = staffId,
                DepartmentId = departmentId
            };

            _context.StaffCourses.Add(newAllocatedCourse);
            _context.SaveChanges();

            TempData["AllocatedSuccessMessage"] = "Subject allocated to staff successfully";

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 26
0
        //OptionsClick
        //This is the event handler for clicking on the Options item under the tools menu
        //It will change basic options such as the background image, Database Filepath
        //Woot!! Jeremy was here!!
        protected void OptionsClick(object who, EventArgs e)
        {
            OptionsForm OpF;

            if (Db == null)
            {
                OpF = new OptionsForm(bgcolor, BackgroundFile);
            }
            else
            {
                OpF = new OptionsForm(bgcolor, BackgroundFile, Db.Connection.filepath);
            }
            if (OpF.ShowDialog() == DialogResult.OK)
            {
                if (!OpF.isImage)
                {
                    drawspace.BackgroundImage = null;
                    bgcolor             = OpF.BGColor;
                    drawspace.BackColor = bgcolor;
                }
                else
                {
                    drawspace.BackgroundImageLayout = ImageLayout.Stretch;
                    if (OpF.imageFilePath.Contains(".bmp"))
                    {
                        BackgroundFile = OpF.imageFilePath;
                        //drawspace.Size = new Bitmap(BackgroundFile);
                        drawspace.BackgroundImage = new Bitmap(BackgroundFile);
                        drawspace.Size            = drawspace.BackgroundImage.Size;
                        zoom = 1;
                    }
                }
                if (OpF.isDataBase && Db == null)
                {
                    Db = new DatabaseData(OpF.dbFilePath);
                    if (OpF.F2.isPassword)
                    {
                        Db.Connection.Passwrd = OpF.F2.Password;
                    }
                    Db.Connection.SetConnection();
                }
            }
            OpF.Dispose();
            //MessageBox.Show("Data base is made? FilePath = " + Db.Connection.filepath);
        }
Ejemplo n.º 27
0
        private void LoadTree(DatabaseData databaseData)
        {
            RrdDef   databaseDefinition = databaseData.Definition;
            string   databaseName       = Path.GetFileNameWithoutExtension(databaseDefinition.Path);
            TreeNode databaseNode;

            TreeNode[] databaseNodes = rrdDbTreeView.Nodes.Find(databaseDefinition.Path, true);
            if (databaseNodes.Length == 0)
            {
                databaseNode = rrdDbTreeView.Nodes.Add(databaseDefinition.Path, databaseName);
                if (!databaseData.Saved)
                {
                    databaseNode.Text += "*";
                }
            }
            else
            {
                databaseNode = databaseNodes[0];
                if (!databaseData.Saved &&
                    !databaseNode.Text.Contains("*"))
                {
                    databaseNode.Text += "*";
                }
            }


            databaseNode.Tag = databaseData;

            databaseNode.Nodes.Clear();
            var datasources = databaseNode.Nodes.Add(dataSourceNodesName, dataSourceNodesName);

            foreach (var datasource in databaseDefinition.getDsDefs())
            {
                TreeNode datasourceNode = datasources.Nodes.Add(datasource.DsName);
                datasourceNode.Tag = datasource;
                foreach (var arcDef in databaseDefinition.getArcDefs())
                {
                    string nodeText = string.Format("RRA:{0}:{1}:{2}:{3}", arcDef.getConsolFun().Name,
                                                    arcDef.Xff, arcDef.Steps, arcDef.Rows);
                    var archiveNode = datasourceNode.Nodes.Add(nodeText);
                    archiveNode.Tag = arcDef;
                }
            }
            databaseNode.Nodes.Add(archiveNodesName, archiveNodesName);
        }
Ejemplo n.º 28
0
        private void Initialize()
        {
            if (IsInMemoryDatabase)
            {
                this.data = new DatabaseData(new MemoryStream());
            }
            else
            {
                this.data = new DatabaseData(new FileStream(FileName, FileMode.OpenOrCreate));
            }

            if (this.data.IsNew())
            {
                this.data.WriteToDb(new HeaderPage());
            }

            KV = new KeyValueStore(this.data);
        }
Ejemplo n.º 29
0
        private void graphCommandTextBox_DragDrop(object sender, DragEventArgs e)
        {
            DatabaseData  rrdDef = (DatabaseData)e.Data.GetData(typeof(DatabaseData));
            StringBuilder sb     = new StringBuilder();

            sb.AppendLine("-");
            sb.AppendLine("-w 790");
            sb.AppendLine("-h 260");
            sb.AppendLine("--imgformat PNG");
            foreach (var ds in rrdDef.Definition.getDsDefs())
            {
                sb.AppendFormat(string.Format("DEF:{0}_v={1}:{2}:AVERAGE", ds.getDsName(), Path.GetFileName(rrdDef.Definition.Path), ds.getDsName()));
                sb.AppendLine();
                sb.AppendFormat("LINE2:{0}_v#FF0000", ds.getDsName());
            }

            graphCommandTextBox.Text = sb.ToString();
        }
Ejemplo n.º 30
0
        public void UpdateDatabase(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                using (var _context = serviceScope.ServiceProvider.GetService <VogCodeChallengeDbContext>())
                {
                    if (Configuration.GetValue <bool>("DB_MIGRATE") == true)
                    {
                        _context.Database.Migrate();
                    }

                    if (Configuration.GetValue <bool>("DB_INITIALIZE") == true)
                    {
                        DatabaseData.Initialize(_context);
                    }
                }
            }
        }
Ejemplo n.º 31
0
        public void ArchivesSelected(DatabaseData databaseData)
        {
            List <ArchiveDisplayData> archives = new List <ArchiveDisplayData>();

            foreach (ArcDef arcDef in databaseData.Definition.getArcDefs())
            {
                archives.Add(new ArchiveDisplayData()
                {
                    ConsolFunctionName = arcDef.getConsolFun().Name,
                    RowCount           = arcDef.getRows(),
                    Steps     = arcDef.getSteps(),
                    Xff       = arcDef.getXff(),
                    StartTime = DateTime.MinValue,
                    EndTime   = DateTime.MaxValue
                });
            }
            rrdDbForm.SetArchiveData(archives.ToArray());
        }
Ejemplo n.º 32
0
		internal void Generate()
		{
			_surfaceDataList = new List<ClassData>();

			var xmlRdbSchemaPathfile = Path.Combine(
				//@"C:\DATA\PROJEKT\St4mpede\St4mpede\St4mpede",
				_coreSettings.RootFolder,
				//	\RdbSchema",
				_rdbSchemaSettings.ProjectPath,
				//St4mpede.RdbSchema.xml";
				_rdbSchemaSettings.DatabaseXmlFile);

			IParserLogic2 parserLogic2 = new ParserLogic2();

			_log.Add("Reading xml {0}.", xmlRdbSchemaPathfile);

			_database = parserLogic2.GetResult(xmlRdbSchemaPathfile);

			_database.Tables.ForEach(table =>
			{
			//	Set data for the very [class].
			var surfaceClass = new ClassData
			{
				Name = $"{table.Name}Surface",
				Comment = new CommentData($"This is the Surface for the {table.Name} table."),
				IsPartial = false,
				Properties = new List<PropertyData>(),
				Methods = new List<MethodData>()
			};
			_surfaceDataList.Add(surfaceClass);

			//	#	Create the properties.
			//	Well... we don't have any properties.

			//	#	Create the constructor.
			var constructorMethod = new MethodData
			{
				IsConstructor = true,
				Name = surfaceClass.Name
			};
			surfaceClass.Methods.Add(constructorMethod);

				//	#	Create the methods.
				//	##	Create the Add method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "Add",
					Comment = new CommentData( new[] {
						"This method is used for adding a new record in the database.",
						"<para>St4mpede guid:{BC89740A-CBA5-4EDE-BFF4-9B0D8BA4058F}</para>"}),
					Scope = Common.VisibilityScope.Private,
					ReturnTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
					Parameters = new[] {
							new ParameterData
							{
								Name = "context",
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							}
						}
						.Concat(
								table.NonPrimaryKeyColumns
									.Select(p =>
										new ParameterData
									   {
										   Name = p.Name,
										   SystemTypeString = parserLogic2.ConvertDatabaseTypeToDotnetTypeString(p.DatabaseTypeName)
									   }))
						.ToList(),
					Body = new BodyData(new[]
					{
						$"return Add( ",
						"\tcontext, ",
						$"	new TheDAL.Poco.{table.Name}(", //	TODO:OF:Fetch namespace from Poco project.
						//	TODO:OF:We should set default value and not 0 to the primary keys.
						"\t\t" + string.Join(", ", table.PrimaryKeyColumns.Select(c=>"0")) + ", ",
						"\t\t" + string.Join(", ", table.NonPrimaryKeyColumns.Select(c=>c.Name.ToCamelCase()).ToList()),
						"));"
					})
				});

		//	##	Create the Add method.
		surfaceClass.Methods.Add(new MethodData
				{
					Name = "Add",
					Comment = new CommentData(new[] {
						"This method is used for adding a new record in the database.",
						"<para>St4mpede guid:{759FBA46-A462-4E4A-BA2B-9B5AFDA572DE}</para>"}),
					Scope = Common.VisibilityScope.Private,
					ReturnTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
					Parameters =
							new[] { new ParameterData
							{
								Name="context", 
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							} }
						.Concat(
							new[] {	new ParameterData
							   {
								   Name = table.Name,	//	TODO:OF:Make camelcase.
								   SystemTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
								}
							})
						.ToList(),
					Body = new BodyData(new[]
					{
						$"const string Sql = @" + "\"",
						$"	Insert Into {table.Name}",
						$"	(",
						$"		{string.Join(", ",table.Columns.Where(c=>false==c.IsInPrimaryKey).Select(c=>c.Name))}",
						$"	)",
						$"	Values",
						$"	(",
						//	TODO:OF:Make lowercase.
						$"		{string.Join(", ",table.Columns.Where(c=>false==c.IsInPrimaryKey).Select(c=>"@" + c.Name))}",
						$"	)",
						$"	Select * From {table.Name} Where {table.Columns.Single(c=>c.IsInPrimaryKey).Name} = Scope_Identity()" + "\";",
						$"var ret = context.Connection.Query<TheDAL.Poco.{table.Name}>(", //	TODO:OF:Fetch namespace from Poco project.
						"	Sql, ",
						"	new {",
						$"	{string.Join(", ", table.Columns.Where(c=>c.IsInPrimaryKey).Select(c=> "\t" + c.Name.ToCamelCase() + " = " + table.Name.ToCamelCase() + "." + c.Name  ))}",
						"	},",
						"	context.Transaction,", 
						"	false, null, null);", 
						"return ret.Single();",
					})
				});

				//	##	Create the Delete method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "Delete",
					Comment = new CommentData(new[] {
						"This method is used for deleting a record.",
						"<para>St4mpede guid:{F74246AE-0295-4094-AA7F-1D118C11229D}</para>"
						}),
					Scope = Common.VisibilityScope.Public,
					ReturnTypeString = $"void",
					Parameters =
							new[] { new ParameterData
							{
								Name="context",
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							} }
						.Concat(
							new [] { new ParameterData
							   {
								   Name = table.Name,
								   SystemTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
							   }
					}).ToList(),
					Body = new BodyData(new[]
					{
						"DeleteById( context, " +
						string.Join(", ", table.PrimaryKeyColumns.Select(c=>
						$"{table.Name.ToCamelCase()}.{c.Name}")) + ");"
					})
				});

				//	##	Create the DeleteById method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "DeleteById",
					Comment = new CommentData(new[] {
						"This method is used for deleting a record by its primary key.",
						"<para>St4mpede guid:{F0137E62-1D45-4B92-A48E-05954850FFE8}</para>"
						}),
					Scope = Common.VisibilityScope.Public,
					ReturnTypeString = $"void",
					Parameters =
							new[] { new ParameterData
							{
								Name="context",
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							} }
						.Concat(
							table.PrimaryKeyColumns
								.Select(p =>
								   new ParameterData
								   {
									   Name = p.Name,
									   SystemTypeString = parserLogic2.ConvertDatabaseTypeToDotnetTypeString(p.DatabaseTypeName)
								   }))
						.ToList(),
					Body = new BodyData(new[]
						{
							$"const string Sql = @" + "\"",
							$"	Delete From {table.Name}",
							"\t Where " + string.Join(" And ", table.PrimaryKeyColumns.Select(c=>$"{c.Name} = @{c.Name.ToCamelCase()}")),
							"\";",
							$"context.Connection.Execute(",
							"	Sql, ",
							"	new {",
							$"	{string.Join(", ", table.Columns.Where(c=>c.IsInPrimaryKey).Select(c=> "\t" +$"{c.Name.ToCamelCase()} = {c.Name.ToCamelCase()}"  ))}",
							"	},",
							"	context.Transaction,",
							"	null, null);",
						})
				});

				//	##	Create the GetAll method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "GetAll",
					Comment = new CommentData(new[] {
						"This method returns every record for this table/surface.",
						"Do not use it on too big tables.",
						"<para>St4mpede guid:{4A910A99-9A50-4977-B2A2-404240CDDC73}</para>"
						}),
					Scope = Common.VisibilityScope.Public,
					ReturnTypeString = $"IList<TheDAL.Poco.{table.Name}>", //	TODO:OF:Fetch namespace from Poco project.
					Parameters =
						new[] { new ParameterData
							{
								Name="context",
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							} }.ToList(),
					Body = new BodyData(new[]
						{
							$"const string Sql = @" + "\"",
							$"	Select * From {table.Name}",
							"\";",
							$"var res = context.Connection.Query<TheDAL.Poco.{table.Name}>(",	//	TODO:OF:Fetch namespace from settings.
							"	Sql, ",
							"	null, ",
							"	context.Transaction,",
							"	false, null, null);",
							"return res.ToList();"
					})
				});

				//	##	Create the GetById method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "GetById",
					Comment = new CommentData(new[] {
						"This method is used for getting a record but its Id/primary key.",
						"If nothing is found an exception is thrown. If you want to get null back use LoadById <see cref=\"LoadById\"/> instead.",
						"<para>St4mpede guid:{71CF185E-0DD1-4FAE-9721-920B5C3C12D9}</para>"
						}),
					Scope = Common.VisibilityScope.Public,
					ReturnTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
					Parameters =
						new[] { new ParameterData
							{
								Name="context",
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							} }
						.Concat(
							table.PrimaryKeyColumns
								.Select(p =>
								   new ParameterData
								   {
									   Name = p.Name,
									   SystemTypeString = parserLogic2.ConvertDatabaseTypeToDotnetTypeString(p.DatabaseTypeName)
								   }))
						.ToList(),
					Body = new BodyData(new[]
						{
							$"const string Sql = @" + "\"",
							$"	Select * From {table.Name}",
							"\t Where " + string.Join(" And ", table.PrimaryKeyColumns.Select(c => $"{c.Name} = @{c.Name.ToCamelCase()}")),
							"\";",
							$"var res = context.Connection.Query<TheDAL.Poco.{table.Name}>(",	//	TODO:OF:Fetch namespace from settings.
							"	Sql, ",
							"	new {",
							$"		{string.Join(", ", table.Columns.Where(c => c.IsInPrimaryKey).Select(c =>$"{c.Name.ToCamelCase()} = {c.Name.ToCamelCase()}"))}",
							"	},",
							"	context.Transaction,",
							"	false, null, null);",
							"return res.Single();"
						})
				});

				//	##	Create the LoadById method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "LoadById",
					Comment = new CommentData(new[] {
						"This method is used for getting a record but its Id/primary key.",
						"If nothing is found an null is returned. If you want to throw an exception use GetById <see cref=\"GetById\"> instead.",
						"<para>St4mpede guid:{BC171F29-81F2-41ED-AC5C-AD6884EC9718}</para>"
						}),
					Scope = Common.VisibilityScope.Public,
					ReturnTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
					Parameters =
						new[] { new ParameterData
						{
							Name="context",
							SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
						} }
						.Concat(
							table.Columns
								.Where(c => c.IsInPrimaryKey)
								.Select(p =>
								   new ParameterData
								   {
									   Name = p.Name,
									   SystemTypeString = parserLogic2.ConvertDatabaseTypeToDotnetTypeString(p.DatabaseTypeName)
								   }))
						.ToList(),
					Body = new BodyData(new[]
						{
							$"const string Sql = @" + "\"",
							$"	Select * From {table.Name}",
							"\t Where " + string.Join(" And ", table.PrimaryKeyColumns.Select(c => $"{c.Name} = @{c.Name.ToCamelCase()}")),
							"\";",
							$"var res = context.Connection.Query<TheDAL.Poco.{table.Name}>(",	//	TODO:OF:Fetch namespace from settings.
							"	Sql, ",
							"	new {",
							$"		{string.Join(", ", table.Columns.Where(c => c.IsInPrimaryKey).Select(c =>$"{c.Name.ToCamelCase()} = {c.Name.ToCamelCase()}"))}",
							"	},",
							"	context.Transaction,",
							"	false, null, null);",
							"return res.SingleOrDefault();"
						})
				});

				//	##	Create the Update method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "Update",
					Comment = new CommentData(new [] {
						"This method is used for updating an existing record in the database.",
						"<para>St4mpede guid:{5A4CE926-447C-4F3F-ADFC-8CA9229C60BF}</para>"
						}),
					Scope = Common.VisibilityScope.Private,
					ReturnTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
					Parameters =
							new[] { new ParameterData
							{
								Name="context",
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							} }
						.Concat(
							table.Columns
								.Select(p =>
								   new ParameterData
								   {
									   Name = p.Name,
									   SystemTypeString = parserLogic2.ConvertDatabaseTypeToDotnetTypeString(p.DatabaseTypeName)
								   }))
						.ToList(),
					Body = new BodyData(new[]
						{
							$"return Update( ",
							"\tcontext, ",
							$"\tnew TheDAL.Poco.{table.Name}(",	//	TODO:OF:Fetch namespace from settings.
							"\t\t" + string.Join(", ",table.Columns.Select( c=> $"{c.Name.ToCamelCase()}")),
							"));"
						})
				});

				//	##	Create the Update method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "Update",
					Comment = new CommentData(new []{
						"This method is used for updating an existing record in the database.",
						"<para>St4mpede guid:{B2B1B845-5F93-4A5C-9F90-FBA570228542}</para>"
						}),
					Scope = Common.VisibilityScope.Private,
					ReturnTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
					Parameters = new[] {
							new ParameterData
							{
								Name="context",
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							},
							new ParameterData
							{
								Name = table.Name,	//	TODO:OF:Make camelcase.
								SystemTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
							} }
						.ToList(),
					Body = new BodyData(new[]
						{
						$"const string Sql = @" + "\"",
						$"	Update {table.Name}",
						$"	Set",
						"\t\t" + string.Join(", ",table.NonPrimaryKeyColumns.Select(c=>
							$"{c.Name} = @{c.Name.ToCamelCase()}"
						)),
						$"\tWhere",
						"\t\t" + string.Join(" And ",table.PrimaryKeyColumns.Select(c=>
							$"{c.Name} = @{c.Name}"))
						,
						$"\t Select * From {table.Name} Where ", 
						$"\t\t" + string.Join(" And ", table.PrimaryKeyColumns.Select(c=>$"{c.Name} = ${c.Name.ToCamelCase()}")),
						"\t\";",
						$"var ret = context.Connection.Query<TheDAL.Poco.{table.Name}>(", //	TODO:OF:Fetch namespace from Poco project.
						"	Sql, ",
						"	new {",
						$"	{string.Join(", ", table.Columns.Select(c=> "\t" + c.Name.ToCamelCase() + " = " + table.Name.ToCamelCase() + "." + c.Name  ))}",
						"	},",
						"	context.Transaction,",
						"	false, null, null);",
						"return ret.Single();",
					})
				});

				//	##	Create the Upsert method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "Upsert",
					Comment = new CommentData(new[] {
						"This method is used for creating a new or  updating an existing record in the database.",
						"If the primary key is 0 (zero) we know it is a new record and try to add it. Otherwise we try to update the record.",
						"<para>St4mpede guid:{A821E709-7333-4ABA-9F38-E85617C906FE}</para>"
						}),
					Scope = Common.VisibilityScope.Public,
					ReturnTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
					Parameters =
						new[] { new ParameterData
							{
								Name="context",
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							} }
						.Concat(
						table.Columns
							.Select(c =>
							   new ParameterData
							   {
								   Name = c.Name,
								   SystemTypeString = parserLogic2.ConvertDatabaseTypeToDotnetTypeString(c.DatabaseTypeName)
							   }))
						.ToList(),
					Body = new BodyData(new[]
						{
						$"return Upsert(",
						"\tcontext,",
						$"\tnew TheDAL.Poco.{table.Name}(", //	TODO:OF:Fetch namespace from settings.
						"\t\t" + string.Join( ", ", table.Columns.Select(c=>$"{c.Name.ToCamelCase()}")),
						"));"
					})
				});

				//	##	Create the Upsert method.
				surfaceClass.Methods.Add(new MethodData
				{
					Name = "Upsert",
					Comment = new CommentData(new[] {
						"This method is used for creating a new or  updating an existing record in the database.",
						"If the primary key is default value (typically null or zero) we know it is a new record and try to add it. Otherwise we try to update the record.",
						"<para>St4mpede guid:{97D67E96-7C3E-4D8B-8984-104896646077}</para>"
						}),
					Scope = Common.VisibilityScope.Public,
					ReturnTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
					Parameters = new[] {
							new ParameterData
							{
								Name="context",
								SystemTypeString = "TheDAL.CommitScope"	//	TODO:OF:Fetch namespace from settings.
							},
							new ParameterData
							{
								Name = table.Name,	//	TODO:OF:Make camelcase.
								SystemTypeString = $"TheDAL.Poco.{table.Name}", //	TODO:OF:Fetch namespace from Poco project.
							} }
						.ToList(),
					Body = new BodyData(new[]
						{
						"if(" + string.Join(" &&", table.PrimaryKeyColumns.Select(c=> $"{table.Name.ToCamelCase()}.{c.Name} == default({parserLogic2.ConvertDatabaseTypeToDotnetTypeString(c.DatabaseTypeName)})") ) + "){",
						$"\treturn Add(context, {table.Name.ToCamelCase()});", 
						"}else{",
						$"\treturn Update(context, {table.Name.ToCamelCase()});", 
						"}"
					})
				});
			});

			_log.Add("Included surfaces are:");
			_log.Add(_surfaceDataList.ToInfo());
		}
Ejemplo n.º 33
0
		internal void ReadXml()
		{
			var xmlRdbSchemaPathfile = Path.Combine(
				//@"C:\DATA\PROJEKT\St4mpede\St4mpede\St4mpede",
				_coreSettings.RootFolder,
				//	\RdbSchema",
				_rdbSchemaSettings.ProjectPath,
				//St4mpede.RdbSchema.xml";
				_rdbSchemaSettings.DatabaseXmlFile);

			IParserLogic2 parserLogic2 = new ParserLogic2();

			_log.Add("Reading xml {0}.", xmlRdbSchemaPathfile);

			//_database = _core.ReadFromXmlPathfile<DatabaseData>(xmlRdbSchemaPathfile);
			_database = parserLogic2.GetResult(xmlRdbSchemaPathfile);

			_log.Add(string.Format("Read database with tables: {0}.",
				string.Join(", ", _database.Tables.Select(t=>t.Name))));
		}