private static void ImportEntities(PhotographyDbContext context, string baseDir = @"Datasets\")
        {
            const string exportDir = "./ImportResults/";

            var lenses = DataProcessor.Deserializer.ImportLenses(context, File.ReadAllText(baseDir + "lenses.json"));

            PrintAndExportEntityToFile(lenses, exportDir + "Lenses.txt");

            var cameras = DataProcessor.Deserializer.ImportCameras(context, File.ReadAllText(baseDir + "cameras.json"));

            PrintAndExportEntityToFile(cameras, exportDir + "Cameras.txt");

            var photographers = DataProcessor.Deserializer.ImportPhotographers(context, File.ReadAllText(baseDir + "photographers.json"));

            PrintAndExportEntityToFile(photographers, exportDir + "Photographers.txt");


            var accessories = DataProcessor.Deserializer.ImportAccessories(context, File.ReadAllText(baseDir + "accessories.xml"));

            PrintAndExportEntityToFile(accessories, exportDir + "Accessories.txt");

            var workshops = DataProcessor.Deserializer.ImportWorkshops(context, File.ReadAllText(baseDir + "workshops.xml"));

            PrintAndExportEntityToFile(workshops, exportDir + "Workshops.txt");
        }
        private static void ExportEntities(PhotographyDbContext context)
        {
            const string exportDir = "./ExportResults/";

            string jsonOutput = DataProcessor.Serializer.ExportOrderedPhotographers(context);

            Console.WriteLine(jsonOutput);
            File.WriteAllText(exportDir + "photographers-ordered.json", jsonOutput);

            string jsonOutput2 = DataProcessor.Serializer.ExportLandscapePhotographers(context);

            Console.WriteLine(jsonOutput2);
            File.WriteAllText(exportDir + "landscape-photographers.json", jsonOutput2);


            string xmlOutput = DataProcessor.Serializer.ExportSameCamerasPhotographers(context);

            Console.WriteLine(xmlOutput);
            File.WriteAllText(exportDir + "same-cameras-photographers.xml", xmlOutput);

            string xmlOutput2 = DataProcessor.Serializer.ExportWorkshopsByLocation(context);

            Console.WriteLine(xmlOutput2);
            File.WriteAllText(exportDir + "workshops-by-location.xml", xmlOutput2);
        }
        private static void ResetDatabase(PhotographyDbContext context, bool shouldDeleteDatabase = false)
        {
            if (shouldDeleteDatabase)
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }

            context.Database.EnsureCreated();

            var disableIntegrityChecksQuery = "EXEC sp_MSforeachtable @command1='ALTER TABLE ? NOCHECK CONSTRAINT ALL'";

            context.Database.ExecuteSqlCommand(disableIntegrityChecksQuery);

            var deleteRowsQuery = "EXEC sp_MSforeachtable @command1='DELETE FROM ?'";

            context.Database.ExecuteSqlCommand(deleteRowsQuery);

            var enableIntegrityChecksQuery = "EXEC sp_MSforeachtable @command1='ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'";

            context.Database.ExecuteSqlCommand(enableIntegrityChecksQuery);

            var reseedQuery = "EXEC sp_MSforeachtable @command1='DBCC CHECKIDENT(''?'', RESEED, 0)'";

            try
            {
                context.Database.ExecuteSqlCommand(reseedQuery);
            }
            catch (SqlException) // OrderItems table has no identity column, which isn't a problem
            {
            }
        }
        public static void Main(string[] args)
        {
            var context = new PhotographyDbContext();

            ResetDatabase(context, true);

            Console.WriteLine("Database Reset.");

            Mapper.Initialize(cfg => cfg.AddProfile <MappingProfile>());

            ImportEntities(context);
            ExportEntities(context);
        }
