Exemplo n.º 1
0
        public async Task DeleteQuestion_Success()
        {
            var question1 = new Question
            {
                QuestionId = 1,
                Content    = "This is ... car?",
                AnswerA    = "a",
                AnswerB    = "an",
                AnswerC    = "that",
                AnswerD    = "this",
                CorectAns  = "a"
            };

            var question2 = new Question
            {
                QuestionId = 2,
                Content    = "What your name?",
                AnswerA    = "Mr Nam",
                AnswerB    = "a",
                AnswerC    = "an",
                AnswerD    = "her",
                CorectAns  = "Mr Nam"
            };

            var list = new List <Question>();

            list.Add(question1);
            list.Add(question2);

            await _questionRepository.AddRange(list);

            var questionService = new QuestionService(_questionRepository);

            var controller = new QuestionsController(questionService);

            //action
            var result = await controller.DeleteQuestion(1);

            //course

            result.Should().NotBeNull();

            var response    = Assert.IsType <OkObjectResult>(result.Result);
            var returnValue = Assert.IsType <Question>(response.Value);

            Assert.Equal(1, returnValue.QuestionId);
            Assert.Equal("This is ... car?", returnValue.Content);
            Assert.Equal("a", returnValue.AnswerA);
            Assert.Equal("an", returnValue.AnswerB);
            Assert.Equal("that", returnValue.AnswerC);
            Assert.Equal("this", returnValue.AnswerD);
            Assert.Equal("a", returnValue.CorectAns);

            var totalQuestion = await _questionRepository.GetAll();

            totalQuestion.Should().HaveCount(1);
        }
Exemplo n.º 2
0
        public static void ParseChannel(string filename)
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load(filename);

                var xmlNodeList = doc.SelectNodes("/tv/channel");
                var rand        = new Random();

                if (xmlNodeList != null)
                {
                    var channelRepo = new BaseRepository <Channel>();
                    var channelList = (from XmlNode node in xmlNodeList
                                       where node.Attributes != null
                                       let originId = node.Attributes["id"].Value.GetInt()
                                                      select new Channel
                    {
                        Name = node.FirstChild.InnerText,
                        Price = rand.Next(0, rand.Next(1, 5) * 10),
                        IsAgeLimit = rand.Next(0, 4) % 2 == 0,
                        OriginalId = originId
                    }).ToList();
                    channelRepo.AddRange(channelList);

                    MessageContainer.ChannelsLoadGood();
                }
                else
                {
                    MessageContainer.SomethingWrongInFileLoad();
                }
            }
            catch (DbEntityValidationException ex)
            {
                var sb = new StringBuilder();
                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.Append($"{failure.Entry.Entity.GetType()} failed validation\n");
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.Append($"- {error.PropertyName} : {error.ErrorMessage}");
                        sb.AppendLine();
                    }
                }
                throw new DbEntityValidationException("Entity Validation Failed - errors follow:\n" + sb, ex);
            }
            catch (Exception ex)
            {
                MessageContainer.SomethingWrongInChannelLoad(ex);
            }
        }
