예제 #1
0
 public void OnAuthorUpdated(Author author)
 {
     if (AuthorUpdated != null)
     {
         AuthorUpdated(new SingleItemEventArgs<Author>(author));
     }
 }
예제 #2
0
 public void OnlyLastName()
 {
     Author a = new Author();
     a.Person = new Person { Last = "Bond", Degree = "Licensed to Kill" };
     Assert.Equal("Bond, Licensed to Kill", a.Person.ToString());
     Assert.Equal("^Bond^^^^^Licensed to Kill", a.Person.ToXCN());
 }
        public IHttpActionResult PostAuthor(AuthorBindingModel authorBinding)
        {
            if (authorBinding == null)
            {
                return this.BadRequest("Input is empty.");
            }

            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var author = new Author
                             {
                                 FirstName = authorBinding.FirstName, 
                                 LastName = authorBinding.LastName
                             };

            this.Data.Authors.Create(author);
            this.Data.SaveChanges();

            var authorView = new AuthorViewModel
                                 {
                                     FirstName = author.FirstName, 
                                     LastName = author.LastName
                                 };

            return this.Ok(authorView);
        }
예제 #4
0
 public void FullMonty()
 {
     Author a = new Author();
     a.Person = new Person { Prefix = "Sir", First = "Tom", MI = "A", Last = "Jones", Suffix = "Jr.", Degree = "M.D., PhD, JD, PharmD" };
     Assert.Equal("Sir Tom A Jones, Jr., M.D., PhD, JD, PharmD", a.Person.ToString());
     Assert.Equal("^Jones^Tom^A^Jr.^Sir^M.D., PhD, JD, PharmD", a.Person.ToXCN());
 }
예제 #5
0
 public void Celebrity()
 {
     Author a = new Author();
     a.Person = new Person { Prefix = "Lady", First = "Gaga", Degree = "M.A." };
     Assert.Equal("Lady Gaga, M.A.", a.Person.ToString());
     Assert.Equal("^^Gaga^^^Lady^M.A.", a.Person.ToXCN());
 }
예제 #6
0
 public void MD()
 {
     Author a = new Author();
     a.Person = new Person { First = "Tom", Last = "Jones", Degree = "M.D." };
     Assert.Equal("Tom Jones, M.D.", a.Person.ToString());
     Assert.Equal("^Jones^Tom^^^^M.D.", a.Person.ToXCN());
 }
예제 #7
0
 public void AuthorWithMI()
 {
     Author a = new Author();
     a.Person = new Person { First="Tom", Last="Jones", MI="A" };
     Assert.Equal("Tom A Jones", a.Person.ToString());
     Assert.Equal("^Jones^Tom^A^^^", a.Person.ToXCN());
 }
예제 #8
0
 public void SimpleAuthor()
 {
     Author a = new Author();
     a.Person = new Person { First = "Tom", Last = "Jones" };
     Assert.Equal("Tom Jones", a.Person.ToString());
     Assert.Equal("^Jones^Tom^^^^", a.Person.ToXCN());
 }
예제 #9
0
 protected void Bt_login_Click(object sender, EventArgs e)
 {
     string authorID = txtUserID.Text;
     string authorPwd = txtUserPwd.Text;
     Author author = new Author();
     int flag = author.Login(authorID, authorPwd);
     if (flag == 1)
     {
         author.LoadInfo(authorID);
         Response.Cookies["userID"].Value = txtUserID.Text;
         Response.Cookies["userID"].Expires = DateTime.Now.AddDays(7);
         Response.Cookies["userName"].Value = author.authorName;
         Response.Cookies["userName"].Expires = DateTime.Now.AddDays(7);
         Response.Cookies["userPwd"].Value = txtUserPwd.Text;
         Response.Cookies["userPwd"].Expires = DateTime.Now.AddDays(7);
         Response.Redirect("main.htm");
     }
     else if (flag == -1)
     {
         Response.Write("<Script Language=JavaScript>alert(\"密码错误!\")</Script>");
     }
     else if (flag == 0)
     {
         Response.Write("<Script Language=JavaScript>alert(\"用户名不存在!\")</Script>");
     }
 }
