public static void StoreAstronomers(List <AstronomerDTO> astronomers) { using (var context = new PlanetHuntersContext()) { foreach (var a in astronomers) { if (a.FirstName == null || a.LastName == null) { Console.WriteLine("Invalid data format."); continue; } var currentAstronomer = new Astronomer() { FirstName = a.FirstName, LastName = a.LastName }; try { context.Astronomers.Add(currentAstronomer); context.SaveChanges(); Console.WriteLine($"Record {a.FirstName} {a.LastName} successfully imported."); } catch (DbEntityValidationException) { Console.WriteLine("Invalid data format."); } } } }
private void DeserializeAstronomers() { var astronomerDtos = JsonFileOperations.DeserializeJsonCollection <AstronomerDto>(Constants.AstronomerJsonFile); using (PlanetHuntersContext ctx = new PlanetHuntersContext()) { AstronomerRepo repo = new AstronomerRepo(ctx); foreach (var dto in astronomerDtos) { if (dto.FirstName != null && dto.LastName != null) { var a = new Astronomer(); Mapper.Map(dto, a); repo.Insert(a); this.DebugLog.AppendLine($"Record {dto.FirstName} {dto.LastName} successfully imported."); } else { this.DebugLog.AppendLine(Constants.InvalidDataFormat); } } DbUtil.ExecTransaction(ctx); } }
public static void AddAstronomers(IEnumerable <AstronomersDto> astronomersDtos) { Console.WriteLine("Storing <Astronomers> data in DB ..."); using (PlanetHuntersContext context = new PlanetHuntersContext()) { foreach (AstronomersDto astronomerDto in astronomersDtos) { if (astronomerDto.FirstName == null || astronomerDto.LastName == null) { Console.WriteLine("ERROR: Invalid data format."); } else { Astronomer astronomer = new Astronomer() { FirstName = astronomerDto.FirstName, LastName = astronomerDto.LastName }; context.Astronomers.Add(astronomer); Console.WriteLine($"Record {astronomer.FirstName} {astronomer.LastName} successfully imported."); } } context.SaveChanges(); } Console.WriteLine("<Astronomers> table stored!"); }
private static void ImportAstronomers(PlanetHunterContext context) { var json = File.ReadAllText("../../datasets/astronomers.json"); var astronomers = JsonConvert.DeserializeObject <ICollection <AstronomerDTO> >(json); using (context) { foreach (var astro in astronomers) { if (astro.FirstName == null || astro.LastName == null) { Console.WriteLine("Invalid data format."); continue; } var a = new Astronomer() { FirstName = astro.FirstName, LastName = astro.LastName }; context.Astronomers.Add(a); Console.WriteLine($"Record {astro.FirstName} {astro.LastName} successfully imported."); } context.SaveChanges(); } }
public static void AddAstronomers(IEnumerable <AstronomerDto> astronomers) { using (var context = new PlanetHuntersContext()) { foreach (var astronomer in astronomers) { if (astronomer.FirstName == null || astronomer.LastName == null || astronomer.FirstName.Length > Astronomer.FirstNameMaxLength || astronomer.LastName.Length > Astronomer.LastNameMaxLength) { Console.WriteLine("Invalid data format."); } else { Astronomer newAstronomer = new Astronomer() { FirstName = astronomer.FirstName, LastName = astronomer.LastName }; context.Astronomers.Add(newAstronomer); Console.WriteLine($"Record {astronomer.FirstName} {astronomer.LastName} successfully imported."); } } context.SaveChanges(); } }
/// <summary> /// Returns a count of the numbers of rows affected by the Upsert. /// </summary> /// <param name="person"></param> /// <param name="dataSource"></param> /// <param name="dbName"></param> /// <returns></returns> public int Upsert(Astronomer astronomer) { SqlConnection conn = this.CreateSqlConnection(); try { this.InitializeConnection(conn); SqlCommand cmd = conn.CreateCommand(); // Check if this method exists, and call insert or udpate as appropriate var id = astronomer.AstronomerId; cmd.CommandText = String.Format(@"SELECT CASE WHEN EXISTS (SELECT * FROM [Astronomer] WHERE AstronomerId = '{0}') THEN 1 else 0 END", id); var rowExists = cmd.ExecuteScalar(); if (rowExists.SafeToString() == "1") { return(this.Update(astronomer)); } else { return(this.Insert(astronomer)); } } finally { conn.Close(); } }
/// <summary> /// Deletes the specified Astronomer /// </summary> /// <returns></returns> public int Delete(Astronomer astronomer) { SqlConnection conn = this.CreateSqlConnection(); try { this.InitializeConnection(conn); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = String.Format(@"DELETE FROM [{0}].[Astronomer] WHERE [AstronomerId] = @AstronomerId", this.Schema); if (ReferenceEquals(astronomer.AstronomerId, null)) { cmd.Parameters.AddWithValue("@AstronomerId", DBNull.Value); } else { cmd.Parameters.AddWithValue("@AstronomerId", astronomer.AstronomerId); } int rowsAffected = cmd.ExecuteNonQuery(); return(rowsAffected); } finally { conn.Close(); } }
public ActionResult DeleteConfirmed(int id) { Astronomer astronomer = db.Astronomers.Find(id); db.Astronomers.Remove(astronomer); db.SaveChanges(); return(RedirectToAction("Index")); }
private static void AddEntityAstronomer(PlanetHuntersContext context, AstronomerDto astronomer) { Astronomer astronomerEntity = new Astronomer() { FirstName = astronomer.FirstName, LastName = astronomer.LastName }; context.Astronomers.Add(astronomerEntity); }
public ActionResult Edit([Bind(Include = "Id,Name")] Astronomer astronomer) { if (ModelState.IsValid) { db.Entry(astronomer).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(astronomer)); }
public ActionResult Create([Bind(Include = "Id,Name")] Astronomer astronomer) { if (ModelState.IsValid) { db.Astronomers.Add(astronomer); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(astronomer)); }
public static Astronomer GetAstronomerByName(string astronomer) { string[] astronomerArgs = astronomer.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries).ToArray(); string firstName = astronomerArgs[1]; string lastName = astronomerArgs[0]; using (var ctx = new PlanetHuntersContext()) { Astronomer astro = ctx.Astronomers.Include("ObservedDiscoveries").Include("PioneeredDiscoveries") .FirstOrDefault(s => s.FirstName == firstName || s.LastName == lastName); return(astro); } }
static void Main(string[] args) { ISkyObserver observer1 = new Astronomer(); ISkyObserver observer2 = new LittleBoy(); ISkyObserver observer3 = new Dreamer(); ISkyObserved sky = new SkyFullOfStars(); Console.ResetColor(); Console.WriteLine("Press any key to register Astronomer observer..."); Console.ReadLine(); sky.RegisterObserver(observer1); Console.ResetColor(); Console.WriteLine("Press any key to register Little boy observer..."); Console.ReadLine(); sky.RegisterObserver(observer2); Console.ResetColor(); Console.WriteLine("Press any key to register Dreamer observer..."); Console.ReadLine(); sky.RegisterObserver(observer3); Console.ResetColor(); Console.WriteLine("Press any key to unregister Astronomer observer..."); Console.ReadLine(); sky.UnregisterObserver(observer1); Console.ResetColor(); Console.WriteLine("Press any key to unregister Little boy observer..."); Console.ReadLine(); sky.UnregisterObserver(observer2); Console.ResetColor(); Console.WriteLine("Press any key to unregister Dreamer observer..."); Console.ReadLine(); sky.UnregisterObserver(observer3); Console.ResetColor(); Console.WriteLine("Exiting..."); SkyFullOfStars sfos = sky as SkyFullOfStars; sfos.StopFalling(); }
// GET: Astronomers/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Astronomer astronomer = db.Astronomers.Find(id); if (astronomer == null) { return(HttpNotFound()); } return(View(astronomer)); }
public static void AddAstronome(Astronomer astronomer) { using (var ctx = new PlanetHuntersContext()) { try { ctx.Astronomers.AddOrUpdate(a => new { a.FirstName, a.LastName }, astronomer); ctx.SaveChanges(); Printer.PrintSuccess(astronomer.FirstName + " " + astronomer.LastName); } catch (Exception) { ctx.Astronomers.Remove(astronomer); Printer.PrintError(); } } }
public static void Astronomers() { var json = File.ReadAllText(@"..\..\..\PlanetHunters.Import\ImportFiles\astronomers.json"); List <AstronomerDTO> astronomersDTOs = new List <AstronomerDTO>(); astronomersDTOs = JsonConvert.DeserializeObject <List <AstronomerDTO> >(json); StringBuilder sb = new StringBuilder(); List <Astronomer> astronomers = new List <Astronomer>(); foreach (var astronomerDTO in astronomersDTOs) { if (astronomerDTO.FirstName != null && astronomerDTO.LastName != null) { if (astronomerDTO.FirstName.Length > 50 || astronomerDTO.LastName.Length > 50) { sb.AppendLine("Invalid data format."); } else { Astronomer astro = new Astronomer { FirstName = astronomerDTO.FirstName, LastName = astronomerDTO.LastName }; astronomers.Add(astro); sb.AppendLine($"Record {astro.FullName} successfully imported."); } } else { sb.AppendLine("Invalid data format."); } } ImportQueries.ImportAstronomers(astronomers); Console.WriteLine(sb.ToString()); }
private static void ImportAstronomers() { string jsonFile = File.ReadAllText("../../../Resources/astronomers.json"); var astronomers = JsonConvert.DeserializeObject <IEnumerable <AstronomerDto> >(jsonFile); foreach (var astronom in astronomers) { if (astronom.FirstName == null || astronom.LastName == null) { Printer.PrintError(); continue; } var astronomer = new Astronomer { FirstName = astronom.FirstName, LastName = astronom.LastName }; QueryMethods.AddAstronome(astronomer); } }
private static void ImportAstronomers() { using (PlanetHuntersContext context = new PlanetHuntersContext()) { List <AstronomerDto> astronomerDtos = ParseJson <AstronomerDto>(Constants.AstronomersPath); foreach (AstronomerDto astronomerDto in astronomerDtos) { // We can make the checks for FirstName and LastName like this here, then // add the entity to the Database and save it with context.SaveChanges() with no errors // (but with this design we are skipping the attribute validations in the models) // OR // In order to use all the attribute validations which we have implemented in the models, // we can skip the validations here and just use a try-catch construction with Context.SaveChanges // so can the attributes to work as expected (we have to add the entity to Database in 'try', then remove it in 'catch'); if (astronomerDto.FirstName == null || astronomerDto.FirstName.Length > 50) { Console.WriteLine(Messages.Error); continue; } if (astronomerDto.LastName == null || astronomerDto.LastName.Length > 50) { Console.WriteLine(Messages.Error); continue; } Astronomer astronomerEntity = new Astronomer() { FirstName = astronomerDto.FirstName, LastName = astronomerDto.LastName }; HelperMethods.AddAstronomerToDatabase(context, astronomerEntity); } } }
public static void AddAstronomers(List <AstronomerDTO> astronomers) { using (var ctx = new PlanetHunterContext()) { foreach (var astronomerDTO in astronomers) { if (astronomerDTO.FirstName != null && astronomerDTO.LastName != null) { var astronomer = new Astronomer() { FirstName = astronomerDTO.FirstName, LastName = astronomerDTO.LastName }; ctx.Astronomers.Add(astronomer); Console.WriteLine($"Record {astronomer.FirstName} {astronomer.LastName} successfully imported."); } else { Console.WriteLine("Error. Invalid data provided!"); } } ctx.SaveChanges(); } }
/// <summary> /// Updates the specified Astronomer /// </summary> /// <returns></returns> public int Update(Astronomer astronomer) { SqlConnection conn = this.CreateSqlConnection(); try { this.InitializeConnection(conn); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = String.Format(@"UPDATE [{0}].[Astronomer] SET [createdTime] = @createdTime, [DOB] = @DOB, [Name] = @Name WHERE [AstronomerId] = @AstronomerId", this.Schema); if (ReferenceEquals(astronomer.AstronomerId, null)) { cmd.Parameters.AddWithValue("@AstronomerId", DBNull.Value); } else { cmd.Parameters.AddWithValue("@AstronomerId", astronomer.AstronomerId); } if (ReferenceEquals(astronomer.createdTime, null) || (astronomer.createdTime == DateTime.MinValue)) { cmd.Parameters.AddWithValue("@createdTime", DBNull.Value); } else { cmd.Parameters.AddWithValue("@createdTime", astronomer.createdTime); } if (ReferenceEquals(astronomer.DOB, null)) { cmd.Parameters.AddWithValue("@DOB", DBNull.Value); } else { cmd.Parameters.AddWithValue("@DOB", astronomer.DOB); } if (ReferenceEquals(astronomer.Name, null)) { cmd.Parameters.AddWithValue("@Name", DBNull.Value); } else { cmd.Parameters.AddWithValue("@Name", astronomer.Name); } int rowsAffected = cmd.ExecuteNonQuery(); return(rowsAffected); } finally { conn.Close(); } }
public static void AddDiscoveries(List <DiscoveryDto> discoreries) { using (var context = new PlanetHuntersContext()) { foreach (var discovery in discoreries) { // Validate required input: if (discovery.DateMade == null) { Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); continue; } // Validate Date Format DateTime dateMade; bool isValidDateMade = DateTime.TryParseExact(discovery.DateMade, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateMade); if (!isValidDateMade) { Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); continue; } // Validate Telescope Telescope telescope = context.Telescopes.FirstOrDefault(t => t.Name == discovery.Telescope); if (telescope == null) { Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); continue; } bool isMissingEntity = false; // astronomer, star, planet // Validate Pioneers List <Astronomer> pioneers = new List <Astronomer>(); foreach (var pioneer in discovery.Pioneers) { string[] names = pioneer.Split(',').Select(x => x.Trim()).ToArray(); if (names.Length != 2) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } string lastName = names[0]; string firstName = names[1]; if (firstName == null || lastName == null) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } Astronomer astronomer = context.Astronomers.FirstOrDefault(a => a.FirstName == firstName && a.LastName == lastName); if (astronomer == null) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } pioneers.Add(astronomer); } // Validate Observers List <Astronomer> observers = new List <Astronomer>(); foreach (var observer in discovery.Observers) { string[] names = observer.Split(',').Select(x => x.Trim()).ToArray(); if (names.Length != 2) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } string lastName = names[0]; string firstName = names[1]; if (firstName == null || lastName == null) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } Astronomer astronomer = context.Astronomers.FirstOrDefault(a => a.FirstName == firstName && a.LastName == lastName); if (astronomer == null) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } observers.Add(astronomer); } // Validate Stars List <Star> stars = new List <Star>(); foreach (var starName in discovery.Stars) { if (starName == null) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } Star star = context.Stars.FirstOrDefault(s => s.Name == starName); if (star == null) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } stars.Add(star); } // Validate Planets List <Planet> planets = new List <Planet>(); foreach (var planetName in discovery.Planets) { if (planetName == null) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } Planet planet = context.Planets.FirstOrDefault(p => p.Name == planetName); if (planet == null) { isMissingEntity = true; Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); break; } planets.Add(planet); } // Validate non-existing Astronomers, Stars & Planets if (isMissingEntity) { Console.WriteLine(Notifications.ErrorMsg.InvalidFormat); continue; } // Create Discovery Entity AddEntityDiscovery(context, dateMade, telescope, pioneers, observers, stars, planets); // Success Console.WriteLine($"Discovery ({dateMade:yyyy/MM/dd}-{telescope.Name}) with {stars.Count} star(s), {planets.Count} planet(s), {pioneers.Count} pioneer(s) and {observers.Count} observers successfully imported."); } context.SaveChanges(); } }
static void M(string[] args) { var astronomer = new Astronomer(FirstName: "Jane", LastName: "Doe"); string json = JsonSerializer.Serialize(astronomer, AstronomerJsonContext.Default.Astronomer); }