Exemplo n.º 3
0
        public static void ParseProgramm(string filename)
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load(filename);
                var xmlNodeList = doc.SelectNodes("/tv/programme");

                if (xmlNodeList != null)
                {
                    var rand = new Random();

                    var tvShowsRepo = new BaseRepository <TvShow>();
                    var channelsAll = new BaseRepository <Channel>(tvShowsRepo.ContextDb).GetAll().ToList();

                    var tvShowList = new List <TvShow>();

                    var progressBar = new ProgressForm();
                    progressBar.ShowDialog();
                    //id for progress bar
                    var id = 1;

                    //load channels to container
                    foreach (XmlNode node in xmlNodeList)
                    {
                        if (node.Attributes != null)
                        {
                            var channelOriginId = node.Attributes["channel"].Value.GetInt();
                            var shows           = new TvShow();
                            //{
                            shows.Name = node.FirstChild.InnerText;                                               //,
                            shows.Date = DateTime.ParseExact(node.Attributes["start"].Value,
                                                             "yyyyMMddHHmmss zzz", CultureInfo.InvariantCulture); //,
                            shows.IsAgeLimit          = rand.Next(0, 4) % 3 == 0;                                 //,
                            shows.CodeOriginalChannel = channelOriginId;                                          //,
                            shows.Channel             = channelsAll.Find(x => x.OriginalId == channelOriginId);
                            //};
                            tvShowList.Add(shows);
                        }
                        //count persents for progress bar
                        id++;
                        progressBar.ShowProgress(id, xmlNodeList.Count);
                    }

                    //-------------------------------------------------------------------------------------
                    //using BulkInsert approach to load big entity to DB (less than 0.5sec for 118000 entities)
                    //But, there is some problem:
                    //Channels in show link foreign key Channel_Id,
                    //but it is always '0' and Channels don't link with TvShow
                    //To utilize - tvShowsRepo.AddRange(tvShowList); - all in norm, but it takes too much time
                    //(more than 30 minutes)

                    //using (var ctx = tvShowsRepo.ContextDb)
                    //{
                    //    using (var transactionScope = new TransactionScope())
                    //    {
                    //        ctx.BulkInsert(tvShowList);
                    //        ctx.SaveChanges();
                    //        transactionScope.Complete();
                    //    }
                    //}

                    tvShowsRepo.AddRange(tvShowList);
                    //-------------------------------------------------------------------------------------

                    progressBar.Close();

                    MessageContainer.ProgrammsLoadGood();
                }
                else
                {
                    MessageContainer.SomethingWrongInFileLoad();
                }
            }
            catch (DbEntityValidationException ex)
            {
                var sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.Append($"{failure.Entry.Entity.GetType()} failed validation\n");
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.Append($"- {error.PropertyName} : {error.ErrorMessage}");
                        sb.AppendLine();
                    }
                }
                throw new DbEntityValidationException("Entity Validation Failed - errors follow:\n" + sb, ex);
            }
            catch (Exception ex)
            {
                MessageContainer.SomethingWrongInProgrammLoad(ex);
            }
        }