예제 #10
0
    protected void Bt_Update_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Author author = new Author();
            author.LoadInfo(Request.Cookies["userID"].Value.ToString());
            if (txtPwdold.Text == author.authorPwd)
            {
                string xwhere = "where authorID=" + SQLString.GetQuotedString(Request.Cookies["userID"].Value.ToString());
                Hashtable ht = new Hashtable();
                ht.Add("authorPwd", SQLString.GetQuotedString(txtPwdnew.Text));
                if (author.Update(ht, xwhere))
                {
                    Response.Write("<Script Language=JavaScript>alert(\"密码修改成功!\")</Script>");

                }
                else
                {
                    Response.Write("<Script Language=JavaScript>alert(\"密码修改失败!\")</Script>");
                }

            }
            else
            {
                Response.Write("<Script Language=JavaScript>alert(\"旧密码错误!\")</Script>");

            }
        }
    }
예제 #11
0
        public void UpdateEntity_ShouldUpdateEntity()
        {
            // arrange
            var obj = new Author { Uid = AuthorUid};
            var storageObj = new Author { Uid = AuthorUid };
            var stub = new FakeRepository(new Dictionary<Type, IEnumerable<IEntity>>
            {
                {typeof (Author), new[] {new Author {Uid = Guid.NewGuid()}, storageObj}}
            });
            var updateCommand = new UpdateCommand<Author>();

            // act
            obj.Name = "foo bar";
            obj.About = "sooo some foor";
            obj.Company = "rook";
            obj.SemanticUid = "foo_bar_rook";
            updateCommand.Entity = obj;
            updateCommand.Execute(stub);

            // assert
            Assert.AreEqual(obj.Name, storageObj.Name);
            Assert.AreEqual(obj.About, storageObj.About);
            Assert.AreEqual(obj.Company, storageObj.Company);
            Assert.AreEqual(obj.SemanticUid, storageObj.SemanticUid);
        }
예제 #12
0
 public Author DeleteAuthor(Author author)
 {
     var query = Ninject.Get<DeleteAuthorQuery>();
     query.Author = author;
     query.Execute();
     return author;
 }
예제 #13
0
        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            Stream str = e.Result;
            try
            {
                String eve = "author";
                XDocument loadedData = XDocument.Load(str);
                foreach (var item in loadedData.Descendants(eve))
                {

                    try
                    {
                        Author c = new Author();
                        c.name = item.Element("name").Value;
                        c.count = Convert.ToInt32(item.Element("count").Value);
                        c.likes = Convert.ToInt32(item.Element("voting").Value);
                        authors.Add(c);
                    }
                    catch (Exception ex)
                    {
                        //GoogleAnalytics.EasyTracker.GetTracker().SendException(ex.Message, false);
                    }
                }
                authorlistbox.ItemsSource = authors;
            }
            catch (System.Xml.XmlException ex)
            {
                MessageBox.Show("limited connectivity or invalid data.\nplease try again");
            }
        }
예제 #14
0
 public Author AddAuthor(Author author)
 {
     var query = Ninject.Get<InsertAuthorQuery>();
     query.Author = author;
     query.Execute();
     return author;
 }
예제 #15
0
        private void loadPopularAuthors()
        {
            StreamResourceInfo strm = Application.GetResourceStream(new Uri("getAllAuthors.xml", UriKind.Relative));
            try
            {
                String eve = "author";
                XDocument loadedData = XDocument.Load(strm.Stream);
                foreach (var item in loadedData.Descendants(eve))
                {

                    try
                    {
                        Author c = new Author();
                        c.name = item.Element("name").Value;
                        c.count = Convert.ToInt32(item.Element("count").Value);
                        c.likes = Convert.ToInt32(item.Element("voting").Value);
                        authors.Add(c);
                    }
                    catch (Exception ex)
                    {
                        //GoogleAnalytics.EasyTracker.GetTracker().SendException(ex.Message, false);
                    }
                }
                authorlistbox.ItemsSource = authors;
            }
            catch (Exception ex)
            {
               // GoogleAnalytics.EasyTracker.GetTracker().SendException(ex.Message, false);
            }
        }
