// ************************************** // DeleteCatalog // ************************************** public static void DeleteCatalog(int catalogId) { using (var ctx = new SongSearchContext()) { ctx.DeleteCatalog(catalogId); ctx.SaveChanges(); } }
// ************************************** // AddToMyActiveCart // ************************************** public static void AddToMyActiveCart(int contentId) { using (var ctx = new SongSearchContext()) { var content = ctx.Contents.SingleOrDefault(c => c.ContentId == contentId); if (content == null) { throw new ArgumentException(SystemErrors.ItemDoesNotExist); } // Check if open cart exists and if needed create new cart var cart = ctx.GetActiveCart() ?? EmptyCart(); if (cart != null) { if (cart.Contents.Any(i => i.ContentId == contentId)) { return; } } else { cart = EmptyCart(); ctx.Carts.AddObject(cart); } if (cart.Contents.Count() < 100) { cart.Contents.Add(content); } else { throw new ArgumentOutOfRangeException("You cart already contains the maximum number of items (100)"); } ctx.SaveChanges(); } }
// ************************************** // CreateNewInvitation // ************************************** public static Guid CreateNewInvitation(string inviteEmailAddress) { using (var ctx = new SongSearchContext()) { inviteEmailAddress = inviteEmailAddress.ToLower(); var userId = Account.User().UserId; var inv = ctx.Invitations.SingleOrDefault( i => i.InvitationEmailAddress.ToLower() == inviteEmailAddress.ToLower() && i.InvitationStatus == (int)InvitationStatusCodes.Open && i.InvitedByUserId == userId); if (inv == null) { inv = new Invitation { InvitationId = Guid.NewGuid(), InvitationEmailAddress = inviteEmailAddress, ExpirationDate = DateTime.Now.AddDays(30).Date, InvitedByUserId = userId, InvitationStatus = (int)InvitationStatusCodes.Open, IsPlanInvitation = !Account.User().IsSuperAdmin() //if it's a member admin, count against their user quota }; ctx.Invitations.AddObject(inv); } else {//extend expiration date //inv.InvitationStatus = (int)InvitationStatusCodes.Open; inv.ExpirationDate = DateTime.Now.AddDays(30).Date; } ctx.SaveChanges(); return inv.InvitationId; } }
// ************************************** // Delete // ************************************** public static void Delete(int contentId) { using (var ctx = new SongSearchContext()) { ctx.DeleteContent(contentId); ctx.SaveChanges(); } }
// ---------------------------------------------------------------------------- // (Public) // ---------------------------------------------------------------------------- // ************************************** // AddToUserBalance // ************************************** public static void AddToUserBalance(this User user) { using (var ctx = new SongSearchContext()) { ctx.AddToUserBalance(user); ctx.SaveChanges(); } }
// ************************************** // DeleteTag // ************************************** public static void DeleteTag(int tagId) { var userId = Account.User().UserId; using (var ctx = new SongSearchContext()) { var tag = ctx.Tags.SingleOrDefault(t => t.TagId == tagId && t.CreatedByUserId == userId); if (tag != null) { ctx.Tags.DeleteObject(tag); ctx.SaveChanges(); } } }
public static void Delete(int[] contentIds) { using (var ctx = new SongSearchContext()) { foreach (var contentId in contentIds) { ctx.DeleteContent(contentId); } ctx.SaveChanges(); } }
// ************************************** // CreateCatalog // ************************************** public static int CreateCatalog(Catalog catalog) { using (var ctx = new SongSearchContext()) { var cat = ctx.GetCatalog(catalog.CatalogName); var user = Account.User(); if (cat == null) { cat = new Catalog { CatalogName = catalog.CatalogName }; ctx.Catalogs.AddObject(cat); ctx.SaveChanges(); UserManagementService.UpdateUserCatalogRole(user.UserId, cat.CatalogId, (int)Roles.Admin); } else if (!user.IsAtLeastInCatalogRole(Roles.Admin, cat.CatalogId)) { throw new AccessViolationException("You do not have admin rights to this catalog"); } return cat.CatalogId; } }
// ************************************** // UpdateProfile // ************************************** public static bool ChangePassword(User user, string newPassword) { using (var ctx = new SongSearchContext()) { var dbuser = ctx.GetUser(user); if (dbuser == null) { return false; } if (!String.IsNullOrEmpty(newPassword)) { if (PasswordHashMatches(dbuser.Password, user.Password)) { dbuser.Password = newPassword.PasswordHashString(); } else { throw new ArgumentException("Passwords do not match"); } } else { throw new ArgumentNullException("New password cannot be blank"); } ctx.SaveChanges(); dbuser = null; return true; } }
// ************************************** // UploadToRemote // ************************************** public static void UploadToRemote(bool checkSize = false, bool onlyNewContent = false, MediaVersion[] mediaVersions = null) { Log.Debug(String.Format("Starting Amazon upload at {0}", DateTime.Now)); using (var ctx = new SongSearchContext()) { var query = ctx.Contents.AsQueryable(); if (onlyNewContent) { query = query.Where(c => c.ContentMedia.Any(m => m.IsRemote == false)); } var contents = query.ToList(); if (contents.Count > 0) { Log.Debug("Getting remote file list"); var remoteList = GetRemoteFileList(mediaVersions ?? new MediaVersion[] { MediaVersion.Preview, MediaVersion.Full }); //var remoteFolder = AmazonCloudService.GetContentPrefix(version); Log.Debug("Comparing " + contents.Count + " content items"); foreach (var content in contents) { Log.Debug("Checking ContentId " + content.ContentId); var dbContent = ctx.Contents.SingleOrDefault(c => c.ContentId == content.ContentId); var contentMedia = dbContent.ContentMedia.ToList(); if (mediaVersions != null) { contentMedia = contentMedia.Where(c => mediaVersions.Contains((MediaVersion)c.MediaVersion)).ToList(); } foreach (var media in contentMedia) { var key = AmazonCloudService.GetContentKey(media); var remoteMedia = remoteList[(MediaVersion)media.MediaVersion]; var filePath = Path.Combine((MediaVersion)media.MediaVersion == MediaVersion.Full ? SystemConfig.MediaPathFull : SystemConfig.MediaPathPreview, String.Concat(content.ContentId, SystemConfig.MediaDefaultExtension) ); var file = new FileInfo(filePath); if (file.Exists) { var remoteFile = checkSize ? remoteMedia.SingleOrDefault(x => x.Key == key && x.Size == file.Length) : remoteMedia.SingleOrDefault(x => x.Key == key); if (remoteFile == null) { try { AmazonCloudService.PutContentMedia(file.FullName, media); Log.Debug(String.Format("Uploaded local file {0}", file.FullName)); media.IsRemote = true; } catch (Exception ex) { Log.Error(ex); media.IsRemote = false; continue; } } else { Log.Debug(String.Format("File for {0} matches", content.ContentId)); media.IsRemote = true; } } else { // file is not local, let's see if it's remote var remoteFile = remoteMedia.SingleOrDefault(x => x.Key == key); if (remoteFile != null) { //if (checkSize) { //RepushMedia(content, media, filePath, file); media.IsRemote = true; //} } else { media.IsRemote = false; } } } ctx.SaveChanges(); } // DataSession.CommitChanges(); Log.Debug(String.Format("Completed Amazon upload at {0}", DateTime.Now)); } } }
// ************************************** // DeleteUser // ************************************** public static void DeleteUser(int userId, bool takeOwnerShip = false) { using (var ctx = new SongSearchContext()) { var user = ctx.Users.SingleOrDefault(x => x.UserId == userId); if (user != null) { if (user.UserId == Account.User().UserId) { throw new ArgumentException("You cannot delete yourself"); } if (user.IsSuperAdmin() && GetNumberOfUsersByAccessLevel(Roles.SuperAdmin) <= 1) { throw new ArgumentException("You cannot delete the last SuperAdmin"); } else { //if (takeOwnerShip) { // ctx.TakeOwnerShip(user); //} ctx.ReParentOrphans(user, user.ParentUser); if (user.CreatedCatalogs.Count() > 0) { var userCats = user.CreatedCatalogs.ToList(); foreach (var cat in userCats) { ctx.DeleteCatalog(cat.CatalogId); } } if (user.Invitation != null) { ctx.Invitations.DeleteObject(user.Invitation); } //handled via cascade in db //user.ActiveCartContents.ToList().ForEach(x => user.ActiveCartContents.Remove(x)); //user.UserCatalogRoles.ToList().ForEach(x => user.UserCatalogRoles.Remove(x)); var balance = user.PlanBalance; // ctx.PlanBalances.SingleOrDefault(x => x.PlanBalanceId == user.PlanBalanceId); if (balance != null) { balance.Users.Remove(user); if (balance.Users.Count() == 0) { ctx.Delete(balance); } else { ctx.RemoveFromUserBalance(user); if (user.IsAnyAdmin()) { ctx.RemoveFromAdminBalance(user); } } } ctx.Users.DeleteObject(user); ctx.SaveChanges(); } } } }
// ************************************** // DownloadPackagedCart // ************************************** public static Cart DownloadCompressedCart(int cartId) { var userId = Account.User().UserId; using (var ctx = new SongSearchContext()) { var cart = ctx.Carts.SingleOrDefault(c => c.UserId == userId && c.CartId == cartId); if (cart == null) { throw new ArgumentOutOfRangeException(); } cart.MarkAsDownloaded(); ctx.SaveChanges(); return cart; } }
//: BaseService, IContentAdminService { // ************************************** // Update // ************************************** public static void Update(Content contentModel, IList<int> tagsModel, IDictionary<TagType, string> newTagsModel, IList<ContentRepresentationUpdateModel> representationModel) { using (var ctx = new SongSearchContext()) { //UpdateModelWith Content var content = ctx.Contents .Include("Tags") .Include("Catalog") .Include("ContentRepresentations") .Include("ContentRepresentations.Territories") .Where(c => c.ContentId == contentModel.ContentId).SingleOrDefault();// && user.UserCatalogRoles.Any(x => x.CatalogId == c.CatalogId)).SingleOrDefault(); if (content == null) { throw new ArgumentOutOfRangeException("Content does not exist"); } content.UpdateModelWith(contentModel); //UpdateModelWith Tags tagsModel = tagsModel.Where(t => t > 0).ToList(); // create new tags var newTags = ctx.CreateTags(newTagsModel); tagsModel = tagsModel.Union(newTags).ToList(); // add to tagsModel content = ctx.UpdateTags(content, tagsModel); //UpdateModelWith Representation content = ctx.UpdateRepresentation(content, representationModel); content.LastUpdatedByUserId = Account.User().UserId; content.LastUpdatedOn = DateTime.Now; ctx.SaveChanges(); CacheService.InitializeApp(true); //CacheService.CacheUpdate(CacheService.CacheKeys.Content); //CacheService.CacheUpdate(CacheService.CacheKeys.Rights); //CacheService.CacheUpdate(CacheService.CacheKeys.TopTags); //CacheService.CacheUpdate(CacheService.CacheKeys.Tags); //CacheService.CacheUpdate(CacheService.CacheKeys.Territories); } }
// ************************************** // DeleteCart // ************************************** public static void DeleteCart(int cartId) { var userId = Account.User().UserId; using (var ctx = new SongSearchContext()) { var cart = ctx.Carts.SingleOrDefault(c => c.UserId == userId && c.CartId == cartId); if (cart == null) { throw new ArgumentOutOfRangeException(); } string path = cart.ArchivePath(); ctx.Carts.DeleteObject(cart); ctx.SaveChanges(); cart = null; FileSystem.SafeDelete(path, false); } }
// ************************************** // CompressMyActiveCart // ************************************** public static void CompressMyActiveCart(string userArchiveName = null, IList<ContentUserDownloadable> contentNames = null) { using (var ctx = new SongSearchContext()) { var cart = ctx.GetActiveCart(); if (cart != null && cart.Contents.Count() > 0) { string zipName = cart.ArchiveDownloadName(userArchiveName); cart.ArchiveName = zipName; CompressCart(cart.CartId, contentNames); cart.MarkAsCompressed(); ctx.SaveChanges(); SessionService.Session().SessionUpdate(cart.CartId, "ProcessingCartId"); cart = null; } } }
// ************************************** // ArchiveExpiredCarts // ************************************** public static void ArchiveExpiredCarts() { using (var ctx = new SongSearchContext()) { var cutOffDate = DateTime.Now.AddDays(-DAYS_TO_EXPIRE); var expiredCarts = ctx.Carts .Where(c => c.CartStatus == (int)CartStatusCodes.Compressed && c.LastUpdatedOn < cutOffDate); foreach (var cart in expiredCarts) { cart.CartStatus = (int)CartStatusCodes.Downloaded; cart.LastUpdatedOn = DateTime.Now; } ctx.SaveChanges(); expiredCarts = null; } }
// ************************************** // UpdateMediaRemoteStatus // ************************************** public static void UpdateContentMedia(bool checkSize = false) { using (var ctx = new SongSearchContext()) { var contents = ctx.Contents.ToList(); var remoteList = GetRemoteFileList(new MediaVersion[] { MediaVersion.Preview, MediaVersion.Full }); //var remoteFolder = AmazonCloudService.GetContentPrefix(version); foreach (var content in contents.AsParallel()) { var dbContent = ctx.Contents.SingleOrDefault(c => c.ContentId == content.ContentId); foreach (var media in dbContent.ContentMedia.AsParallel()) { var key = AmazonCloudService.GetContentKey(media); var remoteMedia = remoteList[(MediaVersion)media.MediaVersion]; var filePath = Path.Combine((MediaVersion)media.MediaVersion == MediaVersion.Full ? SystemConfig.MediaPathFull : SystemConfig.MediaPathPreview, String.Concat(content.ContentId, SystemConfig.MediaDefaultExtension) ); var file = new FileInfo(filePath); if (file.Exists) { var hasRemoteFile = checkSize ? remoteMedia.Any(x => x.Key == key && x.Size == file.Length) : remoteMedia.Any(x => x.Key == key); media.IsRemote = hasRemoteFile; UpdateContentId3Tag(content, file); UpdateMediaId3info(media, file); } else { // media.IsRemote = false; dbContent.ContentMedia.Remove(media); } } ctx.SaveChanges(); } // DataSession.CommitChanges(); } Log.Debug("Done syncing"); }
private static void MakeATag(int contentId, string field, TagType tagType) { if (field != null) { var fieldvalues = field.Split(',').Select(v => v.Trim()).Where(s => !String.IsNullOrWhiteSpace(s)); using (var ctx = new SongSearchContext()) { var content = ctx.Contents.SingleOrDefault<Content>(x => x.ContentId == contentId); if (content != null) { foreach (var itm in fieldvalues) { var value = itm.Trim(); Tag tag = ctx.Tags.SingleOrDefault<Tag>(t => t.TagName.Equals(value, StringComparison.InvariantCultureIgnoreCase)) ?? new Tag() { TagName = value, CreatedByUserId = 1, TagTypeId = (int)tagType } ; if (tag.TagId == 0) { ctx.Tags.AddObject(tag); ctx.SaveChanges(); } if (!content.Tags.Contains(tag)) { content.Tags.Add(tag); } } ctx.SaveChanges(); } } } }
// ************************************** // SaveCatalog // ************************************** private CatalogUploadState SaveCatalog(CatalogUploadState state) { System.Diagnostics.Debug.Write("Step5"); var user = Account.User(); // Save/create Catalog if (user.IsAtLeastInRole(Roles.Admin) && !user.MyBalances().NumberOfSongs.IsAtTheLimit) { using (var ctx = new SongSearchContext()) { var catalog = ctx.Catalogs.SingleOrDefault(c => c.CatalogName.ToUpper() == state.CatalogName) ?? new Catalog() { CatalogName = state.CatalogName, CreatedByUserId = user.UserId, CreatedOn = DateTime.Now }; if (catalog.CatalogId == 0) { ctx.Catalogs.AddObject(catalog); //DataSession.CommitChanges(); //Make current user an admin var userCatalog = new UserCatalogRole() { UserId = user.UserId, CatalogId = catalog.CatalogId, RoleId = (int)Roles.Admin }; ctx.UserCatalogRoles.AddObject(userCatalog); //Make parent user an admin if (user.ParentUserId.HasValue) { var parentUserCatalog = //DataSession.Single<UserCatalogRole>( // x => x.UserId == user.ParentUserId.Value && // x.CatalogId == catalog.CatalogId && // x.RoleId == (int)Roles.Admin // ) ?? new UserCatalogRole() { UserId = user.ParentUserId.Value, CatalogId = catalog.CatalogId, RoleId = (int)Roles.Admin }; ctx.UserCatalogRoles.AddObject(parentUserCatalog); } //Make plan user an admin if (!user.IsPlanOwner && user.PlanUserId != user.ParentUserId.GetValueOrDefault()) { var planUserCatalog = //DataSession.Single<UserCatalogRole>( // x => x.UserId == user.PlanUserId && // x.CatalogId == catalog.CatalogId && // x.RoleId == (int)Roles.Admin // ) ?? new UserCatalogRole() { UserId = user.PlanUserId, CatalogId = catalog.CatalogId, RoleId = (int)Roles.Admin }; ctx.UserCatalogRoles.AddObject(planUserCatalog); } // defer? ctx.SaveChanges(); } state.CatalogId = catalog.CatalogId; state.CatalogName = catalog.CatalogName.ToUpper(); // Save Content var content = App.IsLicensedVersion ? state.Content.Take(user.MyBalances().NumberOfSongs.IsGoodFor(state.Content.Count())).ToList() : state.Content; foreach (var itm in content) { itm.CatalogId = state.CatalogId; itm.CreatedByUserId = user.UserId; itm.CreatedOn = DateTime.Now; itm.LastUpdatedByUserId = user.UserId; itm.LastUpdatedOn = DateTime.Now; //itm.IsMediaOnRemoteServer = false; itm.Title = itm.Title.AsEmptyIfNull();//.CamelCase();//.ToUpper(); itm.Artist = itm.Artist.AsEmptyIfNull();//.CamelCase();//.ToUpper(); itm.RecordLabel = itm.RecordLabel.AsEmptyIfNull();//.CamelCase();//.ToUpper(); itm.ReleaseYear = itm.ReleaseYear.GetValueOrDefault().AsNullIfZero(); itm.Notes = itm.Notes; var full = itm.UploadFiles.SingleOrDefault(f => f.FileMediaVersion == MediaVersion.Full); foreach (var version in ModelEnums.MediaVersions()) { var upl = itm.UploadFiles.SingleOrDefault(f => f.FileMediaVersion == version); if (upl != null) { var file = new FileInfo(upl.FilePath); var id3 = ID3Writer.NormalizeTag(upl.FilePath, itm); var media = new ContentMedia() { MediaVersion = (int)version, MediaType = "mp3", MediaSize = file.Length, MediaLength = id3.MediaLength, MediaDate = file.GetMediaDate(), MediaBitRate = id3.GetBitRate(file.Length) }; media.IsRemote = false; itm.ContentMedia.Add(media); } } ctx.Contents.AddObject(itm); ctx.AddToSongsBalance(user); ctx.SaveChanges(); if (itm.ContentId > 0) { foreach (var file in itm.UploadFiles) { MediaService.SaveContentMedia(file.FilePath, itm.Media(file.FileMediaVersion)); } } } } } SessionService.Session().InitializeSession(true); CacheService.InitializeApp(true); return state; }
// ************************************** // TakeOwnerShip // ************************************** public static void TakeOwnerShip(int userId) { using (var ctx = new SongSearchContext()) { var user = ctx.GetUser(userId); if (user != null) { ctx.TakeOwnerShip(user); ctx.SaveChanges(); } user = null; } }
public static void CompressCartCallback(IAsyncResult asyncResult) { // Extract the delegate from the // System.Runtime.Remoting.Messaging.AsyncResult. using (var ctx = new SongSearchContext()) { try { CompressCartDelegate compressDelegate = (CompressCartDelegate)((AsyncResult)asyncResult).AsyncDelegate; int cartId = (int)asyncResult.AsyncState; compressDelegate.EndInvoke(asyncResult); var cart = ctx .Carts .Include("Contents")//.Include("Contents.ContentMedia") .SingleOrDefault(c => c.CartId == cartId); if (cart != null && cart.Contents.Count() > 0) { cart.MarkAsCompressed(); ctx.SaveChanges(); cart = null; } } catch (Exception ex) { Log.Error(ex); } } }
// ************************************** // UpdateUsersRole // ************************************** public static void ToggleSystemAdminAccess(int userId) { using (var ctx = new SongSearchContext()) { var user = ctx.GetUser(userId); var admin = (int)Roles.Admin; if (user != null && !user.IsSuperAdmin()) { if (user.RoleId != admin) { user.RoleId = admin; ctx.AddToAdminBalance(user); } else { user.RoleId = (int)Roles.Client; ctx.RemoveFromAdminBalance(user); } ctx.SaveChanges(); } } }
// // ATTENTION: This seems to require the Application Pool to run as an admin or some account with elevated privileges, have to check... // public static void CompressMyActiveCartOffline(string userArchiveName = null, IList<ContentUserDownloadable> contentNames = null) { //mark as processing try { using (var ctx = new SongSearchContext()) { var userId = Account.User().UserId; var cart = ctx.Carts //.Include("Contents").Include("Contents.ContentMedia") .SingleOrDefault(c => c.UserId == userId && c.CartStatus == (int)CartStatusCodes.Active); if (cart != null && cart.Contents.Count() > 0) { cart.ArchiveName = cart.ArchiveDownloadName(userArchiveName); cart.CartStatus = (int)CartStatusCodes.Processing; ctx.SaveChanges(); //hand off compression work CompressCartDelegate compressDelegate = new CompressCartDelegate(CompressCart); // Define the AsyncCallback delegate. AsyncCallback callBack = new AsyncCallback(CompressCartCallback); compressDelegate.BeginInvoke(cart.CartId, contentNames, callBack, cart.CartId ); } cart = null; } } catch (Exception ex) { Log.Error(ex); throw ex; } }
// ************************************** // UpdateUserRoleAllCatalogs // ************************************** public static void UpdateAllCatalogs(int userId, int roleId) { using (var ctx = new SongSearchContext()) { var catalogs = ctx.Catalogs.AsQueryable(); var user = ctx.GetUser(userId); if (!Account.User().IsSuperAdmin()) { var parentUser = ctx.Users .Include("UserCatalogRoles.Catalog") .SingleOrDefault(u => u.UserId == user.ParentUserId); // limit to catalogs with myUser admin access if not superadmin catalogs = parentUser != null ? catalogs.LimitToAdministeredBy(parentUser) : catalogs; } foreach (var catalog in catalogs) { var usrCatalog = user.UserCatalogRoles.SingleOrDefault(uc => uc.CatalogId == catalog.CatalogId); if (usrCatalog == null && roleId > 0) { // new catalog role // check role against enum roleId = ModelEnums.GetRoles().GetBestMatchForRole(roleId); usrCatalog = new UserCatalogRole { UserId = userId, CatalogId = catalog.CatalogId, RoleId = roleId }; ctx.UserCatalogRoles.AddObject(usrCatalog); } else { if (roleId > 0) { usrCatalog.RoleId = roleId; } else { // revoke access ctx.UserCatalogRoles.DeleteObject(usrCatalog); } } } if (!user.IsInRole(Roles.Admin) && roleId == (int)Roles.Admin) { // newly minted admin? user.RoleId = roleId; ctx.AddToAdminBalance(user); } ctx.SaveChanges(); } }
// ************************************** // DeletedExpiredArchivedCarts // ************************************** public static void DeletedExpiredArchivedCarts() { using (var ctx = new SongSearchContext()) { var cutOffDate = DateTime.Now.AddDays(-DAYS_TO_DELETE); var expiredCarts = ctx.Carts .Where(c => c.CartStatus == (int)CartStatusCodes.Downloaded && c.LastUpdatedOn < cutOffDate) .ToList(); foreach (var cart in expiredCarts) { string path = cart.ArchivePath(); ctx.Carts.DeleteObject(cart); ctx.SaveChanges(); FileSystem.SafeDelete(path, false); } expiredCarts = null; } }
// ************************************** // UpdateCatalogRoleAllUsers // ************************************** public static void UpdateAllUsers(int catalogId, int roleId) { using (var ctx = new SongSearchContext()) { var cat = ctx.Catalogs.SingleOrDefault(x => x.CatalogId == catalogId); if (cat != null) { //var users = DataSession.GetObjectQuery<User>().Include("UserCatalogRoles").ToList(); var users = Account.User().MyUserHierarchy(true); ctx.SetCatalogRole(catalogId, roleId, users); ctx.SaveChanges(); } } }
public static void RemoveFromMyActiveCart(int[] contentIds) { using (var ctx = new SongSearchContext()) { var cart = ctx.GetActiveCart(); if (cart != null) { foreach (var contentId in contentIds) { var content = cart.Contents.Where(c => c.ContentId == contentId).SingleOrDefault(); if (content != null) { cart.Contents.Remove(content); } } ctx.SaveChanges(); } cart = null; } }
// ************************************** // UpdateUserCatalogRole // ************************************** public static void UpdateUserCatalogRole(int userId, int catalogId, int roleId) { using (var ctx = new SongSearchContext()) { var user = ctx.GetUserDetail(userId); if (user != null && catalogId > 0) { var usrCatalogRole = user.UserCatalogRoles.Where(c => c.CatalogId == catalogId).SingleOrDefault(); if (usrCatalogRole == null) { if (roleId > 0) { // new catalog role // check role against enum roleId = ModelEnums.GetRoles().GetBestMatchForRole(roleId); usrCatalogRole = new UserCatalogRole { UserId = userId, CatalogId = catalogId, RoleId = roleId }; ctx.UserCatalogRoles.AddObject(usrCatalogRole); } } else { if (roleId > 0) { // update role usrCatalogRole.RoleId = roleId; } else { //also remove these catalogs from any child users, really? var childUsers = user.MyUserHierarchy(withCatalogRoles: true); foreach (var child in childUsers) { var cat = ctx.UserCatalogRoles.SingleOrDefault(x => x.CatalogId == catalogId && x.UserId == child.UserId); if (cat != null) { ctx.UserCatalogRoles.DeleteObject(cat); } } // revoke parent access ctx.UserCatalogRoles.DeleteObject(usrCatalogRole); } } // check if it's an admin role; if so, elevate the system role to Admin if user is not already there if (roleId == (int)Roles.Admin && user.RoleId > roleId) { user.RoleId = roleId; ctx.AddToAdminBalance(user); } ctx.SaveChanges(); } } }
public static void AddToMyActiveCart(int[] contentIds) { // Check if open cart exists and if needed create new cart using (var ctx = new SongSearchContext()) { var cart = ctx.GetActiveCart() ?? EmptyCart(); if (cart.CartId == 0) { ctx.Carts.AddObject(cart); } if (cart.Contents.Count() + contentIds.Count() > 100) { throw new ArgumentOutOfRangeException("You cart already contains the maximum number of items (100)"); } var contents = ctx.Contents.Where(c => contentIds.Contains(c.ContentId)).ToList(); foreach (var contentId in contentIds) { if (!cart.Contents.Any(i => i.ContentId == contentId)) { var content = contents.SingleOrDefault(c => c.ContentId == contentId); if (content == null) { throw new ArgumentException(SystemErrors.ItemDoesNotExist); } cart.Contents.Add(content); } } ctx.SaveChanges(); } }
// ************************************** // UpdateUsersRole // ************************************** public static void UpdateUsersRole(int userId, int roleId) { using (var ctx = new SongSearchContext()) { var user = ctx.GetUser(userId); if (user != null && ModelEnums.GetRoles().Contains(roleId)) { user.RoleId = roleId; if (roleId == (int)Roles.Admin) { user.AddToAdminBalance(); } else if (user.RoleId == (int)Roles.Admin) { user.RemoveFromAdminBalance(); } user.RoleId = roleId; ctx.SaveChanges(); } } }