private void BtnSubmitClick(object sender, EventArgs e) { if (ValidateAll()) { Cursor.Current = Cursors.WaitCursor; if (txtPassword.Text != "") { SHA1 sha1 = SHA1.Create(); string hp = GetSha1Hash(sha1, txtPassword.Text); account.HashedPassword = hp; } account.FullName = txtFullName.Text; account.Email = txtEmail.Text; try { RentItProxy.UpdateAccountInfo(Credentials, account); var newCredentials = new AccountCredentials { UserName = account.UserName, HashedPassword = account.HashedPassword }; FireCredentialsChangeEvent(newCredentials); } catch { MessageBox.Show("Something went wrong :( Try again."); } SetFields(); Cursor.Current = Cursors.Default; } }
public void GetAllCustomerDataExceptionTestTwo() { RentItClient target = new RentItClient(); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; target.GetAllCustomerData(credentials); }
public void GetAllCustomerDataExceptionTestOne() { RentItClient target = new RentItClient(); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; target.GetAllCustomerData(credentials); }
public void GetAllCustomerDataTest() { RentItClient target = new RentItClient(); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; UserAccount actual = target.GetAllCustomerData(credentials); Assert.AreEqual("user21", actual.UserName); Assert.AreEqual("*****@*****.**", actual.Email); Assert.AreEqual("user21", actual.FullName); Assert.AreEqual("a1881c06eec96db9901c7bbfe41c42a3f08e9cb4", actual.HashedPassword); Assert.AreEqual(0, actual.Credits); }
public void AddCreditsTest() { RentItClient target = new RentItClient(); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; int oldCredits = target.GetAllCustomerData(credentials).Credits; uint addAmount = 100; bool expected = true; bool actual = target.AddCredits(credentials, addAmount); Assert.AreEqual(expected, actual); int newCredits = target.GetAllCustomerData(credentials).Credits; Assert.AreEqual(oldCredits + addAmount, newCredits); }
public void DeleteMediaTest1() { RentItClient target = new RentItClient(); int mediaId = 3; // Kraftwerk - The Robots AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; bool expected = true; bool actual = target.DeleteMedia(mediaId, credentials); Assert.AreEqual(expected, actual); var db = new RentItTestDatabase.RentItDatabaseDataContext(); // clean up var deletedMedia = (from m in db.Medias where m.id == mediaId select m).Single(); deletedMedia.active = true; db.SubmitChanges(); }
/// <author>Per Mortensen</author> public bool AddCredits(AccountCredentials credentials, uint addAmount) { ValidateCredentials(credentials); try { var db = new DatabaseDataContext(); IQueryable<User_account> userAccount = from user in db.User_accounts where user.user_name.Equals(credentials.UserName) select user; userAccount.Single().credit += (int)addAmount; db.SubmitChanges(); } catch (Exception) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input.")); } return true; }
/// <author>Per Mortensen</author> /// <summary> /// Determines whether the publisher account with the supplied credentials are authorized /// to change the media item's metadata. /// </summary> /// <param name="mediaId"> /// The id of the media item to be changed. /// </param> /// <param name="credentials"> /// The credentials of the publisher account. /// </param> /// <param name="db"> /// The database context to retrieve data from. /// </param> /// <param name="service"> /// The service on which the ValidateCredentials should be called. /// </param> /// <returns> /// true if the publisher can change the media, false otherwise. /// </returns> public static bool IsPublisherAuthorized(int mediaId, AccountCredentials credentials, DatabaseDataContext db, RentItService service) { try { service.ValidateCredentials(credentials); } catch (Exception) { return false; } if (!db.Medias.Exists(m => m.id == mediaId && m.active)) return false; // if the media with the specified id was not found Media media = (from m in db.Medias where m.id == mediaId && m.active select m).Single(); // find out whether this publisher is authorized to delete this media if (db.Publisher_accounts.Exists(p => p.user_name.Equals(credentials.UserName) && p.publisher_id == media.publisher_id)) return true; // if this publisher does not have permission to update the media return false; }
/// <author>Lars Toft Jacobsen</author> /// <summary> /// Rent media /// </summary> /// <param name="mediaId"></param> /// <param name="credentials"></param> /// <returns></returns> public bool RentMedia(int mediaId, AccountCredentials credentials) { // Throws an exceptions if the credentials are not valid. Account account = ValidateCredentials(credentials); if (account == null) { throw new FaultException<Exception>( new Exception("No credentials have been submitted.")); } var db = new DatabaseDataContext(); // Check if the requested media exists. if (!db.Medias.Exists(m => m.id == mediaId)) { throw new FaultException<Exception>( new Exception("The requested media does not exist")); } // Check if there already exist active rentals for the requested media. // If there already is an active rental of the media, through an exception // indicating so. if (db.Rentals.Exists( rental => rental.user_name.Equals(credentials.UserName) && rental.media_id == mediaId && rental.end_time > DateTime.Now)) { throw new FaultException<Exception>( new Exception("The requested media has already been rented.")); } try { var r = new RentItDatabase.Rental { user_name = account.UserName, media_id = mediaId, start_time = DateTime.Now, end_time = DateTime.Now.AddDays(14) }; // Get the account information for the requesting user var user = (from u in db.User_accounts where u.user_name.Equals(credentials.UserName) select u).Single(); // Get the media requested for rental. var rentedMedia = (from m in db.Medias where m.id == mediaId select m).Single(); // If the user has not enough credits if (user.credit < rentedMedia.price) { throw new FaultException<Exception>( new Exception("The specifed user does not have enough credits to rent this media.")); } // Update the user credit balance accordingly. user.credit = user.credit - rentedMedia.price; db.Rentals.InsertOnSubmit(r); db.SubmitChanges(); } catch (Exception) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input.")); } return true; }
/// <author>Jacob Rasmussen.</author> /// <summary> /// /// </summary> /// <param name="credentials"></param> public PublisherAccount GetAllPublisherData(AccountCredentials credentials) { Account account = ValidateCredentials(credentials); DatabaseDataContext db; Publisher_account publisherAccount; try { db = new DatabaseDataContext(); publisherAccount = (from publisher in db.Publisher_accounts where publisher.Account.user_name.Equals(account.UserName) select publisher).Single(); } catch (Exception) { throw new FaultException<Exception>( new Exception("Internal Error.")); } //Medias published by the given publisher account. IQueryable<RentItDatabase.Media> publishedMedias = from media in db.Medias where media.publisher_id.Equals(publisherAccount.publisher_id) && media.active select media; //Object containing the four lists of published items. Passed in with the new PublisherAccount-object. var mediaItems = Util.CompileMedias(publishedMedias, this); return new PublisherAccount(publisherAccount.user_name, publisherAccount.Account.full_name, publisherAccount.Account.email, publisherAccount.Account.password, publisherAccount.Publisher.title, mediaItems); }
/// <author>Kenneth Søhrmann</author> /// <summary> /// See the interface specification of the method in IRentIt.cs for documentation /// of this method. /// </summary> public Account ValidateCredentials(AccountCredentials credentials) { if (credentials == null) { throw new FaultException<ArgumentException>( new ArgumentException("The credentials-parameter is a null reference.")); } if (string.IsNullOrEmpty(credentials.UserName) || string.IsNullOrEmpty(credentials.HashedPassword)) { throw new FaultException<ArgumentException>( new ArgumentException("Invalid credentials.")); } DatabaseDataContext db; try { db = new DatabaseDataContext(); } catch (Exception) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input.")); } // The Account-instance to be retrieved from the database. RentItDatabase.Account account; try { account = (from ac in db.Accounts where ac.user_name.Equals(credentials.UserName) && ac.password.Equals(credentials.HashedPassword.ToUpper()) && ac.active select ac).Single(); } catch (Exception) { throw new FaultException<InvalidCredentialsException>( new InvalidCredentialsException(), "The submitted Credentials are invalid"); } // The credentials has successfully been evaluated, return account details to caller. return Account.ValueOf(account); }
/// <author>Per Mortensen</author> public bool UpdateMediaMetadata(MediaInfo newData, AccountCredentials credentials) { ValidateCredentials(credentials); DatabaseDataContext db; try { db = new DatabaseDataContext(); } catch (Exception) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input.")); } // Is publisher authorized for this media? if (!Util.IsPublisherAuthorized(newData.Id, credentials, db, this)) throw new FaultException<InvalidCredentialsException>( new InvalidCredentialsException("This user is not authorized to update this media.")); if (newData.Price < 0) { throw new FaultException<InvalidCredentialsException>( new InvalidCredentialsException("The price cannot be negative.")); } try { // find media based on id if (!db.Medias.Exists(m => m.id == newData.Id && m.active)) return false; Media media = (from m in db.Medias where m.id == newData.Id && m.active select m).Single(); // add genre to database if it doesn't exist and get its genre id int genreId = Util.AddGenre(newData.Genre, newData.Type); // update general metadata media.genre_id = genreId; media.price = newData.Price; media.release_date = newData.ReleaseDate; media.title = newData.Title; // update type-specific metadata switch (newData.Type) { case MediaType.Album: var newAlbumData = (AlbumInfo)newData; Album album = media.Album; album.album_artist = newAlbumData.AlbumArtist; album.description = newAlbumData.Description; break; case MediaType.Book: var newBookData = (BookInfo)newData; Book book = media.Book; book.author = newBookData.Author; book.pages = newBookData.Pages; book.summary = newBookData.Summary; break; case MediaType.Movie: var newMovieData = (MovieInfo)newData; Movie movie = media.Movie; movie.director = newMovieData.Director; movie.length = (int)newMovieData.Duration.TotalSeconds; movie.summary = newMovieData.Summary; break; case MediaType.Song: var newSongData = (SongInfo)newData; Song song = media.Song; song.artist = newSongData.Artist; song.length = (int)newSongData.Duration.TotalSeconds; break; } db.SubmitChanges(); } catch (Exception) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input.")); } return true; }
public void DeleteAccountTest() { var db = new RentItTestDatabase.RentItDatabaseDataContext(); RentItClient target = new RentItClient(); Account delAccount = new Account { UserName = "******", FullName = "Unit Testesen1", Email = "*****@*****.**", HashedPassword = "******" }; target.CreateNewUser(delAccount); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; bool expected = true; bool actual; actual = target.DeleteAccount(credentials); Assert.AreEqual(expected, actual); CleanupCreateUser(credentials.UserName); }
public void SubmitReviewTest() { RentItClient target = new RentItClient(); const string User = "******"; const int MediaId = 79; MediaReview review = new MediaReview { MediaId = MediaId, Rating = Rating.Three, ReviewText = "Bucketboy, yes.", Timestamp = DateTime.Now, UserName = User }; AccountCredentials credentials = new AccountCredentials { UserName = User, HashedPassword = "******" }; bool actual = target.SubmitReview(review, credentials); Assert.IsTrue(actual); this.SubmitReviewCleanup(User, MediaId); }
public void SubmitReviewExceptionTest() { RentItClient target = new RentItClient(); MediaReview review = new MediaReview { MediaId = 64, Rating = Rating.Three, ReviewText = "Bucket.", Timestamp = DateTime.Now, UserName = "******" }; AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; target.SubmitReview(review, credentials); target.SubmitReview(review, credentials); }
public void GetAllPublisherDataTest() { RentItClient target = new RentItClient(); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; PublisherAccount actual = target.GetAllPublisherData(credentials); Assert.AreEqual("publishCorp", actual.UserName); Assert.AreEqual("*****@*****.**", actual.Email); Assert.AreEqual("Publish Corp. Publishing Division", actual.FullName); Assert.AreEqual("7110EDA4D09E062AA5E4A390B0A572AC0D2C0220", actual.HashedPassword); Assert.AreEqual("Publish Corp. International", actual.PublisherName); }
public void DeleteMediaTest2() { RentItClient target = new RentItClient(); int mediaId = 2; // "House of Leaves" AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; target.DeleteMedia(mediaId, credentials); // InvalidCredentialsException }
public void GetAllPublisherDataExceptionTestOne() { RentItClient target = new RentItClient(); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; target.GetAllPublisherData(credentials); }
/// <author>Kenneth Søhrmann</author> /// <summary> /// See the interface specification of the method in IRentIt.cs for documentation /// of this method. /// </summary> public bool UpdateAccountInfo(AccountCredentials credentials, Account account) { if (account == null || credentials.UserName != account.UserName) { throw new FaultException<ArgumentException>( new ArgumentException("The account-parameter is null or usernames do not match up.")); } ValidateCredentials(credentials); // The credentials was successfully validated. // Retrieve the corresponding account from the database. try { var db = new DatabaseDataContext(); RentItDatabase.Account dbAccount = (from acc in db.Accounts where acc.user_name.Equals(credentials.UserName) && acc.active select acc).Single(); // Update the database with the new submitted data. if (account.FullName.Length > 0) dbAccount.full_name = account.FullName; string emailRegex = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"; if (account.Email.Length > 0) { if (Regex.IsMatch(account.Email, emailRegex)) dbAccount.email = account.Email; else throw new ArgumentException("The e-mail address was not valid."); } if (account.HashedPassword.Length > 0) dbAccount.password = account.HashedPassword; // Submit the changes to the database. db.SubmitChanges(); } catch (ArgumentException e) { throw new FaultException<ArgumentException>(e); } catch (Exception) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input.")); } return true; }
public void GetAllPublisherDataExceptionTestTwo() { RentItClient target = new RentItClient(); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; target.GetAllPublisherData(credentials); }
/// <author>Lars Toft Jacobsen</author> /// <summary> /// Delete user account from RentIt database. Actually the /// user is only invalidated by setting the active flag to false. /// </summary> /// <param name="credentials"></param> /// <returns></returns> public bool DeleteAccount(AccountCredentials credentials) { // validate credentials Account account = ValidateCredentials(credentials); if (account == null) return false; try { var db = new DatabaseDataContext(); RentItDatabase.Account acctResult = (from user in db.Accounts where user.user_name.Equals(account.UserName) select user).Single(); // set active flag acctResult.active = false; db.SubmitChanges(); } catch (Exception) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input.")); } return true; }
/// <summary> /// Handles change requests to the current global credentials of the application. /// </summary> /// <param name="sender">The sender of the request.</param> /// <param name="args">The arguments specifying the new credentials.</param> private void ChangeCredentials(object sender, CredentialsChangeArgs args) { credentials = args.Credentials; Cursor.Current = Cursors.WaitCursor; RentItUserControl nextScreen = new MainScreen { RentItProxy = this.rentItProxy, Credentials = this.credentials }; ChangeContent(sender, new ContentChangeArgs(nextScreen, "RentIt")); Cursor.Current = Cursors.Default; TopBar.Credentials = this.credentials; }
/// <author>Per Mortensen</author> public bool DeleteMedia(int mediaId, AccountCredentials credentials) { ValidateCredentials(credentials); DatabaseDataContext db; try { db = new DatabaseDataContext(); } catch (Exception) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input.")); } try { // find media based on id Media media = (from m in db.Medias where m.id == mediaId && m.active select m).Single(); // Is publisher authorized for this media? if (!Util.IsPublisherAuthorized(mediaId, credentials, db, this)) throw new FaultException<InvalidCredentialsException>( new InvalidCredentialsException("This user is not authorized to delete this media.")); // if refs to media in rentals/reviews only mark inactive if (db.Reviews.Exists(r => r.media_id.Equals(mediaId)) || db.Rentals.Exists(r => r.media_id.Equals(mediaId))) { media.active = false; if (media.Media_type.name.Equals(Util.StringValueOfMediaType(MediaType.Album))) { foreach (Album_song song in media.Album.Album_songs) { song.Song.Media.active = false; } } db.SubmitChanges(); return true; } // media type of the media MediaType mediaType = Util.MediaTypeOfValue(media.Media_type.name); // delete type-specific media record switch (mediaType) { case MediaType.Book: Book book = (from m in db.Books where m.media_id == mediaId select m).Single(); db.Books.DeleteOnSubmit(book); db.Medias.DeleteOnSubmit(book.Media); break; case MediaType.Movie: Movie movie = (from m in db.Movies where m.media_id == mediaId select m).Single(); db.Movies.DeleteOnSubmit(movie); db.Medias.DeleteOnSubmit(movie.Media); break; case MediaType.Album: Album album = (from m in db.Albums where m.media_id == mediaId select m).Single(); // get album/song junctions IQueryable<Album_song> albumSongs = from m in db.Album_songs where m.album_id == album.media_id select m; // delete all album/song junctions and songs foreach (var albumSong in albumSongs) { db.Album_songs.DeleteOnSubmit(albumSong); db.Songs.DeleteOnSubmit(albumSong.Song); db.Medias.DeleteOnSubmit(albumSong.Song.Media); db.Ratings.DeleteOnSubmit(albumSong.Song.Media.Rating); } // delete album db.Albums.DeleteOnSubmit(album); db.Medias.DeleteOnSubmit(album.Media); break; case MediaType.Song: Song song = (from m in db.Songs where m.media_id == mediaId select m).Single(); // get album/song junctions IQueryable<Album_song> albumSongs2 = from m in db.Album_songs where m.song_id == media.id select m; // delete all album/song junctions and songs foreach (var albumSong in albumSongs2) db.Album_songs.DeleteOnSubmit(albumSong); db.Songs.DeleteOnSubmit(song); db.Medias.DeleteOnSubmit(song.Media); break; default: throw new ArgumentOutOfRangeException(); } RentItDatabase.Rating rating = media.Rating; db.Ratings.DeleteOnSubmit(rating); if (media.Media_file != null) { db.Media_files.DeleteOnSubmit(media.Media_file); } db.SubmitChanges(); } catch (InvalidOperationException) { // Media was not found throw new FaultException<ArgumentException>( new ArgumentException("The Media with id " + mediaId + " does not exist.")); } catch (Exception) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input.")); } return true; }
public void DeleteMediaTest3() { RentItClient target = new RentItClient(); int mediaId = 90000; // non-existant AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; target.DeleteMedia(mediaId, credentials); // InvalidCredentialsException }
/// <author>Jacob Rasmussen.</author> /// <summary> /// /// </summary> /// <param name="credentials"></param> public UserAccount GetAllCustomerData(AccountCredentials credentials) { Account account = ValidateCredentials(credentials); if (Util.IsPublisher(account)) throw new FaultException<InvalidCredentialsException>( new InvalidCredentialsException("Credentials must not belong to a publisher account.")); User_account userAccount; try { var db = new DatabaseDataContext(); userAccount = (from user in db.User_accounts where user.Account.user_name.Equals(account.UserName) select user).Single(); } catch (Exception) { throw new FaultException<Exception>( new Exception("Internal Error.")); } //List of rentals made by the user. var userRentals = new List<Rental>(); if (userAccount.Rentals.Count > 0) { foreach (var rental in userAccount.Rentals) { // If the media is no longer active if (!rental.Media.active) { continue; } //Fills the userRentals-list with Rental-objects containing info from db. MediaType mediaType = Util.MediaTypeOfValue(rental.Media.Media_type.name); switch (mediaType) { case MediaType.Song: break; default: userRentals.Add(new Rental(rental.media_id, mediaType, rental.start_time, rental.end_time)); break; } } } return new UserAccount(userAccount.user_name, userAccount.Account.full_name, userAccount.Account.email, userAccount.Account.password, userAccount.credit, userRentals); }
public void UpdateAccountInfoTest1() { RentItClient target = new RentItClient(); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; Account account = target.GetAllCustomerData(credentials); string oldEmail = account.Email; account.Email += "+"; bool expected = true; bool actual = target.UpdateAccountInfo(credentials, account); Assert.AreEqual(expected, actual); string newEmail = target.GetAllCustomerData(credentials).Email; Assert.AreEqual(oldEmail + "+", newEmail); }
/// <author>Lars Toft Jacobsen</author> /// <summary> /// Publish new media /// </summary> /// <param name="info"></param> /// <param name="credentials"></param> /// <returns></returns> public int PublishMedia(MediaInfo info, AccountCredentials credentials) { Account account = ValidateCredentials(credentials); if (account == null) { throw new FaultException<InvalidCredentialsException>( new InvalidCredentialsException("Invalid credentials submitted.")); ; } if (!Util.IsPublisher(account)) throw new FaultException<InvalidCredentialsException>( new InvalidCredentialsException("This user is not a publisher.")); if (info.Price < 0) { throw new FaultException<InvalidCredentialsException>( new InvalidCredentialsException("The price of the media cannot be negative.")); } var db = new DatabaseDataContext(); Genre genre; // fetch mediatype and genre id's if (!db.Media_types.Exists(t => t.name.Equals(info.Type))) { throw new FaultException<ArgumentException>( new ArgumentException("Invalid media type parameter")); } Media_type mtype = (from t in db.Media_types where t.name.Equals(info.Type) select t).Single(); // Add the genre if it doesn't already exist. int genreId = Util.AddGenre(info.Genre, info.Type); genre = (from g in db.Genres where g.id == genreId select g).Single(); // Check if the specified publisher exists. if (!db.Publishers.Exists(p => p.title.Equals(info.Publisher))) { throw new FaultException<ArgumentException>( new ArgumentException("Invalid publisher parameter")); } Publisher publisher = (from p in db.Publishers where p.title.Equals(info.Publisher) select p).Single(); try { var newMedia = new RentItDatabase.Media { title = info.Title, genre_id = genre.id, type_id = mtype.id, price = info.Price, release_date = info.ReleaseDate, publisher_id = publisher.id, active = true }; switch (info.Type) { case MediaType.Album: AlbumInfo albumInfo = (AlbumInfo)info; RentItDatabase.Album newAlbum = new Album() { Media = newMedia, album_artist = albumInfo.AlbumArtist, description = albumInfo.Description }; db.Albums.InsertOnSubmit(newAlbum); break; case MediaType.Book: BookInfo bookInfo = (BookInfo)info; RentItDatabase.Book newBook = new Book() { Media = newMedia, author = bookInfo.Author, pages = bookInfo.Pages, summary = bookInfo.Summary }; db.Books.InsertOnSubmit(newBook); break; case MediaType.Movie: MovieInfo movieInfo = (MovieInfo)info; RentItDatabase.Movie newMovie = new Movie() { Media = newMedia, director = movieInfo.Director, length = (int)movieInfo.Duration.TotalSeconds, summary = movieInfo.Summary }; db.Movies.InsertOnSubmit(newMovie); break; case MediaType.Song: SongInfo songInfo = (SongInfo)info; RentItDatabase.Song newSong = new Song() { Media = newMedia, artist = songInfo.Artist, length = (int)songInfo.Duration.TotalSeconds }; db.Songs.InsertOnSubmit(newSong); RentItDatabase.Album_song albumSong = new Album_song() { album_id = songInfo.AlbumId, Song = newSong }; db.Album_songs.InsertOnSubmit(albumSong); break; } db.Medias.InsertOnSubmit(newMedia); db.SubmitChanges(); var newRating = new RentItDatabase.Rating { media_id = newMedia.id, avg_rating = 0.0, ratings_count = 0 }; db.Ratings.InsertOnSubmit(newRating); db.SubmitChanges(); return newMedia.id; } catch (Exception e) { throw new FaultException<Exception>( new Exception("An internal error has occured. This is not related to the input: " + e.Message)); } }
public void UpdateMediaMetadataTest() { RentItClient target = new RentItClient(); AccountCredentials credentials = new AccountCredentials { UserName = "******", HashedPassword = "******" }; int mediaId = 10; // Kraftwerk - "The Man-Machine" album AlbumInfo newAlbumData = target.GetAlbumInfo(mediaId); string albumArtist = newAlbumData.AlbumArtist; newAlbumData.AlbumArtist = newAlbumData.AlbumArtist == "Kraftwerk" ? "Craftwork" : "Kraftwerk"; bool actual = target.UpdateMediaMetadata(newAlbumData, credentials); string updatedAlbumArtist = target.GetAlbumInfo(mediaId).AlbumArtist; Assert.IsTrue(actual); Assert.IsTrue(albumArtist == "Kraftwerk"? "Craftwork" == updatedAlbumArtist : "Kraftwerk" == updatedAlbumArtist); mediaId = 1; // "The Room" MovieInfo newMovieData = target.GetMovieInfo(mediaId); string director = newMovieData.Director; newMovieData.Director = newMovieData.Director == "Tommy Wiseau" ? "Timmy Wiseau" : "Tommy Wiseau"; actual = target.UpdateMediaMetadata(newMovieData, credentials); string updatedDirector = target.GetMovieInfo(mediaId).Director; Assert.IsTrue(actual); Assert.IsTrue(director == "Tommy Wiseau" ? "Timmy Wiseau" == updatedDirector : "Tommy Wiseau" == updatedDirector); mediaId = 2; // "House of Leaves" BookInfo newBookData = target.GetBookInfo(mediaId); string author = newBookData.Author; newBookData.Author = newBookData.Author == "Mark Z. Danielewsky" ? "Mak Z. Danielewsky" : "Mark Z. Danielewsky"; actual = target.UpdateMediaMetadata(newBookData, credentials); string updatedAuthor = target.GetBookInfo(mediaId).Author; Assert.IsTrue(actual); Assert.IsTrue(author == "Mark Z. Danielewsky" ? "Mak Z. Danielewsky" == updatedAuthor : "Mark Z. Danielewsky" == updatedAuthor); }
/// <author>Kenneth Søhrmann</author> public bool SubmitReview(MediaReview review, AccountCredentials credentials) { // Validate the credentials. ValidateCredentials(credentials); // Check if the user name of the credentials match the one of the review. if (!credentials.UserName.Equals(review.UserName)) { throw new FaultException<ArgumentException>( new ArgumentException("The user name specified in review does not match that of the credentials.")); } DatabaseDataContext db; try { db = new DatabaseDataContext(); } catch (Exception e) { throw new FaultException<Exception>( new Exception("1. An internal error has occured. This is not related to the input. " + e.Message)); } // Get the media instance reviewed. RentItDatabase.Media media; try { media = (from m in db.Medias where m.id.Equals(review.MediaId) select m).Single(); } catch (Exception) { throw new FaultException<ArgumentException>( new ArgumentException("The specified media id does not exist.")); } // Get the account of the reviewer. RentItDatabase.User_account userAccount; try { userAccount = (from u in db.User_accounts where u.user_name.Equals(review.UserName) select u).Single(); } catch (Exception) { throw new FaultException<ArgumentException>( new ArgumentException("Only user accounts can add reviews. If it fails with a user account, an internal error has occured.")); } try { // Create a new database-entry of the submitted review. var dbReview = new RentItDatabase.Review { Media = media, review1 = review.ReviewText, rating = Util.ValueOfRating(review.Rating), timestamp = review.Timestamp, User_account = userAccount, }; db.Reviews.InsertOnSubmit(dbReview); // Calculate new average rating and rating count. double avgRating = media.Rating.avg_rating; int numOfRatings = media.Rating.ratings_count; media.Rating.avg_rating = ((avgRating * numOfRatings) + Util.ValueOfRating(review.Rating)) / (numOfRatings + 1.0); media.Rating.ratings_count = numOfRatings + 1; db.SubmitChanges(); } catch (Exception e) { throw new FaultException<Exception>( new Exception("2 An internal error has occured. This is not related to the input. " + e.Message)); } return true; }
/// <author>Kenneth Søhrmann</author> /// <summary> /// Convenience method for uploading a movie to the server. /// The methods blocks during upload. /// </summary> /// <param name="credentials"> /// The credentials of the publisher who is to upload the specified /// movie. /// </param> /// <param name="movieInfo"> /// The metadata of the movie to be uploaded. /// </param> /// <exception cref="WebException"> /// Is thrown if the upload of the movie failed. /// </exception> /// <exception cref="ArgumentException"> /// Is thrown if the credentials are not authorized. /// </exception> public static void UploadMovie(Credentials credentials, MovieInfoUpload movieInfo) { if (!string.IsNullOrEmpty(movieInfo.FilePath)) { if (!File.Exists(movieInfo.FilePath)) { throw new ArgumentException("The specified file does not exist."); } if (!new FileInfo(movieInfo.FilePath).Extension.Equals(".mp4")) { throw new ArgumentException("The specified file does not have the supported extension, mp4."); } } var serviceClient = GetServiceClient(); var accountCredentials = new AccountCredentials { UserName = credentials.UserName, HashedPassword = credentials.HashedPassword }; try { serviceClient.ValidateCredentials(accountCredentials); } catch (Exception) { throw new ArgumentException("Invalid credentials submitted."); } var mInfo = new MovieInfo() { Title = movieInfo.Title, Type = MediaType.Movie, Genre = movieInfo.Genre, Price = movieInfo.Price, Publisher = movieInfo.Publisher, ReleaseDate = movieInfo.ReleaseDate, Director = movieInfo.Director, Duration = movieInfo.Duration, Summary = movieInfo.Summary, }; int movieId; try { movieId = serviceClient.PublishMedia(mInfo, accountCredentials); } catch (Exception e) { throw new Exception("Something went wrong: " + e.Message); } try { if (!string.IsNullOrEmpty(movieInfo.FilePath)) { UploadMediaFile(movieInfo.FilePath, movieId, credentials); } UploadThumbnail(movieId, movieInfo, credentials); } catch (Exception) { // Clean up server database if the upload failed. serviceClient.DeleteMedia(movieId, accountCredentials); throw new WebException("Upload of media failed."); } }