예제 #16
0
    protected void Bt_update_Click(object sender, EventArgs e)
    {
        string userID = Request.Cookies["userID"].Value.ToString();
        string where = " where authorID=" + SQLString.GetQuotedString(userID);
        Hashtable ht = new Hashtable();
        ht.Add("authorName", SQLString.GetQuotedString(txtName.Text));
        ht.Add("authorSex", SQLString.GetQuotedString(rblSex.SelectedValue));
        ht.Add("authorBirth", SQLString.GetQuotedString(txtBirth.Text));
        ht.Add("authorRegion", SQLString.GetQuotedString(txtRegion.Text));
        ht.Add("authorMail", SQLString.GetQuotedString(txtMail.Text));
        ht.Add("authorPost", SQLString.GetQuotedString(TxtPostcode.Text));
        ht.Add("authorDegree", SQLString.GetQuotedString(ddlDegree.SelectedValue));
        ht.Add("authorMajor", SQLString.GetQuotedString(txtMajor.Text));
        ht.Add("authorTitle", SQLString.GetQuotedString(txtTitle.Text));
        ht.Add("authorJob", SQLString.GetQuotedString(txtJob.Text));
        ht.Add("authorCompany", SQLString.GetQuotedString(txtCompany.Text));
        ht.Add("authorPhone", SQLString.GetQuotedString(txtPhone.Text));
        ht.Add("authorAddress", SQLString.GetQuotedString(txtAddress.Text));
        ht.Add("authorInfo", SQLString.GetQuotedString(txtInfo.Text));

        Author author = new Author();
        if (author.Update(ht, where))
        {
            Response.Write("<Script Language=JavaScript>alert(\"修改成功!\")</Script>");

        }
    }
예제 #17
0
        public List<Photo> Read(int page = 1)
        {
            var photos = new List<Photo>();
            var flickr = new FlickrNet.Flickr(_apiToken, _secretKey);
            
            PhotoCollection col = flickr.FavoritesGetPublicList(_userid, DateTime.Now.AddYears(-10), DateTime.Now,
                                                                PhotoSearchExtras.All, page, _perPage);

            foreach (FlickrNet.Photo item in col)
            {
                var author = new Author
                    {
                        Name = item.OwnerName,
                        ID = item.UserId,
                        URL = string.Format("https://www.flickr.com/photos/{0}/", item.UserId)
                    };
                photos.Add(new Photo
                    {
                        Title = item.Title,
                        URL = item.WebUrl,
                        Path = item.DoesLargeExist ? item.LargeUrl : item.MediumUrl,
                        PublishedDate = item.DateTaken,
                        Author = author
                    });
            }
            return photos;
        }
예제 #18
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            Console.InputEncoding = Encoding.UTF8;

            int num = 153;
            Ex001_InformationOfNumber infoNum = new Ex001_InformationOfNumber(num);
            Console.WriteLine(infoNum.ToString());

            dynamic lastName = "Chand";
            dynamic dynAuthor = new Author();
            Console.WriteLine(dynAuthor.FullNameMethod(lastName));

            string strShow = String.Format("    Space     of     string:     {0}    ", ExerciseString.nbOfSpace(infoNum.ToString()));
            Console.WriteLine(strShow);
            ExerciseString.removeSpaceReduntion(ref strShow);
            Console.WriteLine(strShow);
            ExerciseString.concatString(ref strShow, "abc");
            Console.WriteLine(strShow);

            ExerciseString.stringLower(ref strShow);
            Console.WriteLine(strShow);

            //ExerciseString.stringUpper(ref strShow);
            //Console.WriteLine(strShow);

            ExerciseString.upperCharacterStartWord(ref strShow);
            Console.WriteLine(strShow);

            ExerciseString.upperAndLowerCharacterAlternate(ref strShow);
            Console.WriteLine(strShow);

            Console.ReadKey();
        }
예제 #19
0
        // PUT api/Authors/5
        public async Task<IHttpActionResult> PutAuthor(int id, Author author)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != author.Id)
            {
                return BadRequest();
            }

            db.Entry(author).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AuthorExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
예제 #20
0
 public DataObjectOperationResult CommitChanges(AuthorFormModel postedData)
 {
     Mapper.CreateMap<AuthorFormModel, Author>();
     var author = new Author(Db);
     Mapper.Map<AuthorFormModel, Author>(postedData, author);
     return author.Save();
 }