Beispiel #5
0
        public static string ExportOrderedPhotographers(PhotographyDbContext context)
        {
            var photographers = context.Photographers
                                .OrderBy(p => p.FirstName)
                                .ThenByDescending(p => p.LastName)
                                .Select(p => new
            {
                p.FirstName,
                p.LastName,
                p.Phone
            });
            var json = JsonConvert.SerializeObject(photographers, Formatting.Indented);

            return(json);
        }
        public static string ImportCameras(PhotographyDbContext context, string jsonString)
        {
            var camerasDtos = JsonConvert.DeserializeObject <CameraDto[]>(jsonString);

            var validDslrCameras       = new List <DSLRCamera>();
            var validMirrorlessCameras = new List <MirrorlessCamera>();
            var sb = new StringBuilder();

            foreach (var cameraDto in camerasDtos)
            {
                if (!IsValid(cameraDto) || cameraDto.Type == null || cameraDto.Make == null || cameraDto.Model == null)
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                Type cameraType = Assembly
                                  .GetAssembly(typeof(Camera))
                                  .GetTypes()
                                  .FirstOrDefault(type => type.Name.ToLower() == (cameraDto.Type + "Camera").ToLower());

                if (cameraDto.Type.ToLower() == "mirrorless")
                {
                    var camera = (MirrorlessCamera)Mapper.Map(cameraDto, cameraDto.GetType(), cameraType);
                    validMirrorlessCameras.Add(camera);
                }

                if (cameraDto.Type.ToLower() == "dslr")
                {
                    var camera = (DSLRCamera)Mapper.Map(cameraDto, cameraDto.GetType(), cameraType);
                    validDslrCameras.Add(camera);
                }

                string cameraDtoinfo = $"{cameraDto.Type} {cameraDto.Make} {cameraDto.Model}";

                sb.AppendLine(string.Format(SuccessMessage, cameraDtoinfo));
            }

            context.MirrorlessCameras.AddRange(validMirrorlessCameras);
            context.DslrCameras.AddRange(validDslrCameras);

            context.SaveChanges();

            var result = sb.ToString();

            return(result);
        }
        public static string ImportAccessories(PhotographyDbContext context, string xmlString)
        {
            var serializer    = new XmlSerializer(typeof(AccessoryDto[]), new XmlRootAttribute("accessories"));
            var accessoryDtos = (AccessoryDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));

            var validAccessories = new List <Accessory>();
            var sb = new StringBuilder();

            foreach (var accessoryDto in accessoryDtos)
            {
                if (!IsValid(accessoryDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                //add random photographer
                var photographersDb = context.Photographers.ToArray();

                Random rnd          = new Random();
                var    photographer = photographersDb[rnd.Next(photographersDb.Count() - 1)];

                var accessory = new Accessory()
                {
                    Name  = accessoryDto.Name,
                    Owner = photographer
                };

                validAccessories.Add(accessory);
                sb.AppendLine(String.Format(SuccessMessage, accessoryDto.Name));
            }

            context.Accessories.AddRange(validAccessories);
            context.SaveChanges();

            var result = sb.ToString();

            return(result);
        }
        public static string ImportWorkshopsManual(PhotographyDbContext context, string xmlString)
        {
            var serializer   = new XmlSerializer(typeof(WorkshopDto[]), new XmlRootAttribute("workshops"));
            var workshopDtos = (WorkshopDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));


            var validWorkshops = new List <Workshop>();
            var sb             = new StringBuilder();

            foreach (var workshopDto in workshopDtos)
            {
                //var participantsDtos =
                //    (ParticipantDto[]) serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));
            }

            context.Workshops.AddRange(validWorkshops);
            context.SaveChanges();

            var result = sb.ToString();

            return(result);
        }
Beispiel #9
0
        public static string ExportWorkshopsByLocation(PhotographyDbContext context)
        {
            var workshops = context.Workshops
                            .Include(w => w.Participants)
                            .Where(w => w.Participants.Count >= 0)
                            .GroupBy(w => w.Location, w => w, (l, w) => new
            {
                Location  = l,
                Workshops = w
            })
                            .Where(l => l.Workshops.Any())
                            .Select(e => new LocationDto()
            {
                Name          = e.Location,
                WorkshopsDtos = e.Workshops.Select(w => new WorkshopExportDto()
                {
                    Name        = w.Name,
                    TotalProfit = (w.Participants.Count * w.PricePerParticipant) -
                                  ((w.Participants.Count * w.PricePerParticipant) * 0.2m),
                    ParticipantDto = new ParticipantsDto()
                    {
                        ParticipantCount = w.Participants.Count,
                        Names            = w.Participants.Select(p => p.Photographer.FirstName + " " + p.Photographer.LastName)
                                           .ToList()
                    }
                }).ToList()
            }).ToArray();


            var sb = new StringBuilder();

            var serializer = new XmlSerializer(typeof(LocationDto[]), new XmlRootAttribute("locations"));

            serializer.Serialize(new StringWriter(sb), workshops, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));

            var result = sb.ToString();

            return(result);
        }
