public static void SetMongoDBForTesting(INinjaFactoryData db) { var con = ConfigurationManager.ConnectionStrings["NinjaFactoryMongoDB"]; var conStr = con.ConnectionString; SetMongoDBForTesting(conStr, db); }
/* * //================================================================================================ * // HOW TO USE EXAMPLE * //================================================================================================ * * //var db = GetMongoDatabase(ConfigurationManager.ConnectionStrings["NinjaFactoryMongoDB"].ConnectionString); * * //var ninjaJobsCollection = db.GetCollection("jobs"); * * ////Get all the records in the collection * //GetAllRecordsInCollection(ninjaJobsCollection); * * ////Adding new entity to the collection * //AddNewEntityToCollection(ninjaJobsCollection, new Job { Description = "Kill your boss", Score = 43 }); * * ////Editing a entity * //var topPersonQuery = Query<Job>.EQ(e => e.Score, 100); * //var updateTopPerson = Update<Job>.Set(e => e.Score, 43); * //ninjaJobsCollection.Update(topPersonQuery, updateTopPerson); * * ////Removing entity * ////var query = Query<Entity>.EQ(e => e.Id, id); * ////personsCollection.Remove(query); * * ////Export the collection to MSSQL * //ExportCollectionToMSSQLServer(ninjaJobsCollection); * * //================================================================================================ * // HOW TO USE EXAMPLE * //================================================================================================ */ public static void InsertMongoDbReportsInDatabse(INinjaFactoryData db) { var con = ConfigurationManager.ConnectionStrings["NinjaFactoryMongoDB"]; var conStr = con.ConnectionString; InsertMongoDbReportsInDatabse(conStr, db); }
/// <summary> /// Gets the reports and finalize orders. /// </summary> /// <param name="sender"> The sender. </param> /// <param name="e"> The <see cref="EventArgs" /> instance containing the event data. </param> /// <exception cref="System.NotImplementedException"> Not Implemented </exception> private void GetReportsAndFinalizeOrders(object sender, EventArgs e) { INinjaFactoryData db = this.DB; MongoDBImport.InsertMongoDbReportsInDatabse(db); MessageBox.Show("Done"); }
private static void AddReportToDb(INinjaFactoryData db, JobReport rep) { Job finishedJob = db.Jobs.Where(j => j.Id == rep.Id).FirstOrDefault(); finishedJob.IsSuccessfull = rep.Success; finishedJob.EndDate = rep.EndDate; finishedJob.Ninja.KillCount += rep.KillCount; db.SaveChanges(); }
public static void SetMongoDBForTesting(string connectionString, INinjaFactoryData db) { var mongoDatabase = GetMongoDatabase(connectionString); var mongoCollection = mongoDatabase.GetCollection("jobs"); ClearRecords(mongoCollection); int addedCount = AddSomeRecords(mongoCollection, db); MessageBox.Show(string.Format("Removed all rows in the Mongo table, and added {0} [valid] rows for testing.", addedCount)); }
/// <summary> /// Creates the lost ninjas report. /// </summary> /// <param name="db"> The database. </param> /// <param name="filePath"> The file path. </param> public void CreateLostNinjasReport(INinjaFactoryData db, string filePath) { DateTime startedBefore = DateTime.Now.AddMonths(-2); IEnumerable<LostNinjaReport> oldUnfinishedJobs; oldUnfinishedJobs = this.SelectOldUnfinishedJobs(db, startedBefore); this.WriteToFile(oldUnfinishedJobs, filePath); }
public static void InsertMongoDbReportsInDatabse(string connectionString, INinjaFactoryData db) { var mongoDatabase = GetMongoDatabase(connectionString); var mongoCollection = mongoDatabase.GetCollection("jobs"); var reports = GetAllRecordsInCollection(mongoCollection); ExportCollectionToDataBase(reports, db); ClearRecords(mongoCollection); }
/// <summary> /// Gets the lost ninjas. /// </summary> /// <param name="lostNinjaReports"> The lost ninja reports. </param> /// <param name="db"> The database. </param> /// <returns> Queryable collection of all lost ninjas </returns> private IQueryable<Ninja> GetLostNinjas(XDocument lostNinjaReports, INinjaFactoryData db) { IEnumerable<int> lostNinjaIds = new List<int>(); lostNinjaIds = from ninja in lostNinjaReports.Descendants("LostNinjaReport") select int.Parse(ninja.Element("NinjaId").Value); var lostNinjas = db.Ninjas.All().Where(n => lostNinjaIds.Contains(n.Id)); return lostNinjas; }
/// <summary> /// Creates the lost ninjas report. /// </summary> /// <param name="db"> The database. </param> /// <param name="filePath"> The file path. </param> public void CreateLostNinjasReport(INinjaFactoryData db, string filePath) { DateTime startedBefore = DateTime.Now.AddMonths(-2); IEnumerable <LostNinjaReport> oldUnfinishedJobs; oldUnfinishedJobs = this.SelectOldUnfinishedJobs(db, startedBefore); this.WriteToFile(oldUnfinishedJobs, filePath); }
/// <summary> /// Deletes the ninjas mentioned in a lost ninjas report. /// </summary> /// <param name="db"> The database. </param> /// <param name="filePath"> The file path. </param> public void DeleteNinjasMentionedInLostNinjaReport(INinjaFactoryData db, string filePath) { XDocument lostNinjaReports = XDocument.Load(filePath); var lostNinjas = this.GetLostNinjas(lostNinjaReports, db); var failedMissions = this.GetFailedMissions(lostNinjaReports, db); this.RemoveFromDataBase(lostNinjas, failedMissions, db); }
/// <summary> /// Gets the failed missions. /// </summary> /// <param name="lostNinjaReports"> The lost ninja reports. </param> /// <param name="db"> The database. </param> /// <returns> Queryable collection of all failed missions </returns> private IQueryable<Job> GetFailedMissions(XDocument lostNinjaReports, INinjaFactoryData db) { IEnumerable<int> failedMissionsIds = new List<int>(); failedMissionsIds = from ninja in lostNinjaReports.Descendants("LostNinjaReport") select int.Parse(ninja.Element("JobId").Value); var failedMissions = db.Jobs.All().Where(j => failedMissionsIds.Contains(j.Id)); return failedMissions; }
/// <summary> /// Gets all jobs that are still in progress (dont have end date too) /// </summary> /// <param name="db"> the database context to get the data from </param> /// <param name="date"> the speciafied date for reports period </param> /// <returns></returns> private static IEnumerable <JobReport> SelectUnfinishedJobs(INinjaFactoryData db) { return(db.Jobs .Where(job => job.IsSuccessfull.Value == null) .Select(job => new JobReport() { Job = job, Ninja = job.Ninja, Client = job.Client, })); }
/// <summary> /// Gets all jobs that are still in progress (dont have end date too) /// </summary> /// <param name="db"> the database context to get the data from </param> /// <param name="date"> the speciafied date for reports period </param> /// <returns></returns> private static IEnumerable<JobReport> SelectUnfinishedJobs(INinjaFactoryData db) { return db.Jobs .Where(job => job.IsSuccessfull.Value == null) .Select(job => new JobReport() { Job = job, Ninja = job.Ninja, Client = job.Client, }); }
/// <summary> /// Gets the failed missions. /// </summary> /// <param name="lostNinjaReports"> The lost ninja reports. </param> /// <param name="db"> The database. </param> /// <returns> Queryable collection of all failed missions </returns> private IQueryable <Job> GetFailedMissions(XDocument lostNinjaReports, INinjaFactoryData db) { IEnumerable <int> failedMissionsIds = new List <int>(); failedMissionsIds = from ninja in lostNinjaReports.Descendants("LostNinjaReport") select int.Parse(ninja.Element("JobId").Value); var failedMissions = db.Jobs.All().Where(j => failedMissionsIds.Contains(j.Id)); return(failedMissions); }
/// <summary> /// Gets all jobs with specific outcome since a specified date /// </summary> /// <param name="db"> the database context to get the data from </param> /// <param name="date"> the specified date for reports period </param> /// <param name="state"> the state of the jobs required </param> /// <returns></returns> private static IEnumerable <JobReport> SelectJobs(INinjaFactoryData db, DateTime date, bool state) { return(db.Jobs .Where(job => job.EndDate.Value.Month >= date.Month) .Where(job => job.IsSuccessfull.Value == state) .Select(job => new JobReport() { Job = job, Ninja = job.Ninja, Client = job.Client })); }
/// <summary> /// Gets the lost ninjas. /// </summary> /// <param name="lostNinjaReports"> The lost ninja reports. </param> /// <param name="db"> The database. </param> /// <returns> Queryable collection of all lost ninjas </returns> private IQueryable <Ninja> GetLostNinjas(XDocument lostNinjaReports, INinjaFactoryData db) { IEnumerable <int> lostNinjaIds = new List <int>(); lostNinjaIds = from ninja in lostNinjaReports.Descendants("LostNinjaReport") select int.Parse(ninja.Element("NinjaId").Value); var lostNinjas = db.Ninjas.All().Where(n => lostNinjaIds.Contains(n.Id)); return(lostNinjas); }
/// <summary> /// Selects the old unfinished jobs. /// </summary> /// <param name="db"> The database. </param> /// <param name="startedBefore"> The started before. </param> /// <returns> IEnumerable collection of all unfinished jobs started before specified date </returns> private IEnumerable<LostNinjaReport> SelectOldUnfinishedJobs(INinjaFactoryData db, DateTime startedBefore) { return db.Jobs.All() .Where(job => job.IsSuccessfull.HasValue == false) .Where(job => job.Ninja.IsDeleted == false) .Where(job => job.StartDate < startedBefore) .Select(job => new LostNinjaReport() { Job = job, Ninja = job.Ninja, Client = job.Client }); }
/// <summary> /// Selects the old unfinished jobs. /// </summary> /// <param name="db"> The database. </param> /// <param name="startedBefore"> The started before. </param> /// <returns> IEnumerable collection of all unfinished jobs started before specified date </returns> private IEnumerable <LostNinjaReport> SelectOldUnfinishedJobs(INinjaFactoryData db, DateTime startedBefore) { return(db.Jobs.All() .Where(job => job.IsSuccessfull.HasValue == false) .Where(job => job.Ninja.IsDeleted == false) .Where(job => job.StartDate < startedBefore) .Select(job => new LostNinjaReport() { Job = job, Ninja = job.Ninja, Client = job.Client })); }
/// <summary> /// Removes the lost ninjas from the data base. /// </summary> /// <param name="lostNinjas"> The lost ninjas. </param> /// <param name="failedMissions"> The failed missions. </param> /// <param name="db"> The database. </param> private void RemoveFromDataBase(IQueryable<Ninja> lostNinjas, IQueryable<Job> failedMissions, INinjaFactoryData db) { foreach (Ninja nin in lostNinjas) { nin.IsDeleted = true; } foreach (Job job in failedMissions) { job.IsSuccessfull = false; job.EndDate = DateTime.Now; } db.SaveChanges(); }
/// <summary> /// Creates the report for lost ninjas. /// </summary> /// <param name="sender"> The sender. </param> /// <param name="e"> The <see cref="EventArgs" /> instance containing the event data. </param> /// <exception cref="System.NotImplementedException"> Not Implemented </exception> private void CreateReportForLostNinjas(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "xml files (*.xml)|*.xml"; saveFileDialog.FileName = "LostNinjasReport"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { string filePath = saveFileDialog.FileName; INinjaFactoryData db = this.DB; XmlLostNinjaReportCreator creator = new XmlLostNinjaReportCreator(); creator.CreateLostNinjasReport(db, filePath); MessageBox.Show("Done"); } }
/// <summary> /// Removes the lost ninjas. /// </summary> /// <param name="sender"> The sender. </param> /// <param name="e"> The <see cref="EventArgs" /> instance containing the event data. </param> /// <exception cref="System.NotImplementedException"> Not Implemented </exception> private void RemoveLostNinjas(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "xml files (*.xml)|*.xml"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; INinjaFactoryData db = this.DB; XmlLostNinjaReportParser reportParser = new XmlLostNinjaReportParser(); reportParser.DeleteNinjasMentionedInLostNinjaReport(db, filePath); MessageBox.Show("Done"); } }
private static bool CheckIfReportIsValid(INinjaFactoryData db, JobReport rep) { var job = db.Jobs.Where(j => j.Id == rep.Id).FirstOrDefault(); if (job == null) { throw new ArgumentOutOfRangeException("There is no job with Id '" + rep.Id + "'"); } if (job.IsSuccessfull.HasValue == true) { throw new ArgumentException("The job with Id '" + rep.Id + "' is already compleated"); } return(true); }
private static bool CheckJobIsValid(DataBase.Job job, INinjaFactoryData db) { var unfinishedJobsCountOfSameNinja = db.Jobs .Where(j => j.NinjaId == job.NinjaId) .Where(j => j.IsSuccessfull.HasValue == false) .Count(); if (unfinishedJobsCountOfSameNinja > 0) { throw new ArgumentException("A ninja can not take two jobs at the same time. Job '" + job.Name + "' was not imported"); } else { return(true); } }
/// <summary> /// Creates the ninja catalogue. /// </summary> /// <param name="sender"> The sender. </param> /// <param name="e"> The <see cref="EventArgs" /> instance containing the event data. </param> /// <exception cref="System.NotImplementedException"> Not Implemented </exception> private void CreateNinjaCatalogue(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "JSON files (*.json)|*.json"; saveFileDialog.FileName = "NinjaCatalogue"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { string filePath = saveFileDialog.FileName; INinjaFactoryData db = this.DB; NinjaCatalogueCreator creator = new NinjaCatalogueCreator(); creator.CreateJson(db, filePath); MessageBox.Show("Ninjas catalog created successfully!"); } }
/// <summary> /// Creates a JSON report of ninjas from a database and places it in a file /// </summary> /// <param name="db"> the database to draw infromation from </param> /// <param name="filePath"> the path to the output file containing json report </param> public void CreateJson(INinjaFactoryData db, string filePath) { var ninjaItems = this.GetNinjaCatalogueFromDb(db); foreach (var item in ninjaItems) { if (item.SuccessfulJobsCount > 0) { item.SuccessRate = Math.Round((double)item.SuccessfulJobsCount / item.JobsCount, 2); } } DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(NinjaCatalogueItem[])); FileStream fileStream = new FileStream(filePath, FileMode.Create); jsonSerializer.WriteObject(fileStream, ninjaItems); }
/// <summary> /// Creates the income report. /// </summary> /// <param name="sender"> The sender. </param> /// <param name="e"> The <see cref="EventArgs" /> instance containing the event data. </param> /// <exception cref="System.NotImplementedException"> Not Implemented </exception> private void CreateIncomeReport(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "PDF files (*.pdf)|*.pdf"; saveFileDialog.FileName = "IncomeReports"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { string filePath = saveFileDialog.FileName; INinjaFactoryData db = this.DB; // TODO: Implement and use a library doing this task. Use the filePath and db from above. PDFIncomeReportCreator pdfCreator = new PDFIncomeReportCreator(); pdfCreator.CreatePDFReport(db, filePath); MessageBox.Show("Income reports created successfully!"); } }
public NinjaCatalogueItem[] GetNinjaCatalogueFromDb(INinjaFactoryData db) { var ninjaItems = db.Ninjas .Where(n => n.Jobs.Where(j => j.IsSuccessfull.HasValue == false).Count() == 0) .Select(n => new NinjaCatalogueItem() { NinjaId = n.Id, Name = n.Name, KillCount = n.KillCount, Weapon = n.WeaponOfChoice, Price = n.MinimalPersonalPrice + n.Speciality.MinimalCompanyPrice, SpecialtyName = n.Speciality.Name, JobsCount = n.Jobs.Count(), SuccessfulJobsCount = n.Jobs.Where(j => j.IsSuccessfull.HasValue == true && j.IsSuccessfull.Value == true).Count(), SuccessRate = 0 }) .ToArray(); return ninjaItems; }
public NinjaCatalogueItem[] GetNinjaCatalogueFromDb(INinjaFactoryData db) { var ninjaItems = db.Ninjas .Where(n => n.Jobs.Where(j => j.IsSuccessfull.HasValue == false).Count() == 0) .Select(n => new NinjaCatalogueItem() { NinjaId = n.Id, Name = n.Name, KillCount = n.KillCount, Weapon = n.WeaponOfChoice, Price = n.MinimalPersonalPrice + n.Speciality.MinimalCompanyPrice, SpecialtyName = n.Speciality.Name, JobsCount = n.Jobs.Count(), SuccessfulJobsCount = n.Jobs.Where(j => j.IsSuccessfull.HasValue == true && j.IsSuccessfull.Value == true).Count(), SuccessRate = 0 }) .ToArray(); return(ninjaItems); }
/// <summary> /// Adds the new orders. /// </summary> /// <param name="sender"> The sender. </param> /// <param name="e"> The <see cref="EventArgs" /> instance containing the event data. </param> /// <exception cref="System.NotImplementedException"> Not Implemented </exception> private void AddNewOrders(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "ZIP files (*.zip)|*.zip"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; INinjaFactoryData db = this.DB; string directoryOfExtractedFiles = "UnimportedJobs"; string pattern = string.Empty; ExcelImport.ExtractFile(filePath, directoryOfExtractedFiles); ExcelImport.ProcessExcelFiles(directoryOfExtractedFiles, pattern, db); Directory.Delete(directoryOfExtractedFiles, true); MessageBox.Show("Done"); } }
public static void ProcessExcelFiles(string rootDirPath, string pattern, INinjaFactoryData db) { var files = Directory.GetFiles(rootDirPath, pattern); if (string.IsNullOrEmpty(pattern)) { files = Directory.GetFiles(rootDirPath); } ImportExcelFilesIntoDb(files, db); var directories = Directory.GetDirectories(rootDirPath); foreach (var dir in directories) { var dirFiles = Directory.GetFiles(dir, pattern); ImportExcelFilesIntoDb(dirFiles, db); ProcessExcelFiles(dir, pattern, db); } }
public void CreatePDFReport(INinjaFactoryData db, string filePath) { DateTime date = DateTime.Now.AddMonths(ReportsTimespanInMonths); try { IEnumerable <JobReport> successfullJobs = SelectJobs(db, date, true); IEnumerable <JobReport> failedJobs = SelectJobs(db, date, false); IEnumerable <JobReport> jobsInProgress = SelectUnfinishedJobs(db); Document doc = new Document(iTextSharp.text.PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create)); doc.Open(); string header = SuccessfulJosHeader; string footer = SuccessfulJosFooter; WriteToFile(successfullJobs, filePath, doc, header, footer); doc.NewPage(); header = FailedJosHeader; footer = FailedJosFooter; WriteToFile(failedJobs, filePath, doc, header, footer); doc.NewPage(); header = UnfinishedJosHeader; footer = UnfinishedJosFooter; WriteToFile(jobsInProgress, filePath, doc, header, footer); doc.Close(); } catch (Exception exc) { MessageBox.Show("An error occured!" + exc.Message); } /* * IEnumerable<JobReport> successfullJobs; * * successfullJobs = this.SelectSuccesfullJobs(db); * * this.WriteToFile(successfullJobs, filePath); */ }
/// <summary> /// Imports data in database /// </summary> /// <param name="files"> excel files containing import data </param> /// <param name="db"> the database to import the data in </param> private static void ImportExcelFilesIntoDb(string[] files, INinjaFactoryData db) { string sheetName = "Sales"; foreach (var filePath in files) { DataTable excelTable = ReadExcelFile(filePath, sheetName); for (int i = 2; i < excelTable.Rows.Count - 1; i++) { var row = excelTable.Rows[i]; int ninjaId = int.Parse(row.ItemArray[0].ToString()); int clientId = int.Parse(row.ItemArray[1].ToString()); string briefDescription = row.ItemArray[2].ToString(); double jobPrice = double.Parse(row.ItemArray[3].ToString()); DataBase.Job job = new DataBase.Job() { NinjaId = ninjaId, ClientId = clientId, Name = briefDescription, Price = (decimal)jobPrice, StartDate = DateTime.Now, IsDeleted = false }; try { CheckJobIsValid(job, db); ImportJobToDb(job, db); } catch (ArgumentException ae) { MessageBox.Show(ae.Message); } } } }
public void CreatePDFReport(INinjaFactoryData db, string filePath) { DateTime date = DateTime.Now.AddMonths(ReportsTimespanInMonths); try { IEnumerable<JobReport> successfullJobs = SelectJobs(db, date, true); IEnumerable<JobReport> failedJobs = SelectJobs(db, date, false); IEnumerable<JobReport> jobsInProgress = SelectUnfinishedJobs(db); Document doc = new Document(iTextSharp.text.PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create)); doc.Open(); string header = SuccessfulJosHeader; string footer = SuccessfulJosFooter; WriteToFile(successfullJobs, filePath, doc, header, footer); doc.NewPage(); header = FailedJosHeader; footer = FailedJosFooter; WriteToFile(failedJobs, filePath, doc, header, footer); doc.NewPage(); header = UnfinishedJosHeader; footer = UnfinishedJosFooter; WriteToFile(jobsInProgress, filePath, doc, header, footer); doc.Close(); } catch (Exception exc) { MessageBox.Show("An error occured!" + exc.Message); } /* IEnumerable<JobReport> successfullJobs; successfullJobs = this.SelectSuccesfullJobs(db); this.WriteToFile(successfullJobs, filePath); */ }
private static void ExportCollectionToDataBase(ICollection <JobReport> reports, INinjaFactoryData db) { foreach (var rep in reports) { /* * // testing. Delete this MessageBox.Show() once the program is confirmed to work. * // MessageBox.Show(string.Format( * // "id:{0}, \n" + * // "Success: {1}, \n" + * // "KillCount: {2}, \n" + * // "EndDate: {3}", * // rep.Id, * // rep.Success, * // rep.KillCount, * // rep.EndDate)); */ try { if (CheckIfReportIsValid(db, rep)) { AddReportToDb(db, rep); } } catch (ArgumentException ae) { MessageBox.Show(ae.Message + "\n\n" + string.Format( "id:{0}, \n" + "Success: {1}, \n" + "KillCount: {2}, \n" + "EndDate: {3}", rep.Id, rep.Success, rep.KillCount, rep.EndDate)); } } }
private static int AddSomeRecords(MongoCollection <BsonDocument> mongoCollection, INinjaFactoryData db) { IQueryable <JobReport> unfinishedJobsReports = db.Jobs .Where(j => j.IsSuccessfull.HasValue == false) .Select(j => new JobReport() { Id = j.Id, Success = true, EndDate = DateTime.Today, KillCount = 2 }); foreach (JobReport jobRep in unfinishedJobsReports) { AddNewEntityToCollection(mongoCollection, jobRep); } return(unfinishedJobsReports.Count()); }
private static int AddSomeRecords(MongoCollection<BsonDocument> mongoCollection, INinjaFactoryData db) { IQueryable<JobReport> unfinishedJobsReports = db.Jobs .Where(j => j.IsSuccessfull.HasValue == false) .Select(j => new JobReport() { Id = j.Id, Success = true, EndDate = DateTime.Today, KillCount = 2 }); foreach (JobReport jobRep in unfinishedJobsReports) { AddNewEntityToCollection(mongoCollection, jobRep); } return unfinishedJobsReports.Count(); }
/// <summary> /// Gets all jobs with specific outcome since a specified date /// </summary> /// <param name="db"> the database context to get the data from </param> /// <param name="date"> the specified date for reports period </param> /// <param name="state"> the state of the jobs required </param> /// <returns></returns> private static IEnumerable<JobReport> SelectJobs(INinjaFactoryData db, DateTime date, bool state) { return db.Jobs .Where(job => job.EndDate.Value.Month >= date.Month) .Where(job => job.IsSuccessfull.Value == state) .Select(job => new JobReport() { Job = job, Ninja = job.Ninja, Client = job.Client }); }
/* //================================================================================================ // HOW TO USE EXAMPLE //================================================================================================ //var db = GetMongoDatabase(ConfigurationManager.ConnectionStrings["NinjaFactoryMongoDB"].ConnectionString); //var ninjaJobsCollection = db.GetCollection("jobs"); ////Get all the records in the collection //GetAllRecordsInCollection(ninjaJobsCollection); ////Adding new entity to the collection //AddNewEntityToCollection(ninjaJobsCollection, new Job { Description = "Kill your boss", Score = 43 }); ////Editing a entity //var topPersonQuery = Query<Job>.EQ(e => e.Score, 100); //var updateTopPerson = Update<Job>.Set(e => e.Score, 43); //ninjaJobsCollection.Update(topPersonQuery, updateTopPerson); ////Removing entity ////var query = Query<Entity>.EQ(e => e.Id, id); ////personsCollection.Remove(query); ////Export the collection to MSSQL //ExportCollectionToMSSQLServer(ninjaJobsCollection); //================================================================================================ // HOW TO USE EXAMPLE //================================================================================================ */ public static void InsertMongoDbReportsInDatabse(INinjaFactoryData db) { var con = ConfigurationManager.ConnectionStrings["NinjaFactoryMongoDB"]; var conStr = con.ConnectionString; InsertMongoDbReportsInDatabse(conStr, db); }
private static void ExportCollectionToDataBase(ICollection<JobReport> reports, INinjaFactoryData db) { foreach (var rep in reports) { /* // testing. Delete this MessageBox.Show() once the program is confirmed to work. // MessageBox.Show(string.Format( // "id:{0}, \n" + // "Success: {1}, \n" + // "KillCount: {2}, \n" + // "EndDate: {3}", // rep.Id, // rep.Success, // rep.KillCount, // rep.EndDate)); */ try { if (CheckIfReportIsValid(db, rep)) { AddReportToDb(db, rep); } } catch (ArgumentException ae) { MessageBox.Show(ae.Message + "\n\n" + string.Format( "id:{0}, \n" + "Success: {1}, \n" + "KillCount: {2}, \n" + "EndDate: {3}", rep.Id, rep.Success, rep.KillCount, rep.EndDate)); } } }
private static bool CheckIfReportIsValid(INinjaFactoryData db, JobReport rep) { var job = db.Jobs.Where(j => j.Id == rep.Id).FirstOrDefault(); if (job == null) { throw new ArgumentOutOfRangeException("There is no job with Id '" + rep.Id + "'"); } if (job.IsSuccessfull.HasValue == true) { throw new ArgumentException("The job with Id '" + rep.Id + "' is already compleated"); } return true; }
private static bool CheckJobIsValid(DataBase.Job job, INinjaFactoryData db) { var unfinishedJobsCountOfSameNinja = db.Jobs .Where(j => j.NinjaId == job.NinjaId) .Where(j => j.IsSuccessfull.HasValue == false) .Count(); if (unfinishedJobsCountOfSameNinja > 0) { throw new ArgumentException("A ninja can not take two jobs at the same time. Job '" + job.Name + "' was not imported"); } else { return true; } }
private static void ImportJobToDb(DataBase.Job job, INinjaFactoryData db) { db.Jobs.Add(job); db.SaveChanges(); }
/// <summary> /// Removes the lost ninjas from the data base. /// </summary> /// <param name="lostNinjas"> The lost ninjas. </param> /// <param name="failedMissions"> The failed missions. </param> /// <param name="db"> The database. </param> private void RemoveFromDataBase(IQueryable <Ninja> lostNinjas, IQueryable <Job> failedMissions, INinjaFactoryData db) { foreach (Ninja nin in lostNinjas) { nin.IsDeleted = true; } foreach (Job job in failedMissions) { job.IsSuccessfull = false; job.EndDate = DateTime.Now; } db.SaveChanges(); }