예제 #21
0
 protected void Bt_register_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         Hashtable ht = new Hashtable();
         ht.Add("authorID", SQLString.GetQuotedString(txtID.Text));
         ht.Add("authorPwd", SQLString.GetQuotedString(txtPwd.Text));
         ht.Add("authorName", SQLString.GetQuotedString(txtName.Text));
         ht.Add("authorSex", SQLString.GetQuotedString(rblSex.SelectedValue));
         ht.Add("authorBirth", SQLString.GetQuotedString(txtBirth.Text));
         ht.Add("authorRegion", SQLString.GetQuotedString(txtRegion.Text));
         ht.Add("authorPost", SQLString.GetQuotedString(TxtPostcode.Text));
         ht.Add("authorMail", SQLString.GetQuotedString(txtMail.Text));
         ht.Add("authorDegree", SQLString.GetQuotedString(dddlDegree.SelectedValue));
         ht.Add("authorMajor", SQLString.GetQuotedString(txtMajor.Text));
         ht.Add("authorTitle", SQLString.GetQuotedString(txtTitle.Text));
         ht.Add("authorJob", SQLString.GetQuotedString(txtJob.Text));
         ht.Add("authorCompany", SQLString.GetQuotedString(txtCompany.Text));
         ht.Add("authorPhone", SQLString.GetQuotedString(txtPhone.Text));
         ht.Add("authorAddress", SQLString.GetQuotedString(txtAddress.Text));
         ht.Add("authorInfo", SQLString.GetQuotedString(txtInfo.Text));
         Author author = new Author();
         if (author.Add(ht))
         {
             Response.Write("<script>alert('注册成功!');window.location='login.aspx';</script>");
         }
         else
         {
             Response.Write("<Script Language=JavaScript>alert(\"注册失败!\")</Script>");
         }
     }
 }
예제 #22
0
        public static Author GetRandomAuthor()
        {
            Random lRandom = new Random();
            var lAuthor = new Author();
            if (lRandom.Next() % 6 > 0)
            {
                lAuthor.FirstName = new string('K', lRandom.Next() % 20 + 1);
            }
            if (lRandom.Next() % 5 == 0)
            {
                lAuthor.MiddleName = new string('A', lRandom.Next() % 20 + 1);
            }
            if (lRandom.Next() % 10 > 0)
            {
                lAuthor.LastName = new string('B', lRandom.Next() % 20 + 1);
            }
            if (lRandom.Next() % 3 > 0)
            {
                lAuthor.Born = new DateTime(lRandom.Next() % 100 + 1880, lRandom.Next() % 12 + 1, lRandom.Next() % 28 + 1);
            }
            if (lRandom.Next() % 6 > 0)
            {
                lAuthor.Dead = new DateTime(lRandom.Next() % 60 + 1920, lRandom.Next() % 12 + 1, lRandom.Next() % 28 + 1);
            }
            if (lRandom.Next() % 8 > 0)
            {
                switch (lRandom.Next() % 2)
                {
                    case 0: lAuthor.Genre = Author.Sex.Female; break;
                    case 1: lAuthor.Genre = Author.Sex.Male; break;
                }
            }

            return lAuthor;
        }
예제 #23
0
        public void Create5NewPageSuccessfulTest()
        {
            using (UnitOfWork uow = new UnitOfWork())
            {
                PageRepository pr = new PageRepository(uow.Current);
                BlogRepository br = new BlogRepository(uow.Current);

                Blog.Model.Domain.Entities.Blog b = new Blog.Model.Domain.Entities.Blog("Nombe blog", "Desc blog");

                Category c = new Category("Categoria 1", "Desc 1");
                Author a = new Author("Nome autore", "Cognome autore", Convert.ToDateTime("27/12/1987"), "*****@*****.**", true, "pass", b);

                Page p1 = new Page("Nome pagina 1", "descr pagine", DateTime.Now, "test", a, b, c);
                Page p2 = new Page("Nome pagina 2", "descr pagine", DateTime.Now, "test", a, b, c);
                Page p3 = new Page("Nome pagina 3", "descr pagine", DateTime.Now, "test", a, b, c);
                Page p4 = new Page("Nome pagina 4", "descr pagine", DateTime.Now, "test", a, b, c);
                Page p5 = new Page("Nome pagina 5", "descr pagine", DateTime.Now, "test", a, b, c);

                br.Save(b);
                pr.Save(p1);
                pr.Save(p2);
                pr.Save(p3);
                pr.Save(p4);
                pr.Save(p5);

                uow.Commit();
            }
        }
        public void MakePersistent_BookTitle_AddsBookTitleToRepository()
        {
            var authors = new Author[] {new Author("Jeffery","Palermo"),
                                        new Author("Ben","Scheirman"),
                                        new Author("Jimmy","Bogard")};

            //Mock a BookTitle
            var mockBookTitle = new Mock<BookTitle>();
            mockBookTitle.Setup(book => book.Title).Returns("ASP.NET MVC 2 in Action");
            mockBookTitle.Setup(book => book.Authors).Returns(new List<Author>(authors));
            mockBookTitle.Setup(book => book.Publisher).Returns(new Publisher("Manning"));

            //Mock a BookTitleRepository
            var mockBookTitleRepository = new Mock<IBookTitleRepository>();
            mockBookTitleRepository
                .Setup(bookTitleRepository => bookTitleRepository.MakePersistent(mockBookTitle.Object))
                .Returns(mockBookTitle.Object);

            //Act
            var persistentBookTitle = mockBookTitleRepository.Object.MakePersistent(mockBookTitle.Object);

            //Asserts
            Assert.NotNull(persistentBookTitle);
            Assert.Equal<string>(persistentBookTitle.Title, "ASP.NET MVC 2 in Action");
            Assert.NotNull(persistentBookTitle.Publisher);
            Assert.Equal<string>(persistentBookTitle.Publisher.Name, "Manning");
            Assert.NotEmpty(persistentBookTitle.Authors);
        }