Exemplo n.º 4
0
        internal static void ParseFavouriteMedia(string xmlFileName, int currentUserId)
        {
            var doc = new XmlDocument();

            doc.Load(xmlFileName);
            var xmlChannelsNodeList = doc.SelectNodes("tv/channel");
            var xmlTvShowsNodeList  = doc.SelectNodes("tv/programme");

            var channelRepo = new BaseRepository <Channel>();
            var tvShowRepo  = new BaseRepository <TvShow>(channelRepo.ContextDb);

            if (channelRepo.GetAll().Any() == false)
            {
                MessageContainer.DisplayInfo("You can't load favourite media. Channels table is clear!!!" +
                                             Environment.NewLine + "Load base about channels first!!!", "Error");
                return;
            }

            if (tvShowRepo.GetAll().Any() == false)
            {
                MessageContainer.DisplayInfo("You can't load favourite media. TV programmers table is clear!!!" +
                                             Environment.NewLine + "Load base about TvShows first!!!", "Error");
                return;
            }

            var currentUser = new BaseRepository <User>(channelRepo.ContextDb)
                              .Get(u => u.Id == currentUserId).FirstOrDefault();

            var orderChanellList = new List <OrderChannel>();
            var userScheduleList = new List <UserSchedule>();

            if (xmlChannelsNodeList != null || xmlTvShowsNodeList != null)
            {
                var userIdInFile = xmlChannelsNodeList?.Item(0)?.ChildNodes[2].InnerText.GetInt();
                if (userIdInFile != currentUserId)
                {
                    MessageContainer.DisplayError("This file include not your favourite media!!! Sorry", "Error");
                    return;
                }

                foreach (XmlNode chaNode in xmlChannelsNodeList)
                {
                    try
                    {
                        if (chaNode.Attributes == null || chaNode.Attributes["favourite"].Value != "true")
                        {
                            MessageContainer.DisplayError("This file doesn't contains favourite media!!!", "WRONG FILE!");
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        MessageContainer.DisplayError("This file doesn't contains favourite media!!!", "WRONG FILE!");
                        return;
                    }
                }

                //check for right format saved *.xml file (for programmers)
                if (xmlTvShowsNodeList != null &&
                    xmlTvShowsNodeList.Cast <XmlNode>().Any(showNode => showNode.Attributes == null ||
                                                            showNode.Attributes["favourite"].Value != "true"))
                {
                    MessageContainer.DisplayError("This file doesn't contains favourite media!!!", "WRONG FILE!");
                    return;
                }

                //add saved channels to list
                orderChanellList.AddRange(from XmlNode channelNode in xmlChannelsNodeList
                                          select channelNode.ChildNodes[0].InnerText.GetInt()
                                          into chanOrigId
                                          select new OrderChannel
                {
                    Channel = channelRepo.Get(ch => ch.OriginalId == chanOrigId).FirstOrDefault(),
                    User    = currentUser
                });


                if (xmlTvShowsNodeList != null)
                {
                    //add saved tvShows to list
                    userScheduleList.AddRange(from XmlNode tvShowNode in xmlTvShowsNodeList
                                              select tvShowNode.ChildNodes[0].InnerText.GetInt()
                                              into showId
                                              select new UserSchedule
                    {
                        User   = currentUser,
                        TvShow = tvShowRepo.Get(sh => sh.Id == showId).FirstOrDefault(),
                        //DueDate = currentOrder?.DueDate ?? DateTime.Now.AddDays(7)
                    });
                }

                if (orderChanellList.Any(o => o.Channel == null) ||
                    userScheduleList.Any(sc => sc.TvShow == null))
                {
                    MessageContainer.DisplayInfo("Saved channels or TV-programmers don't meet current database.", "Info");
                }
                else
                {
                    var ordChannelRepo = new BaseRepository <OrderChannel>(channelRepo.ContextDb);
                    ordChannelRepo.AddRange(orderChanellList);

                    var schedRepo = new BaseRepository <UserSchedule>(channelRepo.ContextDb);
                    schedRepo.AddRange(userScheduleList);

                    MessageContainer.DisplayInfo("Saved schedule was read good.", "Info");
                }
            }

            else
            {
                MessageContainer.SomethingWrongInFileLoad();
            }
        }
Exemplo n.º 5
0
        ///// <summary>
        ///// 添加【必须先实例化才能使用】
        ///// </summary>
        ///// <param name="entity">数据实体</param>
        ///// <returns>添加后的记录ID</returns>
        //public virtual int Add(T entity) { return 0; }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entities">数据列表</param>
        /// <param name="isSave">是否立即保存</param>
        /// <returns></returns>
        public int AddRange(IEnumerable <T> entities, bool isSave = true)
        {
            return(_baseRepository.AddRange(entities, isSave));
        }
Exemplo n.º 6
0
 public void AddRange(List <T> item)
 {
     _baseRep.AddRange(item);
 }
Exemplo n.º 7
0
        public bool SaveProject(Project project, List <ProjectAmenitie> projectAmenitie, List <ProjectPlane> projectPlane, List <ProjectGallery> projectGallery,
                                HttpPostedFileBase Logo, HttpPostedFileBase CoverUrlUpload, HttpPostedFileBase MasterPlanImageUrlUpload, HttpPostedFileBase ConvenientLocationAttachmentUrlUpload,
                                HttpPostedFileBase[] AmenitieAttachmentUrlUpload, HttpPostedFileBase[] ProjectPlaneAttachments, HttpPostedFileBase[] ProjectGalleryAttachments, HttpPostedFileBase ConceptImageUrlUpload)
        {
            #region getting alreadly existing data before inserting the new ones
            var oldAmenitie = _repo.GetAllWhere <ProjectAmenitie>(x => x.ProjectId == project.Id);
            var oldPlanes   = _repo.GetAllWhere <ProjectPlane>(x => x.ProjectId == project.Id);
            var oldGallery  = _repo.GetAllWhere <ProjectGallery>(x => x.ProjectId == project.Id);
            #endregion

            var LogoUploadPath               = _fileService.UploadFile(MyConstants.UploadsPath, Logo);
            var CoverUrlUploadPath           = _fileService.UploadFile(MyConstants.UploadsPath, CoverUrlUpload);
            var MasterPlanImageUrlUploadPath = _fileService.UploadFile(MyConstants.UploadsPath, MasterPlanImageUrlUpload);
            var ConvenientLocationAttachmentUrlUploadPath = _fileService.UploadFile(MyConstants.UploadsPath, ConvenientLocationAttachmentUrlUpload);
            var ConceptImageUrlUploadPath = _fileService.UploadFile(MyConstants.UploadsPath, ConceptImageUrlUpload);


            project.Code               = project.TitleEn.Replace(" ", "");
            project.Logo               = LogoUploadPath != null ? LogoUploadPath.Path : project.Logo;
            project.CoverUrl           = CoverUrlUploadPath != null ? CoverUrlUploadPath.Path : project.CoverUrl;
            project.MasterPlanImageUrl = MasterPlanImageUrlUploadPath != null ? MasterPlanImageUrlUploadPath.Path : project.MasterPlanImageUrl;
            project.ConvenientLocationAttachmentUrl = ConvenientLocationAttachmentUrlUploadPath != null ? ConvenientLocationAttachmentUrlUploadPath.Path : project.ConvenientLocationAttachmentUrl;
            project.ConceptImageUrl = ConceptImageUrlUploadPath != null ? ConceptImageUrlUploadPath.Path : project.ConceptImageUrl;



            StringWriter ConceptArWriter                = new StringWriter();
            StringWriter ConceptEnWriter                = new StringWriter();
            StringWriter HomeConceptArWriter            = new StringWriter();
            StringWriter HomeConceptEnWriter            = new StringWriter();
            StringWriter MasterPlanArWriter             = new StringWriter();
            StringWriter MasterPlanEnWriter             = new StringWriter();
            StringWriter ConvenientLocationTextArWriter = new StringWriter();
            StringWriter ConvenientLocationTextEnWriter = new StringWriter();

            HttpUtility.HtmlDecode(project.ConceptAr, ConceptArWriter); project.ConceptAr             = ConceptArWriter.ToString();
            HttpUtility.HtmlDecode(project.ConceptEn, ConceptEnWriter); project.ConceptEn             = ConceptEnWriter.ToString();
            HttpUtility.HtmlDecode(project.HomeConceptAr, HomeConceptArWriter); project.HomeConceptAr = HomeConceptArWriter.ToString();
            HttpUtility.HtmlDecode(project.HomeConceptEn, HomeConceptEnWriter); project.HomeConceptEn = HomeConceptEnWriter.ToString();
            HttpUtility.HtmlDecode(project.MasterPlanAr, MasterPlanArWriter); project.MasterPlanAr    = MasterPlanArWriter.ToString();
            HttpUtility.HtmlDecode(project.MasterPlanEn, MasterPlanEnWriter); project.MasterPlanEn    = MasterPlanEnWriter.ToString();
            HttpUtility.HtmlDecode(project.ConvenientLocationTextAr, ConvenientLocationTextArWriter); project.ConvenientLocationTextAr = ConvenientLocationTextArWriter.ToString();
            HttpUtility.HtmlDecode(project.ConvenientLocationTextEn, ConvenientLocationTextEnWriter); project.ConvenientLocationTextEn = ConvenientLocationTextEnWriter.ToString();


            var AmenitieAttachmentUrlUploadPaths = _fileService.UploadFiles(MyConstants.UploadsPath, AmenitieAttachmentUrlUpload)?.Where(x => x != null)?.ToList();
            var ProjectPlaneAttachmentsPaths     = _fileService.UploadFiles(MyConstants.UploadsPath, ProjectPlaneAttachments)?.Where(x => x != null)?.ToList();
            var ProjectGalleryAttachmentsPaths   = _fileService.UploadFiles(MyConstants.UploadsPath, ProjectGalleryAttachments)?.Where(x => x != null)?.ToList();

            if (AmenitieAttachmentUrlUploadPaths != null && AmenitieAttachmentUrlUploadPaths.Count > 0)
            {
                var toloop = projectAmenitie.Where(x => x.IsImgChanged).ToList();
                for (int i = 0; i < toloop.Count; i++)
                {
                    toloop[i].AttachmentUrl = AmenitieAttachmentUrlUploadPaths.Count > i ? AmenitieAttachmentUrlUploadPaths[i].Path : string.Empty;
                }
            }

            if (ProjectPlaneAttachmentsPaths != null && ProjectPlaneAttachmentsPaths.Count > 0)
            {
                var toloop = projectPlane.Where(x => x.IsImgChanged).ToList();
                for (int i = 0; i < toloop.Count; i++)
                {
                    toloop[i].AttachmentUrl = ProjectPlaneAttachmentsPaths.Count > i ? ProjectPlaneAttachmentsPaths[i]?.Path : string.Empty;
                }
            }

            if (ProjectGalleryAttachmentsPaths != null && ProjectGalleryAttachmentsPaths.Count > 0)
            {
                var toloop = projectGallery.Where(x => x.IsImgChanged).ToList();
                for (int i = 0; i < toloop.Count; i++)
                {
                    toloop[i].ImageUrl = ProjectGalleryAttachmentsPaths.Count > i ? ProjectGalleryAttachmentsPaths[i].Path : string.Empty;
                }
            }

            project.ProjectAmenities = null;
            project.ProjectPlanes    = null;
            project.ProjectGallery   = null;

            var res = Save(project);

            if (projectAmenitie != null)
            {
                projectAmenitie.ForEach(x => x.ProjectId = project.Id);
            }
            if (projectPlane != null)
            {
                projectPlane.ForEach(x => x.ProjectId = project.Id);
            }
            if (projectGallery != null)
            {
                projectGallery.ForEach(x => x.ProjectId = project.Id);
            }

            if (projectAmenitie != null)
            {
                _repo.AddRange <ProjectAmenitie>(projectAmenitie);
            }
            if (projectPlane != null)
            {
                _repo.AddRange <ProjectPlane>(projectPlane);
            }
            if (projectGallery != null)
            {
                _repo.AddRange <ProjectGallery>(projectGallery);
            }

            var result = _repo.SaveChanges();
            if (result)
            {
                if (project.Id > 0)
                {
                    _repo.RemoveRange <ProjectAmenitie>(oldAmenitie);
                    _repo.RemoveRange <ProjectPlane>(oldPlanes);
                    _repo.RemoveRange <ProjectGallery>(oldGallery);
                    _repo.SaveChanges();
                }
            }

            return(res);
        }
 public void AddItems(List <T> items)
 {
     repository.AddRange(items);
 }
Exemplo n.º 9
0
        private void cbCheckAllChannels_CheckedChanged(object sender, EventArgs e)
        {
            if (cbCheckAllChannels.Checked)
            {
                lvChannelsList.BeginUpdate();
                for (var i = 0; i < lvChannelsList.Items.Count; i++)
                {
                    lvChannelsList.Items[i].Checked = true;
                }
                lvChannelsList.EndUpdate();

                var orderRepo      = new BaseRepository <Order>();
                var tvShowsRepo    = new BaseRepository <TvShow>(orderRepo.ContextDb);
                var channelsRepo   = new BaseRepository <Channel>(orderRepo.ContextDb);
                var ordChannelRepo = new BaseRepository <OrderChannel>(orderRepo.ContextDb);
                var user           = new BaseRepository <User>(orderRepo.ContextDb).Get(u => u.Id == CurrentUserId).FirstOrDefault();

                ordChannelRepo.Clear(CurrentUserId);

                var orderAllChann = channelsRepo.GetAll().ToList();
                var list          = orderAllChann.Select(channel => new OrderChannel
                {
                    Channel = channel, User = user
                }).ToList();

                ordChannelRepo.AddRange(list);

                var showByDateAndChannels = new List <TvShow>();
                foreach (var show in tvShowsRepo.GetAll())
                {
                    if ((int)show.Date.DayOfWeek == GetSelectedDay()
                        /*&& Math.Abs(x.Date.Day - DateTime.Now.Day) < 7*/)
                    {
                        showByDateAndChannels.Add(show);
                    }
                }

                ControlForShows?.Dispose();
                ControlForShows = new UcShowsList(CurrentUserId);
                ControlForShows.LoadShows(showByDateAndChannels);
                tabControl_Shows.SelectedTab.Controls.Add(ControlForShows);
            }
            else if (!cbCheckAllChannels.Checked)
            {
                //-------------------------------------------------------
                lvChannelsList.Items.Clear();

                var userSchRepo        = new BaseRepository <UserSchedule>();
                var deleteScheduleList = new List <UserSchedule>();
                //deleteSchedule = userSchRepo.Get(x => x.TvShow.Channel.OrderChannel. .User.Orders.FirstOrDefault(o => o.Id == CurrentOrderId).Id == CurrentOrderId).ToList();

                //-------------------------------------------------------

                var orderedChannRepo = new BaseRepository <OrderChannel>(userSchRepo.ContextDb);
                var deleteOrdChann   = orderedChannRepo.Get(x => x.Order == null &&
                                                            x.User.Id == CurrentUserId).ToList();

                foreach (var sched in userSchRepo.Get(uSch => uSch.User.Id == CurrentUserId).ToList())
                {
                    if (deleteOrdChann.Any(doch => doch.Channel.OriginalId == sched.TvShow.CodeOriginalChannel))
                    {
                        deleteScheduleList.Add(sched);
                    }
                }

                userSchRepo.RemoveRange(deleteScheduleList);
                orderedChannRepo.RemoveRange(deleteOrdChann);

                //-------------------------------------------------------
                LoadAllChannelsList();
                //-------------------------------------------------------

                ControlForShows?.Dispose();
                ControlForShows = new UcShowsList(CurrentUserId);
                tabControl_Shows.SelectedTab.Controls.Add(ControlForShows);
            }
        }