Beispiel #10
0
        public static string ExportSameCamerasPhotographers(PhotographyDbContext context)
        {
            var photographers = context.Photographers
                                .Include(p => p.Lens)
                                .Where(p => p.PrimaryCamera.Make == p.SecondaryCamera.Make)
                                .Select(p => new SameCameraMakePhotographerDto
            {
                Name          = p.FirstName + " " + p.LastName,
                PrimaryCamera = p.PrimaryCamera.Make + " " +
                                p.PrimaryCamera.Model,
                Lenses = p.Lens.Select(l => l.Make + " " + l.FocalLength + "mm f" + l.MaxAperture).ToList()
            }).ToArray();

            var sb = new StringBuilder();

            var serializer = new XmlSerializer(typeof(SameCameraMakePhotographerDto[]), new XmlRootAttribute("photographers"));

            serializer.Serialize(new StringWriter(sb), photographers, new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));

            var result = sb.ToString();

            return(result);
        }
Beispiel #11
0
        public static string ExportLandscapePhotographers(PhotographyDbContext context)
        {
            //var type = context.Photographers
            //    .Include(p=>p.PrimaryCamera).Count(p => p.PrimaryCamera.GetType()==typeof(MirrorlessCamera));

            var photographers = context.Photographers
                                .Where(p => p.PrimaryCamera is MirrorlessCamera &&
                                       p.Lens.Count > 0 &&
                                       p.Lens.All(lens => lens.FocalLength <= 30))
                                .OrderBy(p => p.FirstName)
                                .Select(p => new
            {
                p.FirstName,
                p.LastName,
                CameraMake  = p.PrimaryCamera.Make,
                LensesCount = p.Lens.Count
            }).ToArray();


            var json = JsonConvert.SerializeObject(photographers, Formatting.Indented);

            return(json);
        }
        public static string ImportLenses(PhotographyDbContext context, string jsonString)
        {
            var lenDtos = JsonConvert.DeserializeObject <LenDto[]>(jsonString);

            var validLens = new List <Len>();
            var sb        = new StringBuilder();

            foreach (var lenDto in lenDtos)
            {
                if (!IsValid(lenDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var len = new Len()
                {
                    Make           = lenDto.Make,
                    FocalLength    = lenDto.FocalLength,
                    MaxAperture    = lenDto.MaxAperture,
                    CompatibleWith = lenDto.CompatibleWith
                };

                validLens.Add(len);

                string lenDtoinfo = $"{lenDto.Make} {lenDto.FocalLength}mm f{lenDto.MaxAperture:f1}";

                sb.AppendLine(string.Format(SuccessMessage, lenDtoinfo));
            }

            context.Lens.AddRange(validLens);
            context.SaveChanges();

            var result = sb.ToString();

            return(result);
        }
 public ArtistService(PhotographyDbContext DbContext, IMapper mapper) : base(DbContext)
 {
     _mapper = mapper;
 }
Beispiel #14
0
 public TagServices(PhotographyDbContext dbContext, IMapper mapper) : base(dbContext)
 {
     _mapper = mapper;
 }
Beispiel #15
0
 public DashboardService(PhotographyDbContext photgraphyDbContext, IMapper mapper) : base(photgraphyDbContext)
 {
     _Mapper = mapper;
 }
 public CarouselService(PhotographyDbContext dbContext, IMapper mapper) : base(dbContext)
 {
     _mapper = mapper;
 }
 public BaseService(PhotographyDbContext dbContext)
 {
     this.dbContext = dbContext;
 }
        public static string ImportPhotographers(PhotographyDbContext context, string jsonString)
        {
            var photographerDtos = JsonConvert.DeserializeObject <PhotographerDto[]>(jsonString);

            var validPhotographers = new List <Photographer>();
            var sb = new StringBuilder();

            foreach (var photographerDto in photographerDtos)
            {
                //check input valid
                if (!IsValid(photographerDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                //add random cameras
                var dslrCameras      = context.DslrCameras.ToArray();
                int maxDslrCameraIds = dslrCameras.Length;

                var mirrorlessCameras      = context.MirrorlessCameras.ToArray();
                int maxMirrorlessCameraIds = mirrorlessCameras.Length;

                Random rnd             = new Random();
                Camera primaryCamera   = dslrCameras[rnd.Next(maxDslrCameraIds - 1)];
                Camera secondaryCamera = mirrorlessCameras[rnd.Next(maxMirrorlessCameraIds - 1)];

                var primaryCameraMake   = primaryCamera.Make;
                var secondaryCameraMake = secondaryCamera.Make;

                //check lenses and create list of valid ones
                var lensIds   = photographerDto.Lenses;
                var validLens = new List <Len>();

                var dbLens = context.Lens;

                foreach (var lensId in lensIds)
                {
                    //check is id exist
                    var len = dbLens.SingleOrDefault(l => l.Id == lensId);

                    if (len == null)
                    {
                        continue;
                    }

                    //check compatible with cameras
                    var compatibleWith = len.CompatibleWith;


                    if (compatibleWith != primaryCameraMake && compatibleWith != secondaryCameraMake)
                    {
                        continue;
                    }

                    validLens.Add(len);
                }

                //create photographer

                var photographer = new Photographer()
                {
                    FirstName = photographerDto.FirstName,
                    LastName  = photographerDto.LastName,
                    Lens      = validLens,
                    Phone     = photographerDto.Phone
                };


                validPhotographers.Add(photographer);

                sb.AppendLine(string.Format(SuccessMessage, $"{photographerDto.FirstName} {photographerDto.LastName} | Lenses:{validLens.Count}"));
            }

            context.Photographers.AddRange(validPhotographers);
            context.SaveChanges();

            var result = sb.ToString();

            return(result);
        }
        public static string ImportWorkshops(PhotographyDbContext context, string xmlString)
        {
            var serializer   = new XmlSerializer(typeof(WorkshopDto[]), new XmlRootAttribute("workshops"));
            var workshopDtos = (WorkshopDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));


            var validWorkshops         = new List <Workshop>();
            var photographersWorkshops = new List <PhotographersWorkshop>();

            var sb = new StringBuilder();

            foreach (var workshopDto in workshopDtos)
            {
                if (!IsValid(workshopDto))
                {
                    sb.AppendLine(FailureMessage);
                    continue;
                }

                var name         = workshopDto.Name;
                var location     = workshopDto.Location;
                var price        = workshopDto.PricePerParticipant;
                var trainerNames = workshopDto.Trainer.Split();
                var trainer      = context.Photographers.FirstOrDefault(p => p.FirstName == trainerNames[0] && p.LastName == trainerNames[1]);

                //create workshop
                var workshop = new Workshop()
                {
                    Name                = name,
                    Location            = location,
                    PricePerParticipant = price,
                    Trainer             = trainer
                };

                //check dates
                var startDateAsString = workshopDto.StartDate;
                if (startDateAsString != null)
                {
                    //   DateTime startDate = DateTime.ParseExact(startDateAsString, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
                    DateTime startDate = DateTime.Parse(startDateAsString);
                    workshop.StartDate = startDate;
                }

                var endDateAsString = workshopDto.EndDate;
                if (endDateAsString != null)
                {
                    //DateTime endDate = DateTime.ParseExact(endDateAsString, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
                    DateTime endDate = DateTime.Parse(endDateAsString);
                    workshop.EndDate = endDate;
                }

                /*26-10-2017
                 * EFCore 2 has unclear error message when performing insert involving many - to - many join table. The property 'prop' on entity type 'someType' has a temporary value.. #10165
                 *  Closed
                 * Exception after upgrading the EF Core package to 2.0.1 #10360
                 */
                /*
                 * //add participants if exists
                 *
                 *
                 * if (workshopDto.Participants.Length>0)
                 * {
                 *  var participantsDtos = workshopDto.Participants;
                 *
                 *  var participants = new List<Photographer>();
                 *
                 *  foreach (var participantsDto in participantsDtos)
                 *  {
                 *      var photographer = context.Photographers.FirstOrDefault(p => p.FirstName == participantsDto.FirstName && p.LastName == participantsDto.LastName);
                 *      participants.Add(photographer);
                 *  }
                 *
                 *  //create photographersWorkshops
                 *
                 *  foreach (var photographer in participants)
                 *  {
                 *      var pw = new PhotographersWorkshop()
                 *      {
                 *          Photographer = photographer,
                 *          Workshop = workshop
                 *      };
                 *
                 *      photographersWorkshops.Add(pw);
                 *      //add pwlist to workshop
                 *      workshop.Participants.Add(pw);
                 *
                 *  }*/


                validWorkshops.Add(workshop);
                sb.AppendLine(string.Format(SuccessMessage, workshopDto.Name));
            }

            context.Workshops.AddRange(validWorkshops);
            // context.PhotorgaphersWorkshops.AddRange(photographersWorkshops);
            context.SaveChanges();

            var result = sb.ToString();

            return(result);
        }
 public IndexdescriptionService(PhotographyDbContext dbContext, IMapper mapper) : base(dbContext)
 {
     _mapper = mapper;
 }