예제 #25
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     bool isAlreadyExists;
     var author = new Author
     {
         Name = Name.Text,
         Surname = Surname.Text
     };
     using (var context = new BookerContext())
     {
         isAlreadyExists = context.Authors.FirstOrDefault(x => x.Name == author.Name && x.Surname == author.Surname) != null;
         if (!isAlreadyExists)
         {
             context.Authors.Add(author);
             context.SaveChanges();
         }
     }
     if (isAlreadyExists)
     {
         Response.Redirect(Request.Url.AbsoluteUri.Substring(0,
             Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count()) + "?authorAction=exist");
     }
     else
     {
         Response.Redirect(Request.Url.AbsoluteUri.Substring(0,
             Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count()) + "?authorAction=add");
     }
 }
예제 #26
0
 private static Author CreateAuthorWithPosts(string expectedName, int postCount)
 {
     var author = new Author {Name = expectedName};
     author.Posts
         .AddRange(Enumerable.Repeat(1, postCount)
             .Select(i => new Post()));
     return author;
 }
예제 #27
0
 public AuthorPanel()
 {
     InitializeComponent();
     authorTextsListBox.ItemsSource = _outputCollection;
     Loaded += ((o, e) => UpdateView(false));
     Unloaded += ((o, e) => { MainWindow.GetSettings().PropertyChanged -= SettingPropertyChanged; });
     _author = null;
 }
예제 #28
0
        public void should_create_new_author_with_initial_post()
        {
            var author = new Author{Name = "Bob"};

            blogEngine.AddAuthor(author);

            dataStorage.AssertWasCalled(_ => _.InsertOnSubmit(author));
            dataStorage.AssertWasCalled(_ => _.SubmitChanges());
        }
예제 #29
0
 private AuthorPanel CreateAuthorPanel(Author author, int top)
 {
     return new AuthorPanel(author)
            {
                Top = top,
                Left = 0,
                Width = panelAuthors.Width,
                Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
            };
 }
예제 #30
0
 public static AuthorModel ConvertToModel(Author author)
 {
     return new AuthorModel()
     {
         Id = author.Id,
         First_name = author.First_name,
         Last_name = author.Last_name,
         Country = author.Country
     };
 }
예제 #31
0
파일: R.cs 프로젝트: catahoc/Ktoto.Neprav
 public static void Commented(Author author, Theme theme, Comment comment)
 {
     AuthorHasComments.ParentReceivesChild(author, comment);
     ThemeHasComments.ParentReceivesChild(theme, comment);
 }
예제 #32
0
        public static string ImportAuthors(BookShopContext context, string jsonString)
        {
            StringBuilder sb = new StringBuilder();

            var authorsDtos = JsonConvert.DeserializeObject <ImportAuthorDto[]>(jsonString);

            var authors = new List <Author>();

            foreach (var authorDto in authorsDtos)
            {
                if (!IsValid(authorDto))
                {
                    sb.Append(ErrorMessage + Environment.NewLine);
                    continue;
                }

                if (authors.Any(a => a.Email == authorDto.Email))
                {
                    sb.Append(ErrorMessage + Environment.NewLine);
                    continue;
                }

                Author author = new Author
                {
                    FirstName = authorDto.FirstName,
                    LastName  = authorDto.LastName,
                    Email     = authorDto.Email,
                    Phone     = authorDto.Phone,
                };

                foreach (var bookDto in authorDto.Books)
                {
                    if (!bookDto.BookId.HasValue)
                    {
                        continue;
                    }
                    Book book = context
                                .Books
                                .FirstOrDefault(b => b.Id == bookDto.BookId);

                    if (book == null)
                    {
                        continue;
                    }
                    author.AuthorsBooks.Add(new AuthorBook
                    {
                        Author = author,
                        Book   = book
                    });

                    if (author.AuthorsBooks.Count == 0)
                    {
                        sb.Append(ErrorMessage + Environment.NewLine);
                        continue;
                    }

                    authors.Add(author);
                    sb.Append(String.Format(SuccessfullyImportedAuthor, $"{author.FirstName} {author.LastName}", author.AuthorsBooks.Count) + Environment.NewLine);
                }
            }
            context.Authors.AddRange(authors);
            context.SaveChanges();

            return(sb.ToString().TrimEnd());
        }
        protected override void Seed(BookShopContext context)
        {
            if (context.Books.Any())
            {
                return;
            }

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            using (var reader = new StreamReader("authors.txt"))
            {
                var line = reader.ReadLine();
                line = reader.ReadLine();
                var    data   = new string[2];
                Author author = new Author();

                while (line != null)
                {
                    data = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    author = new Author()
                    {
                        FirstName = data[0],
                        LastName  = data[1]
                    };

                    context.Authors.Add(author);

                    line = reader.ReadLine();
                }
            }

            context.SaveChanges();

            using (var reader = new StreamReader("categories.txt"))
            {
                var line = reader.ReadLine();
                line = reader.ReadLine();
                Category category = new Category();

                while (line != null)
                {
                    category = new Category()
                    {
                        Name = line
                    };

                    context.Categories.Add(category);

                    line = reader.ReadLine();
                }
            }

            context.SaveChanges();

            using (var reader = new StreamReader("books.txt"))
            {
                var random = new Random();
                var line   = reader.ReadLine();
                line = reader.ReadLine();
                while (line != null)
                {
                    var authors        = context.Authors.ToList();
                    var data           = line.Split(new[] { ' ' }, 6);
                    var authorIndex    = random.Next(0, authors.Count);
                    var author         = authors[authorIndex];
                    var edition        = (EditionType)int.Parse(data[0]);
                    var releaseDate    = DateTime.ParseExact(data[1], "d/M/yyyy", CultureInfo.InvariantCulture);
                    var copies         = int.Parse(data[2]);
                    var price          = decimal.Parse(data[3]);
                    var ageRestriction = (AgeRestriction)int.Parse(data[4]);
                    var title          = data[5];

                    context.Books.Add(new Book()
                    {
                        Author         = author,
                        Edition        = edition,
                        ReleaseDate    = releaseDate,
                        Copies         = copies,
                        Price          = price,
                        AgeRestriction = ageRestriction,
                        Title          = title
                    });

                    line = reader.ReadLine();
                }
            }

            foreach (var book in context.Books)
            {
                var rnd             = new Random();
                var categoriesCount = rnd.Next(1, 10);

                for (int i = 0; i < categoriesCount; i++)
                {
                    book.Categories.Add(context.Categories.Find(rnd.Next(1, 7)));
                }
            }

            context.SaveChanges();
        }
 public async Task <Author> CreateAsync([FromBody] Author author)
 {
     return(await this._authorService.Create(author));
 }
예제 #35
0
        public static string ImportAuthors(BookShopContext context, string jsonString)
        {
            StringBuilder stringBuilder = new StringBuilder();

            ImportAuthorDto[] authorDtos = JsonConvert.DeserializeObject <ImportAuthorDto[]>(jsonString);

            //we create list of authors and validate the email before inport the data to the db
            List <Author> listOfAuthors = new List <Author>();

            foreach (var AuthorDto in authorDtos)
            {
                if (!IsValid(AuthorDto))
                {
                    stringBuilder.AppendLine(ErrorMessage);
                    continue;
                }

                if (listOfAuthors.Any(x => x.Email == AuthorDto.Email))
                {
                    stringBuilder.AppendLine(ErrorMessage);
                    continue;
                }

                //If we pass the first two validations, we can create an Author
                Author author = new Author
                {
                    FirstName = AuthorDto.FirstName,
                    LastName  = AuthorDto.LastName,
                    Email     = AuthorDto.Email,
                    Phone     = AuthorDto.Phone
                };

                foreach (var bookDto in AuthorDto.Books)
                {
                    if (!bookDto.Id.HasValue)
                    {
                        continue;
                    }

                    //We check if there is already a book with this ID in the db
                    Book book = context.Books.FirstOrDefault(b => b.Id == bookDto.Id);

                    if (book == null)
                    {
                        continue;
                    }

                    //If we pass the validations and there is valid book, we add it to the Author (it's many-to-many relationship)
                    author.AuthorsBooks.Add(new AuthorBook
                    {
                        Author = author,
                        Book   = book
                    });
                }

                //if the author has no books, we return error message

                if (author.AuthorsBooks.Count == 0)
                {
                    stringBuilder.AppendLine(ErrorMessage);
                    continue;
                }

                //Else, we have valid books and valid author, so we add them to the DB
                listOfAuthors.Add(author);

                stringBuilder.AppendLine(String.Format(SuccessfullyImportedAuthor, author.FirstName + " " + author.LastName, author.AuthorsBooks.Count));
            }

            //Finally, we add all the valid authors. EF will automatically add the mapped books to each author.
            context.Authors.AddRange(listOfAuthors);
            context.SaveChanges();

            return(stringBuilder.ToString().Trim());
        }
예제 #36
0
        public async Task <bool> Create(Author entity)
        {
            await _db.Authors.AddAsync(entity);

            return(await Save());
        }
예제 #37
0
        public async Task <IActionResult> PutAuthor([FromServices] OceanOfLettersContext _context, int id, Author author)
        {
            if (id != author.Id)
            {
                return(BadRequest());
            }

            _context.Entry(author).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AuthorExists(_context, id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
예제 #38
0
파일: R.cs 프로젝트: catahoc/Ktoto.Neprav
 public static void Disliked(Author author, LikeTarget target)
 {
     AuthorLikedManyThings.Unbind(author, target);
 }
예제 #39
0
 public BookBuilder WrittenBy(Author author)
 {
     this.book.Authors.Add(author);
     return(this);
 }
예제 #40
0
 public override string ToString()
 {
     return($"{PublishDate.ToShortDateString()} - \"{ArticleName}\" Автор: {Author.ToString()}");
 }
예제 #41
0
 public BlogPost(string relativeUri, string title, string content, DateTimeOffset published, Author author)
     : base(relativeUri, title, content, published, author)
 {
 }
예제 #42
0
        public JsonResult AddAuthor(int authorId)
        {
            Author author = ((IAuthorRepository) new RepositoryFactory().Create <Author>()).GetById(authorId);

            return(Json(author));
        }
예제 #43
0
 public Author CreateAuthor(Author author)
 {
     return(_authorService.CreateAuthor(author));
 }
예제 #44
0
 public async Task <bool> Update(Author entity)
 {
     _db.Authors.Update(entity);
     return(await Save());
 }
예제 #45
0
        public async Task <ActionResult <Author> > Store([FromServices] OceanOfLettersContext _context, Author author)
        {
            Response response = new Response();

            Validations.Validations validation = new Validations.Validations();

            try
            {
                response = validation.Validate(author);

                if (validation.IsValid)
                {
                    response = await new AuthorsApplication(_context).Store(author);
                }
                else
                {
                    response.BadRequest = true;
                }
            }
            catch (Exception ex)
            {
                response.Message    = ex.Message;
                response.BadRequest = true;
            }

            if (response.BadRequest)
            {
                return(BadRequest(response));
            }
            else
            {
                return(CreatedAtAction("GetAuthor", new { id = author.Id }, response));
            }
        }
예제 #46
0
 public async Task <bool> Delete(Author entity)
 {
     _db.Authors.Remove(entity);
     return(await Save());
 }
 public async Task <Author> UpdateAsync(Author author)
 {
     return(await this._authorService.Edit(author));
 }
예제 #48
0
 public void AddAuthor(Author author)
 {
     this.context.Authors.Add(author);
 }
 public AuthorBuilder()
 {
     _author = new Author();
 }
예제 #50
0
 public void DeleteAuthor(Author author)
 {
     this.context.Authors.Remove(author);
 }
예제 #51
0
 public ByAuthor(Author author) : base(post => post.AuthorId == author.Id)
 {
 }
예제 #52
0
 public void UpdateAuthor(Author author)
 {
     // no code in this implementation
 }
예제 #53
0
 public void UpdateAuthor(Author author)
 {
 }
예제 #54
0
파일: R.cs 프로젝트: catahoc/Ktoto.Neprav
 public static void CreatedTheme(Author author, Theme theme)
 {
     AuthorCreatedSomeThemes.ParentReceivesChild(author, theme);
 }
예제 #55
0
 public void Dispose()
 {
     Author.DeleteAll();
     Book.DeleteAll();
     Patron.DeleteAll();
 }
예제 #56
0
 public ActionResult addAuthor(Author author)
 {
     db.Authors.Add(author);
     db.SaveChanges();
     return(View(db.Authors.ToList()));
 }
예제 #57
0
 public virtual object DeepCopy()
 {
     return(new Paper(ArticleName, (Person)Author.DeepCopy(), PublishDate));
 }
예제 #58
0
 public Book(string title, string author, string content)
 {
     this.title   = new Title(title);
     this.author  = new Author(author);
     this.content = new Content(content);
 }
예제 #59
0
        public override IDeepCopyable CopyTo(IDeepCopyable other)
        {
            var dest = other as DocumentManifest;

            if (dest != null)
            {
                base.CopyTo(dest);
                if (MasterIdentifier != null)
                {
                    dest.MasterIdentifier = (Hl7.Fhir.Model.Identifier)MasterIdentifier.DeepCopy();
                }
                if (Identifier != null)
                {
                    dest.Identifier = new List <Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy());
                }
                if (Subject != null)
                {
                    dest.Subject = (Hl7.Fhir.Model.ResourceReference)Subject.DeepCopy();
                }
                if (Recipient != null)
                {
                    dest.Recipient = new List <Hl7.Fhir.Model.ResourceReference>(Recipient.DeepCopy());
                }
                if (Type != null)
                {
                    dest.Type = (Hl7.Fhir.Model.CodeableConcept)Type.DeepCopy();
                }
                if (Author != null)
                {
                    dest.Author = new List <Hl7.Fhir.Model.ResourceReference>(Author.DeepCopy());
                }
                if (CreatedElement != null)
                {
                    dest.CreatedElement = (Hl7.Fhir.Model.FhirDateTime)CreatedElement.DeepCopy();
                }
                if (SourceElement != null)
                {
                    dest.SourceElement = (Hl7.Fhir.Model.FhirUri)SourceElement.DeepCopy();
                }
                if (StatusElement != null)
                {
                    dest.StatusElement = (Code <Hl7.Fhir.Model.DocumentReferenceStatus>)StatusElement.DeepCopy();
                }
                if (DescriptionElement != null)
                {
                    dest.DescriptionElement = (Hl7.Fhir.Model.FhirString)DescriptionElement.DeepCopy();
                }
                if (Content != null)
                {
                    dest.Content = new List <Hl7.Fhir.Model.DocumentManifest.DocumentManifestContentComponent>(Content.DeepCopy());
                }
                if (Related != null)
                {
                    dest.Related = new List <Hl7.Fhir.Model.DocumentManifest.DocumentManifestRelatedComponent>(Related.DeepCopy());
                }
                return(dest);
            }
            else
            {
                throw new ArgumentException("Can only copy to an object of the same type", "other");
            }
        }
        public void ReturnTotalOrderPrice_WhenInvokedWithCorrectOrderId()
        {
            var mapperMock     = new Mock <IMapper>();
            var unitOfWorkMock = new Mock <IUnitOfWork>();


            var author1 = new Author {
                Id = 1, AuthorName = "Author1"
            };
            var book1 = new Book()
            {
                Id         = 1,
                Isbn       = "123",
                Title      = "C# Unleashed",
                Author     = author1,
                Price      = 10,
                CategoryId = 1
            };

            var book2 = new Book()
            {
                Id         = 2,
                Isbn       = "457123",
                Title      = "Java Unleashed",
                Author     = author1,
                Price      = 30,
                CategoryId = 1
            };

            var orderStatus = new OrderStatus()
            {
                Id = 1, OrderStatusDescription = "Status"
            };
            var books = new Collection <Book>()
            {
                book1, book2
            };

            var user1 = new BookstoreUser()
            {
                FirstName    = "Pesho",
                LastName     = "Petrov",
                Id           = 2,
                PasswordHash = "secret",
                Email        = "email",
                PhoneNumber  = "0888888",
                UserAddress  = "asd",
                UserName     = "******"
            };

            var order1 = new Order()
            {
                Books           = books,
                DeliveryAddress = "address",
                Id                 = 100,
                OrderStatusId      = 1,
                OrderStatus        = orderStatus,
                PhoneNumber        = user1.PhoneNumber,
                UserId             = 1,
                User               = user1,
                OrderCompletedTime = null,
                ReceivedOrderTime  = null
            };



            mapperMock.Setup(x => x.Map <List <OrderViewModel> >(It.IsAny <List <Order> >()))
            .Returns(new List <OrderViewModel>());



            unitOfWorkMock.Setup(x => x.Orders.GetById(100)).Returns(order1);

            var orderService = new OrderService(unitOfWorkMock.Object, mapperMock.Object);


            var orderId = 100;

            var sut = orderService.GetTotalOrderPrice(orderId);

            Assert.AreEqual(40, sut);
        }