public ActionResult Login(LoginViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var login = Promoter.ACC_LOGIN_PREFIX + model.Login; var skipValidation = false; #if DEBUG skipValidation = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["SkipLogonAD"]); #endif if (!skipValidation) { if (!Membership.ValidateUser(login, model.Password)) { login = model.Login; if (!Membership.ValidateUser(login, model.Password)) { ModelState.AddModelError("", "Неверный логин/пароль."); return(View(model)); } } } var user = DbSession.Query <Promoter>().Where(r => r.Login == model.Login).FirstOrDefault(); if (user == null) { var admin = DbSession.Query <RegionalAdmin>().Any(r => r.Name == model.Login); if (admin) { FormsAuthentication.SetAuthCookie(model.Login, model.RememberMe); return(RedirectToAction("Register")); } else { ModelState.AddModelError("", $"Пользователь \"{model.Login}\" не включен в список организаторов акций. Обратитесь в АналитФармацию."); return(View(model)); } } FormsAuthentication.SetAuthCookie(login, model.RememberMe); System.Web.HttpContext.Current.Session["promoter"] = user; Association lastAssociation = null; if (user.LastAssociationId.HasValue) { lastAssociation = DbSession.Query <Association>().FirstOrDefault(r => r.Id == user.LastAssociationId); } if (lastAssociation == null) { lastAssociation = DbSession.Query <PromoterAssociation>().First(r => r.Promoter == user).Association; user.LastAssociationId = lastAssociation.Id; } NHibernateUtil.Initialize(lastAssociation); DbSession.Evict(lastAssociation); CurrentAssociation = lastAssociation; return(Redirect("~")); }
public void Bug() { Parent parent = new Parent(); parent.Name = "Parent"; RelatedObject obj1 = new RelatedObject(); obj1.Name = "Related Object 1"; RelatedObject obj2 = new RelatedObject(); obj2.Name = "Related Object 2"; Child child1 = new Child(); child1.Parent = parent; child1.RelatedObject = obj1; child1.Name = "Child 1"; Child child2 = new Child(); child2.Parent = parent; child2.RelatedObject = obj2; child2.Name = "Child 2"; parent.Children = new SortedSet <Child>(new ChildComparer()); parent.Children.Add(child1); parent.Children.Add(child2); DifferentChild dc1 = new DifferentChild(); dc1.Parent = parent; dc1.Name = "Different Child 1"; dc1.Child = child1; DifferentChild dc2 = new DifferentChild(); dc2.Parent = parent; dc2.Name = "Different Child 2"; dc2.Child = child2; parent.DifferentChildren = new HashedSet <DifferentChild>(); parent.DifferentChildren.Add(dc1); parent.DifferentChildren.Add(dc2); using (ISession session = OpenSession()) { session.Save(obj1); session.Save(obj2); session.Save(parent); session.Save(child1); session.Save(child2); session.Save(dc1); session.Save(dc2); session.Flush(); } int dcId = 0; using (ISession session = OpenSession()) { Parent loadedParent = (Parent)session.Get(typeof(Parent), parent.ID); NHibernateUtil.Initialize(loadedParent.DifferentChildren); foreach (DifferentChild dc in loadedParent.DifferentChildren) { dcId = dc.ID; break; } } using (ISession session = OpenSession()) { DifferentChild dc = (DifferentChild)session.Get(typeof(DifferentChild), dcId); } using (ISession session = OpenSession()) { session.Delete(dc1); session.Delete(dc2); session.Delete(child1); session.Delete(child2); session.Delete(parent); session.Delete(obj1); session.Delete(obj2); session.Flush(); } }
public void Merge(int sourceId, int targetId) { PermissionContext.VerifyPermission(PermissionToken.MergeEntries); if (sourceId == targetId) { throw new ArgumentException("Source and target artists can't be the same", "targetId"); } HandleTransaction(session => { var source = session.Load <Artist>(sourceId); var target = session.Load <Artist>(targetId); AuditLog($"Merging {EntryLinkFactory.CreateEntryLink(source)} to {EntryLinkFactory.CreateEntryLink(target)}", session); NHibernateUtil.Initialize(source.Picture); NHibernateUtil.Initialize(target.Picture); foreach (var n in source.Names.Names.Where(n => !target.HasName(n))) { var name = target.CreateName(n.Value, n.Language); session.Save(name); } foreach (var w in source.WebLinks.Where(w => !target.HasWebLink(w.Url))) { var link = target.CreateWebLink(w.Description, w.Url, w.Category, w.Disabled); session.Save(link); } var groups = source.Groups.Where(g => !target.HasGroup(g.Parent)).ToArray(); foreach (var g in groups) { g.MoveToMember(target); session.Update(g); } var members = source.Members.Where(m => !m.Member.HasGroup(target)).ToArray(); foreach (var m in members) { m.MoveToGroup(target); session.Update(m); } var albums = source.Albums.Where(a => !target.HasAlbum(a.Album)).ToArray(); foreach (var a in albums) { a.Move(target); session.Update(a); } var songs = source.Songs.Where(s => !target.HasSong(s.Song)).ToArray(); foreach (var s in songs) { s.Move(target); session.Update(s); } var ownerUsers = source.OwnerUsers.Where(s => !target.HasOwnerUser(s.User)).ToArray(); foreach (var u in ownerUsers) { u.Move(target); session.Update(u); } var pictures = source.Pictures.ToArray(); foreach (var p in pictures) { p.Move(target); session.Update(p); } var users = source.Users.ToArray(); foreach (var u in users) { u.Move(target); session.Update(u); } target.Description.CopyIfEmpty(source.Description); // Create merge record var mergeEntry = new ArtistMergeRecord(source, target); session.Save(mergeEntry); source.Deleted = true; Archive(session, source, ArtistArchiveReason.Deleted, $"Merged to {target}"); Archive(session, target, ArtistArchiveReason.Merged, $"Merged from '{source}'"); NHibernateUtil.Initialize(source.Picture); NHibernateUtil.Initialize(target.Picture); session.Update(source); session.Update(target); }); }
public void SubselectFetchHql() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Parent p = new Parent("foo"); p.Children.Add(new Child("foo1")); p.Children.Add(new Child("foo2")); Parent q = new Parent("bar"); q.Children.Add(new Child("bar1")); q.Children.Add(new Child("bar2")); ArrayHelper.AddAll(q.MoreChildren, p.Children); s.Save(p); s.Save(q); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); sessions.Statistics.Clear(); IList parents = s.CreateQuery("from Parent where name between 'bar' and 'foo' order by name desc") .List(); p = (Parent)parents[0]; q = (Parent)parents[1]; Assert.IsFalse(NHibernateUtil.IsInitialized(p.Children)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(p.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(p.Children[0])); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(q.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children[0])); Assert.IsFalse(NHibernateUtil.IsInitialized(p.MoreChildren)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(p.MoreChildren.Count, 0); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(q.MoreChildren.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren[0])); Assert.AreEqual(3, sessions.Statistics.PrepareStatementCount); Child c = (Child)p.Children[0]; NHibernateUtil.Initialize(c.Friends); s.Delete(p); s.Delete(q); t.Commit(); s.Close(); }
public void SessionSerializationWithNHProxy() { using (var s = OpenSession()) { using (var t = s.BeginTransaction()) { var s1 = s.Load <SimpleEntity>(_idSimpleEntity1); NHibernateUtil.Initialize(s1); Assert.That( NHibernateUtil.IsInitialized(s1), Is.True, "s1 should be initialized after initialization"); var i1 = s.Load <IEntity>(_idInterfacedEntity1); NHibernateUtil.Initialize(i1); Assert.That( NHibernateUtil.IsInitialized(i1), Is.True, "i1 should be initialized after initialization"); var s2 = s.Load <SimpleEntity>(_idSimpleEntity2); Assert.That( NHibernateUtil.IsInitialized(s2), Is.False, "s2 should not be initialized after loading"); var i2 = s.Load <IEntity>(_idInterfacedEntity2); Assert.That( NHibernateUtil.IsInitialized(i2), Is.False, "i2 should not be initialized after loading"); t.Commit(); } var serializer = GetFormatter(); ISession ds; using (var memoryStream = new MemoryStream()) { serializer.Serialize(memoryStream, s); s.Close(); memoryStream.Seek(0L, SeekOrigin.Begin); ds = (ISession)serializer.Deserialize(memoryStream); } try { using (var t = ds.BeginTransaction()) { var s1 = ds.Load <SimpleEntity>(_idSimpleEntity1); Assert.That( NHibernateUtil.IsInitialized(s1), Is.True, "s1 should be initialized after deserialization"); Assert.That(s1.Name, Is.EqualTo("1"), "s1.Name"); Assert.That(s1.Text, Is.EqualTo("Text1"), "s1.Text"); var i1 = ds.Load <IEntity>(_idInterfacedEntity1); Assert.That( NHibernateUtil.IsInitialized(i1), Is.True, "i1 should be initialized after deserialization"); Assert.That(i1.Name, Is.EqualTo("1"), "i1.Name"); Assert.That(i1.Text, Is.EqualTo("Text1"), "i1.Text"); var s2 = ds.Load <SimpleEntity>(_idSimpleEntity2); Assert.That( NHibernateUtil.IsInitialized(s2), Is.False, "s2 should not be initialized after deserialization"); NHibernateUtil.Initialize(s2); Assert.That( NHibernateUtil.IsInitialized(s2), Is.True, "s2 should be initialized after initialization"); Assert.That(s2.Name, Is.EqualTo("2"), "s2.Name"); Assert.That(s2.Text, Is.EqualTo("Text2"), "s2.Text"); var i2 = ds.Load <IEntity>(_idInterfacedEntity2); Assert.That( NHibernateUtil.IsInitialized(i2), Is.False, "i2 should not be initialized after deserialization"); NHibernateUtil.Initialize(i2); Assert.That( NHibernateUtil.IsInitialized(i2), Is.True, "i2 should be initialized after initialization"); Assert.That(i2.Name, Is.EqualTo("2"), "i2.Name"); Assert.That(i2.Text, Is.EqualTo("Text2"), "i2.Text"); t.Commit(); } } finally { ds.Dispose(); } } }
public void Load(object proxy) { NHibernateUtil.Initialize(proxy); }
public async Task <AlbumForEditContract> UpdateBasicProperties(AlbumForEditContract properties, EntryPictureFileContract pictureData) { ParamIs.NotNull(() => properties); return(await repository.HandleTransactionAsync(async session => { var album = await session.LoadAsync(properties.Id); VerifyEntryEdit(album); var diff = new AlbumDiff(DoSnapshot(album.ArchivedVersionsManager.GetLatestVersion(), session.OfType <User>().GetLoggedUser(PermissionContext))); session.AuditLogger.SysLog(string.Format("updating properties for {0}", album)); if (album.DiscType != properties.DiscType) { album.DiscType = properties.DiscType; album.UpdateArtistString(); diff.DiscType.Set(); } diff.Description.Set(album.Description.CopyFrom(properties.Description)); var parsedBarcodes = properties.Identifiers.Select(Album.ParseBarcode).ToArray(); var barcodeDiff = album.SyncIdentifiers(parsedBarcodes); session.Sync(barcodeDiff); if (barcodeDiff.Changed) { diff.Identifiers.Set(); } if (album.TranslatedName.DefaultLanguage != properties.DefaultNameLanguage) { album.TranslatedName.DefaultLanguage = properties.DefaultNameLanguage; diff.OriginalName.Set(); } var validNames = properties.Names; var nameDiff = album.Names.Sync(validNames, album); await session.SyncAsync(nameDiff); album.Names.UpdateSortNames(); if (nameDiff.Changed) { diff.Names.Set(); } var webLinkDiff = WebLink.Sync(album.WebLinks, properties.WebLinks, album); session.OfType <AlbumWebLink>().Sync(webLinkDiff); if (webLinkDiff.Changed) { diff.WebLinks.Set(); } var newEvent = new CreateEventQuery().FindOrCreate(session, PermissionContext, properties.OriginalRelease.ReleaseEvent, album); var newOriginalRelease = (properties.OriginalRelease != null ? new AlbumRelease(properties.OriginalRelease, newEvent) : new AlbumRelease()); if (album.OriginalRelease == null) { album.OriginalRelease = new AlbumRelease(); } if (!album.OriginalRelease.Equals(newOriginalRelease)) { album.OriginalRelease = newOriginalRelease; diff.OriginalRelease.Set(); } // Required because of a bug in NHibernate NHibernateUtil.Initialize(album.CoverPictureData); if (pictureData != null) { var parsed = ImageHelper.GetOriginal(pictureData.UploadedFile, pictureData.ContentLength, pictureData.Mime); album.CoverPictureData = new PictureData(parsed); album.CoverPictureMime = parsed.Mime; pictureData.Id = album.Id; pictureData.EntryType = EntryType.Album; var thumbGenerator = new ImageThumbGenerator(imagePersister); thumbGenerator.GenerateThumbsAndMoveImage(pictureData.UploadedFile, pictureData, ImageSizes.AllThumbs); diff.Cover.Set(); } if (album.Status != properties.Status) { album.Status = properties.Status; diff.Status.Set(); } var artistGetter = new Func <ArtistContract, Task <Artist> >(artist => session.LoadAsync <Artist>(artist.Id)); var artistsDiff = await album.SyncArtists(properties.ArtistLinks, artistGetter); await session.OfType <ArtistForAlbum>().SyncAsync(artistsDiff); if (artistsDiff.Changed) { diff.Artists.Set(); } var discsDiff = await album.SyncDiscs(properties.Discs); await session.OfType <AlbumDiscProperties>().SyncAsync(discsDiff); if (discsDiff.Changed) { diff.Discs.Set(); } var songGetter = new Func <SongInAlbumEditContract, Task <Song> >(async contract => { if (contract.SongId != 0) { return await session.LoadAsync <Song>(contract.SongId); } else { var songName = StringHelper.TrimIfNotWhitespace(contract.SongName); session.AuditLogger.SysLog(string.Format("creating a new song '{0}' to {1}", songName, album)); var song = new Song(new LocalizedString(songName, ContentLanguageSelection.Unspecified)); await session.SaveAsync(song); var songDiff = new SongDiff(); songDiff.Names.Set(); var songArtistDiff = await song.SyncArtistsAsync(contract.Artists, addedArtistContracts => GetArtistsAsync(session, addedArtistContracts)); if (songArtistDiff.Changed) { songDiff.Artists.Set(); await session.UpdateAsync(song); } await session.SyncAsync(songArtistDiff); var archived = await ArchiveSongAsync(session.OfType <Song>(), song, songDiff, SongArchiveReason.Created, string.Format("Created for album '{0}'", album.DefaultName.TruncateWithEllipsis(100))); await session.AuditLogger.AuditLogAsync(string.Format("created {0} for {1}", entryLinkFactory.CreateEntryLink(song), entryLinkFactory.CreateEntryLink(album))); await AddEntryEditedEntryAsync(session.OfType <ActivityEntry>(), song, EntryEditEvent.Created, archived); return song; } }); var tracksDiff = await album.SyncSongs(properties.Songs, songGetter, (song, artistContracts) => UpdateSongArtistsAsync(session, song, artistContracts)); await session.OfType <SongInAlbum>().SyncAsync(tracksDiff); if (tracksDiff.Changed) { var add = string.Join(", ", tracksDiff.Added.Select(i => HttpUtility.HtmlEncode(i.SongToStringOrName))); var rem = string.Join(", ", tracksDiff.Removed.Select(i => HttpUtility.HtmlEncode(i.SongToStringOrName))); var edit = string.Join(", ", tracksDiff.Edited.Select(i => HttpUtility.HtmlEncode(i.SongToStringOrName))); var str = string.Format("edited tracks (added: {0}, removed: {1}, reordered: {2})", add, rem, edit) .Truncate(300); await session.AuditLogger.AuditLogAsync(str); diff.Tracks.Set(); } var picsDiff = album.Pictures.SyncPictures(properties.Pictures, session.OfType <User>().GetLoggedUser(PermissionContext), album.CreatePicture); await session.OfType <AlbumPictureFile>().SyncAsync(picsDiff); var entryPictureFileThumbGenerator = new ImageThumbGenerator(pictureFilePersister); album.Pictures.GenerateThumbsAndMoveImage(entryPictureFileThumbGenerator, picsDiff.Added, ImageSizes.Original | ImageSizes.Thumb); if (picsDiff.Changed) { diff.Pictures.Set(); } var pvDiff = album.SyncPVs(properties.PVs); await session.OfType <PVForAlbum>().SyncAsync(pvDiff); if (pvDiff.Changed) { diff.PVs.Set(); } var logStr = string.Format("updated properties for album {0} ({1})", entryLinkFactory.CreateEntryLink(album), diff.ChangedFieldsString) + (properties.UpdateNotes != string.Empty ? " " + properties.UpdateNotes : string.Empty) .Truncate(400); await session.AuditLogger.AuditLogAsync(logStr); var archivedAlbum = Archive(session, album, diff, AlbumArchiveReason.PropertiesUpdated, properties.UpdateNotes); await session.UpdateAsync(album); await AddEntryEditedEntryAsync(session.OfType <ActivityEntry>(), album, EntryEditEvent.Updated, archivedAlbum); var newSongCutoff = TimeSpan.FromHours(1); if (artistsDiff.Added.Any() && album.CreateDate >= DateTime.Now - newSongCutoff) { var addedArtists = artistsDiff.Added.Where(a => a.Artist != null).Select(a => a.Artist).Distinct().ToArray(); if (addedArtists.Any()) { await followedArtistNotifier.SendNotificationsAsync(session, album, addedArtists, PermissionContext.LoggedUser); } } return new AlbumForEditContract(album, PermissionContext.LanguagePreference, imageUrlFactory); })); }
public void TestMergeComponent() { Employee emp = null; IEnumerator <Employee> enumerator = null; using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = new Employee(); emp.HireDate = new DateTime(1999, 12, 31); emp.Person = new Person(); emp.Person.Name = "steve"; emp.Person.Dob = new DateTime(1999, 12, 31); s.Persist(emp); t.Commit(); s.Close(); } using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Get(typeof(Employee), emp.Id); t.Commit(); s.Close(); } Assert.That(emp.OptionalComponent, Is.Null); emp.OptionalComponent = new OptionalComponent(); emp.OptionalComponent.Value1 = "emp-value1"; emp.OptionalComponent.Value2 = "emp-value2"; using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Merge(emp); t.Commit(); s.Close(); } using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Get(typeof(Employee), emp.Id); t.Commit(); s.Close(); } Assert.That(emp.OptionalComponent.Value1, Is.EqualTo("emp-value1")); Assert.That(emp.OptionalComponent.Value2, Is.EqualTo("emp-value2")); emp.OptionalComponent.Value1 = null; emp.OptionalComponent.Value2 = null; using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Merge(emp); t.Commit(); s.Close(); } using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Get(typeof(Employee), emp.Id); NHibernateUtil.Initialize(emp.DirectReports); t.Commit(); s.Close(); } Assert.That(emp.OptionalComponent, Is.Null); Employee emp1 = new Employee(); emp1.HireDate = new DateTime(1999, 12, 31); emp1.Person = new Person(); emp1.Person.Name = "bozo"; emp1.Person.Dob = new DateTime(1999, 12, 31); emp.DirectReports.Add(emp1); using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Merge(emp); t.Commit(); s.Close(); } using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Get(typeof(Employee), emp.Id); NHibernateUtil.Initialize(emp.DirectReports); t.Commit(); s.Close(); } Assert.That(emp.DirectReports.Count, Is.EqualTo(1)); enumerator = emp.DirectReports.GetEnumerator(); enumerator.MoveNext(); emp1 = (Employee)enumerator.Current; Assert.That(emp1.OptionalComponent, Is.Null); emp1.OptionalComponent = new OptionalComponent(); emp1.OptionalComponent.Value1 = "emp1-value1"; emp1.OptionalComponent.Value2 = "emp1-value2"; using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Merge(emp); t.Commit(); s.Close(); } using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Get(typeof(Employee), emp.Id); NHibernateUtil.Initialize(emp.DirectReports); t.Commit(); s.Close(); } Assert.That(emp.DirectReports.Count, Is.EqualTo(1)); enumerator = emp.DirectReports.GetEnumerator(); enumerator.MoveNext(); emp1 = (Employee)enumerator.Current; Assert.That(emp1.OptionalComponent.Value1, Is.EqualTo("emp1-value1")); Assert.That(emp1.OptionalComponent.Value2, Is.EqualTo("emp1-value2")); emp1.OptionalComponent.Value1 = null; emp1.OptionalComponent.Value2 = null; using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Merge(emp); t.Commit(); s.Close(); } using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { emp = (Employee)s.Get(typeof(Employee), emp.Id); NHibernateUtil.Initialize(emp.DirectReports); t.Commit(); s.Close(); } Assert.That(emp.DirectReports.Count, Is.EqualTo(1)); enumerator = emp.DirectReports.GetEnumerator(); enumerator.MoveNext(); emp1 = (Employee)enumerator.Current; Assert.That(emp1.OptionalComponent, Is.Null); using (ISession s = Sfi.OpenSession()) using (ITransaction t = s.BeginTransaction()) { s.Delete(emp); t.Commit(); s.Close(); } }
public RezultatiEkipeForm(int takmicenjeId, DeoTakmicenjaKod deoTakKod) { InitializeComponent(); this.deoTakKod = deoTakKod; Cursor.Current = Cursors.WaitCursor; Cursor.Show(); ISession session = null; try { using (session = NHibernateHelper.Instance.OpenSession()) using (session.BeginTransaction()) { CurrentSessionContext.Bind(session); takmicenje = DAOFactoryFactory.DAOFactory.GetTakmicenjeDAO().FindById(takmicenjeId); NHibernateUtil.Initialize(takmicenje); gimnastika = takmicenje.Gimnastika; IList <RezultatskoTakmicenje> svaRezTakmicenja = loadRezTakmicenja(takmicenjeId); if (svaRezTakmicenja.Count == 0) { throw new BusinessException(Strings.NO_KATEGORIJE_I_TAKMICENJA_ERROR_MSG); } rezTakmicenja = takmicenje.getRezTakmicenjaEkipe(svaRezTakmicenja, deoTakKod, false); if (rezTakmicenja.Count == 0) { throw new BusinessException("Ne postoji ekipno takmicenje ni za jednu kategoriju."); } ekipaRezultatiUkupnoMap = Takmicenje.getEkipaRezultatiUkupnoMap(rezTakmicenja, svaRezTakmicenja, deoTakKod); initUI(); } } catch (BusinessException) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw; } catch (InfrastructureException) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw; } catch (Exception ex) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw new InfrastructureException(ex.Message, ex); } finally { Cursor.Hide(); Cursor.Current = Cursors.Arrow; CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory); } }
public RezultatiUkupnoForm(int takmicenjeId, DeoTakmicenjaKod deoTakKod, int startRezTakmicenjeId, bool forViewingOnly) { InitializeComponent(); this.deoTakKod = deoTakKod; this.forViewingOnly = forViewingOnly; Cursor.Current = Cursors.WaitCursor; Cursor.Show(); ISession session = null; try { using (session = NHibernateHelper.Instance.OpenSession()) using (session.BeginTransaction()) { CurrentSessionContext.Bind(session); takmicenje = DAOFactoryFactory.DAOFactory.GetTakmicenjeDAO().FindById(takmicenjeId); NHibernateUtil.Initialize(takmicenje); IList <RezultatskoTakmicenje> svaRezTakmicenja = loadRezTakmicenja(takmicenjeId); if (svaRezTakmicenja.Count == 0) { throw new BusinessException(Strings.NO_KATEGORIJE_I_TAKMICENJA_ERROR_MSG); } rezTakmicenja = takmicenje.getRezTakmicenjaViseboj(svaRezTakmicenja, deoTakKod, false); if (rezTakmicenja.Count == 0) { throw new BusinessException("Ne postoji takmicenje II ni za jednu kategoriju."); } RezultatskoTakmicenje startRezTakmicenje = null; if (startRezTakmicenjeId != -1) { startRezTakmicenje = findRezTakmicenje(startRezTakmicenjeId, rezTakmicenja); if (startRezTakmicenje == null) { throw new BusinessException("Ne postoje rezultati viseboj za dato takmicenje."); } } initUI(startRezTakmicenje); } } catch (BusinessException) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw; } catch (InfrastructureException) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw; } catch (Exception ex) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw new InfrastructureException(ex.Message, ex); } finally { Cursor.Hide(); Cursor.Current = Cursors.Arrow; CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory); } }
public void UpdateBasicProperties(ArtistForEditContract properties, PictureDataContract pictureData, IUserPermissionContext permissionContext) { ParamIs.NotNull(() => properties); ParamIs.NotNull(() => permissionContext); HandleTransaction(session => { var artist = session.Load <Artist>(properties.Id); VerifyEntryEdit(artist); var diff = new ArtistDiff(DoSnapshot(artist.GetLatestVersion(), GetLoggedUser(session))); SysLog(string.Format("updating properties for {0}", artist)); if (artist.ArtistType != properties.ArtistType) { artist.ArtistType = properties.ArtistType; diff.ArtistType = true; } if (artist.Description != properties.Description) { artist.Description = properties.Description; diff.Description = true; } if (artist.TranslatedName.DefaultLanguage != properties.TranslatedName.DefaultLanguage) { artist.TranslatedName.DefaultLanguage = properties.TranslatedName.DefaultLanguage; diff.OriginalName = true; } NHibernateUtil.Initialize(artist.Picture); if (pictureData != null) { artist.Picture = new PictureData(pictureData); diff.Picture = true; } if (artist.Status != properties.Status) { artist.Status = properties.Status; diff.Status = true; } var nameDiff = artist.Names.Sync(properties.Names.AllNames, artist); SessionHelper.Sync(session, nameDiff); if (nameDiff.Changed) { diff.Names = true; } var validWebLinks = properties.WebLinks.Where(w => !string.IsNullOrEmpty(w.Url)); var webLinkDiff = WebLink.Sync(artist.WebLinks, validWebLinks, artist); SessionHelper.Sync(session, webLinkDiff); if (webLinkDiff.Changed) { diff.WebLinks = true; } if (diff.ArtistType || diff.Names) { foreach (var song in artist.Songs) { song.Song.UpdateArtistString(); session.Update(song); } } var groupsDiff = CollectionHelper.Diff(artist.Groups, properties.Groups, (i, i2) => (i.Id == i2.Id)); foreach (var grp in groupsDiff.Removed) { grp.Delete(); session.Delete(grp); } foreach (var grp in groupsDiff.Added) { var link = artist.AddGroup(session.Load <Artist>(grp.Group.Id)); session.Save(link); } if (groupsDiff.Changed) { diff.Groups = true; } var picsDiff = artist.Pictures.SyncPictures(properties.Pictures, GetLoggedUser(session), artist.CreatePicture); SessionHelper.Sync(session, picsDiff); ImageHelper.GenerateThumbsAndMoveImages(picsDiff.Added); if (picsDiff.Changed) { diff.Pictures = true; } /* * var albumGetter = new Func<AlbumForArtistEditContract, Album>(contract => { * * Album album; * * if (contract.AlbumId != 0) { * * album = session.Load<Album>(contract.AlbumId); * * } else { * * AuditLog(string.Format("creating a new album '{0}' to {1}", contract.AlbumName, artist)); * * album = new Album(contract.AlbumName); * session.Save(album); * * Services.Albums.Archive(session, album, AlbumArchiveReason.Created, * string.Format("Created for artist '{0}'", artist.DefaultName)); * * AuditLog(string.Format("created {0} for {1}", * EntryLinkFactory.CreateEntryLink(album), EntryLinkFactory.CreateEntryLink(artist)), session); * AddEntryEditedEntry(session, album, EntryEditEvent.Created); * * } * * return album; * * }); * * if (properties.AlbumLinks != null * && !properties.TooManyAlbums * && (properties.AlbumLinks.Any() || artist.Albums.Count() < ArtistForEditContract.MaxAlbums / 2) * && artist.Albums.Count() <= ArtistForEditContract.MaxAlbums) { * * var albumDiff = artist.SyncAlbums(properties.AlbumLinks, albumGetter); * * SessionHelper.Sync(session, albumDiff); * * if (albumDiff.Changed) { * * diff.Albums = true; * * var add = string.Join(", ", albumDiff.Added.Select(i => i.Album.ToString())); * var rem = string.Join(", ", albumDiff.Removed.Select(i => i.Album.ToString())); * * var str = string.Format("edited albums (added: {0}, removed: {1})", add, rem) * .Truncate(300); * * AuditLog(str, session); * * } * * }*/ var logStr = string.Format("updated properties for {0} ({1})", EntryLinkFactory.CreateEntryLink(artist), diff.ChangedFieldsString) + (properties.UpdateNotes != string.Empty ? " " + properties.UpdateNotes : string.Empty) .Truncate(400); AuditLog(logStr, session); AddEntryEditedEntry(session, artist, EntryEditEvent.Updated); Archive(session, artist, diff, ArtistArchiveReason.PropertiesUpdated, properties.UpdateNotes); session.Update(artist); return(true); }); }
public void Test() { int a_id; using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { // Create an A and save it ClassA a = new ClassA(); a.Name = "a1"; s.Save(a); // Create a B and save it ClassB b = new ClassB(); b.Id = new ClassBId("bbb", a); b.SomeProp = "Some property"; s.Save(b); // Create a C and save it ClassC c = new ClassC(); c.B = b; s.Save(c); tx.Commit(); a_id = a.Id; } // Clear the cache sessions.Evict(typeof(ClassA)); sessions.Evict(typeof(ClassB)); sessions.Evict(typeof(ClassC)); using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { // Load a so we can use it to load b ClassA a = s.Get <ClassA>(a_id); // Load b so b will be in cache ClassB b = s.Get <ClassB>(new ClassBId("bbb", a)); tx.Commit(); } using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { using (SqlLogSpy sqlLogSpy = new SqlLogSpy()) { IList <ClassC> c_list = s.CreateCriteria(typeof(ClassC)).List <ClassC>(); // make sure we initialize B NHibernateUtil.Initialize(c_list[0].B); Assert.AreEqual(1, sqlLogSpy.Appender.GetEvents().Length, "Only one SQL should have been issued"); } tx.Commit(); } }
public CompetitionDetailView UploadFighters(Guid id) { using (var session = NHibernateHelper.OpenSession()) { var competition = session.QueryOver <Competition>().Where(x => x.Id == id).SingleOrDefault(); if (competition == null) { return(null); } var organizations = session.QueryOver <Organization>().List(); using (var parser = new TextFieldParser(Request.Content.ReadAsStreamAsync().Result)) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters("\t", ";"); parser.HasFieldsEnclosedInQuotes = true; parser.TrimWhiteSpace = true; var headerFields = parser.ReadFields()?.ToList(); if (headerFields != null) { var firstNameIndex = FindIndex(headerFields, 0, "First name", "Given name"); var lastNamePrefixIndex = FindIndex(headerFields, 0, "Prefix", "Last name prefix", "Family name prefix"); var lastNameIndex = FindIndex(headerFields, 0, "Last name", "Family name"); var fullNameIndex = FindIndex(headerFields, 0, "Full name", "Personal name", "Name"); var countryIndex = FindIndex(headerFields, 0, "Country"); var seedIndex = FindIndex(headerFields, 0, "Seed", "Ranking", "Rank"); var organizationIndexes = new List <int>(); var organizationIndexItem = FindIndex(headerFields, 0, "Organization", "Club"); while (organizationIndexItem != -1) { organizationIndexes.Add(organizationIndexItem); organizationIndexItem = FindIndex(headerFields, organizationIndexItem + 1, "Organization", "Club"); } while (!parser.EndOfData) { //Process row try { var fields = parser.ReadFields(); if (fields == null || fields.Length < 2) { continue; } Person fighter; if (firstNameIndex != -1 && lastNameIndex != -1 && fields.Length > firstNameIndex && fields.Length > lastNameIndex && (!string.IsNullOrWhiteSpace(fields[firstNameIndex]) || !string.IsNullOrWhiteSpace(fields[lastNameIndex]))) { if (lastNamePrefixIndex != -1 && fields.Length > lastNamePrefixIndex) { fighter = session.QueryOver <Person>().Where(x => x.FirstName.IsInsensitiveLike(fields[firstNameIndex]) && x.LastNamePrefix.IsInsensitiveLike(fields[lastNamePrefixIndex]) && x.LastName.IsInsensitiveLike(fields[lastNameIndex])).SingleOrDefault(); } else { fighter = session.QueryOver <Person>().Where(x => x.FirstName.IsInsensitiveLike(fields[firstNameIndex]) && x.LastName.IsInsensitiveLike(fields[lastNameIndex])).SingleOrDefault(); } if (fighter == null) { string fullName; if (fullNameIndex != -1 && fields.Length > fullNameIndex && !string.IsNullOrWhiteSpace(fields[fullNameIndex])) { fullName = fields[fullNameIndex]; } else { fullName = fields[firstNameIndex]; if (lastNamePrefixIndex != -1 && fields.Length > lastNamePrefixIndex && !string.IsNullOrWhiteSpace(fields[lastNamePrefixIndex])) { if (string.IsNullOrWhiteSpace(fullName)) { fullName += " "; } fullName += fields[lastNamePrefixIndex]; } if (!string.IsNullOrWhiteSpace(fields[lastNameIndex])) { if (string.IsNullOrWhiteSpace(fullName)) { fullName += " "; } fullName += fields[lastNameIndex]; } } fighter = session.QueryOver <Person>() .Where(x => x.FullName.IsInsensitiveLike(fullName)).SingleOrDefault(); if (fighter != null) { fighter.FirstName = fields[firstNameIndex]; fighter.LastName = fields[lastNameIndex]; if (lastNamePrefixIndex != -1 && fields.Length > lastNamePrefixIndex) { fighter.LastNamePrefix = fields[lastNamePrefixIndex]; } } } if (fighter == null) { fighter = new Person { FirstName = fields[firstNameIndex], LastName = fields[lastNameIndex], }; if (lastNamePrefixIndex != -1 && fields.Length > lastNamePrefixIndex) { fighter.LastNamePrefix = fields[lastNamePrefixIndex]; } if (fullNameIndex != -1 && fields.Length > fullNameIndex) { fighter.FullName = fields[fullNameIndex]; } using (var transaction = session.BeginTransaction()) { session.Save(fighter); transaction.Commit(); } } } else if (fullNameIndex != -1 && fields.Length > fullNameIndex && !string.IsNullOrWhiteSpace(fields[fullNameIndex])) { fighter = session.QueryOver <Person>() .Where(x => x.FullName.IsInsensitiveLike(fields[fullNameIndex])) .SingleOrDefault(); if (fighter == null) { fighter = new Person { FullName = fields[0] }; using (var transaction = session.BeginTransaction()) { session.Save(fighter); transaction.Commit(); } } } else { continue; } var competitionFighter = competition.Fighters.SingleOrDefault(x => x.Fighter.Id == fighter.Id); if (competitionFighter == null) { competitionFighter = new CompetitionFighter { Competition = competition, Fighter = fighter }; using (var transaction = session.BeginTransaction()) { session.Save(competitionFighter); transaction.Commit(); } competition.Fighters.Add(competitionFighter); } if (seedIndex != -1 && fields.Length > seedIndex) { double?newSeed = null; if (double.TryParse(fields[seedIndex], NumberStyles.Any, CultureInfo.InvariantCulture, out var seed)) { newSeed = seed; } if (competitionFighter.Seed != newSeed) { competitionFighter.Seed = newSeed; using (var transaction = session.BeginTransaction()) { session.Update(competitionFighter); transaction.Commit(); } } } if (countryIndex != -1 && fields.Length > countryIndex) { var p = Country.Countries.SingleOrDefault(x => string.Equals(x.Key, fields[countryIndex], StringComparison.InvariantCultureIgnoreCase)); if (!string.IsNullOrWhiteSpace(p.Key)) { fighter.CountryCode = p.Key; } else { p = Country.Countries.SingleOrDefault(x => string.Equals(x.Value, fields[countryIndex], StringComparison.InvariantCultureIgnoreCase)); if (!string.IsNullOrWhiteSpace(p.Key)) { fighter.CountryCode = p.Key; } } } if (organizationIndexes.Any()) { fighter.Organizations.Clear(); foreach (var organizationIndex in organizationIndexes) { if (organizationIndex >= fields.Length || string.IsNullOrWhiteSpace(fields[organizationIndex])) { continue; } var organization = organizations.SingleOrDefault(x => string.Equals(x.Name, fields[organizationIndex], StringComparison.InvariantCultureIgnoreCase) || x.Aliases.Any(alias => string.Equals(alias, fields[organizationIndex], StringComparison.InvariantCultureIgnoreCase))); if (organization == null) { var multiOrganization = fields[organizationIndex].Split('/', '\\', ',', '+'); if (multiOrganization.Length > 1 && organizations.Any(x => string.Equals(x.Name, multiOrganization[0].Trim(), StringComparison.InvariantCultureIgnoreCase) || x.Aliases.Any(alias => string.Equals(alias, multiOrganization[0].Trim(), StringComparison.InvariantCultureIgnoreCase)))) { foreach (var org in multiOrganization) { organization = organizations.SingleOrDefault(x => string.Equals(x.Name, org.Trim(), StringComparison.InvariantCultureIgnoreCase) || x.Aliases.Any(alias => string.Equals(alias, org.Trim(), StringComparison.InvariantCultureIgnoreCase))); if (organization == null) { organization = new Organization { Name = org.Trim() }; using (var transaction = session.BeginTransaction()) { session.Save(organization); transaction.Commit(); } organizations.Add(organization); } if (!fighter.Organizations.Contains(organization)) { fighter.Organizations.Add(organization); } } } else { organization = new Organization { Name = fields[organizationIndex] }; using (var transaction = session.BeginTransaction()) { session.Save(organization); transaction.Commit(); } organizations.Add(organization); fighter.Organizations.Add(organization); } } else { if (!fighter.Organizations.Contains(organization)) { fighter.Organizations.Add(organization); } } } } using (var transaction = session.BeginTransaction()) { session.Update(fighter); transaction.Commit(); } } catch (MalformedLineException ex) { //parser.ErrorLine; //parser.ErrorLineNumber; } } } } using (var transaction = session.BeginTransaction()) { session.Update(competition); transaction.Commit(); } NHibernateUtil.Initialize(competition.Fighters); foreach (var person in competition.Fighters) { NHibernateUtil.Initialize(person.Fighter); NHibernateUtil.Initialize(person.Fighter.Organizations); } NHibernateUtil.Initialize(competition.Matches); NHibernateUtil.Initialize(competition.Phases); NHibernateUtil.Initialize(competition.MatchRules); NHibernateUtil.Initialize(competition.RankingRules); return(new CompetitionDetailView(competition)); } }
public RasporedSudijaForm(int takmicenjeId, DeoTakmicenjaKod deoTakKod) { InitializeComponent(); this.ClientSize = new Size(1150, 540); this.StartPosition = FormStartPosition.CenterScreen; this.deoTakKod = deoTakKod; this.Text = "Raspored sudija - " + DeoTakmicenjaKodovi.toString(deoTakKod); Cursor.Current = Cursors.WaitCursor; Cursor.Show(); ISession session = null; try { using (session = NHibernateHelper.Instance.OpenSession()) using (session.BeginTransaction()) { CurrentSessionContext.Bind(session); kategorijeCount = DAOFactoryFactory.DAOFactory.GetTakmicarskaKategorijaDAO() .GetCountForTakmicenje(takmicenjeId); if (kategorijeCount == 0) { throw new Exception("Greska u programu."); } rasporedi = DAOFactoryFactory.DAOFactory.GetRasporedSudijaDAO() .FindByTakmicenjeDeoTak(takmicenjeId, deoTakKod); takmicenje = DAOFactoryFactory.DAOFactory.GetTakmicenjeDAO().FindById(takmicenjeId); NHibernateUtil.Initialize(takmicenje); // Potrebno za slucaj da ne postoje sudije na spravama vec samo vrhovni sudija. NHibernateUtil.Initialize(takmicenje.VrhovniSudija); // create tabs for (int i = 0; i < rasporedi.Count; i++) { createTab(rasporedi[i]); } tabOpened = new List <bool>(); for (int i = 0; i < rasporedi.Count; i++) { tabOpened.Add(false); } // show first tab if (rasporedi.Count > 0) { if (tabControl1.SelectedIndex != 0) { tabControl1.SelectedIndex = 0; } else { onSelectedIndexChanged(); } } else { tabControl1.TabPages.Remove(tabPage1); } } } catch (Exception ex) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw new InfrastructureException(ex.Message, ex); } finally { Cursor.Hide(); Cursor.Current = Cursors.Arrow; CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory); } }
public void Initialize(object obj) { NHibernateUtil.Initialize(obj); }
public void InvalidValuesInCollections() { // we are testing it using proxies created by NH Person parent = CreateGrandparent(); SavePerson(parent); // Generic collection using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { Person p = s.CreateQuery("from Person p where p.Name = 'GP'") .UniqueResult <Person>(); IEnumerator <Person> ep = p.Children.GetEnumerator(); ep.MoveNext(); Person aChildren = ep.Current; IEnumerator <Person> ep1 = aChildren.Children.GetEnumerator(); ep1.MoveNext(); Person aCh11 = ep1.Current; Assert.IsTrue(vengine.IsValid(p)); aCh11.Name = null; Assert.IsFalse(vengine.IsValid(p)); tx.Rollback(); } // No generic collection using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { Person p = s.CreateQuery("from Person p where p.Name = 'GP'") .UniqueResult <Person>(); IEnumerator ep = p.Friends.GetEnumerator(); ep.MoveNext(); Person aFriend = (Person)ep.Current; Assert.IsTrue(vengine.IsValid(p)); aFriend.Name = "A"; Assert.IsFalse(vengine.IsValid(p)); tx.Rollback(); } // Many-to-one using (ISession s = OpenSession()) using (ITransaction tx = s.BeginTransaction()) { Person p = s.CreateQuery("from Person p where p.Name = 'C1'") .UniqueResult <Person>(); NHibernateUtil.Initialize(p.Parent); Assert.IsTrue(vengine.IsValid(p)); p.Parent.Name = "A"; Assert.IsFalse(vengine.IsValid(p)); tx.Rollback(); } CleanUp(); }
/// <summary> /// Find out if a bidirectional relation exists, if exists then add entity to the collection /// </summary> /// <param name="manyToOneType">Many to one relation</param> /// <param name="childEntityType">Entity type of the child</param> /// <param name="propertyName">Property name of the ManyToOne realtion</param> /// <param name="childEntityInfo">Entity info of the child</param> /// <param name="childMeta">Child metadata</param> /// <returns>true if the child entity was added or removed from the parent entity collection, otherwise false</returns> private bool TryToFindAndLinkBidirectionalRelation(ManyToOneType manyToOneType, EntityType childEntityType, string propertyName, EntityInfo childEntityInfo, IClassMetadata childMeta) { var fk = FindForeignKey(propertyName, childMeta); var parentMeta = session.SessionFactory.GetClassMetadata(manyToOneType.ReturnedClass); var propNames = parentMeta.PropertyNames; var propTypes = parentMeta.PropertyTypes; var childPersister = childMeta as AbstractEntityPersister; if (childPersister == null) { return(false); } var colProp = new Dictionary <string, string>(); for (var i = 0; i < childPersister.PropertyNames.Length; i++) { var propName = childPersister.PropertyNames[i]; var propType = childPersister.GetPropertyType(propName); if (propType.IsAssociationType) { continue; } foreach (var col in childPersister.GetPropertyColumnNames(i)) { if (col == null) { continue; // formula } if (!colProp.ContainsKey(col)) { colProp.Add(col, propName); } } } if (childPersister.IdentifierType.IsComponentType) { var componentType = (ComponentType)childPersister.IdentifierType; for (var i = 0; i < componentType.PropertyNames.Length; i++) { colProp.Add(childPersister.IdentifierColumnNames[i], componentType.PropertyNames[i]); } } else { foreach (var col in childPersister.IdentifierColumnNames) { colProp.Add(col, childPersister.IdentifierPropertyName); } } for (var i = 0; i < propNames.Length; i++) { var propType = propTypes[i]; var propName = propNames[i]; if (!propType.IsAssociationType || !propType.IsCollectionType) { continue; } var colType = (CollectionType)propType; var refCols = colType.GetReferencedColumns(session.GetSessionImplementation().Factory); var refProps = refCols.Select(refCol => !colProp.ContainsKey(refCol) ? refCol : colProp[refCol]).ToArray(); if (NHMetadataBuilder.CatColumnNames(refProps) != fk) { continue; } var elmType = colType.GetElementType(session.GetSessionImplementation().Factory); if (!elmType.ReturnedClass.IsAssignableFrom(childMeta.MappedClass)) { continue; } var parentEntity = GetRelatedEntity(propertyName, childEntityType, childEntityInfo, childMeta); if (parentEntity == null) { return(false); } var coll = parentMeta.GetPropertyValue(parentEntity, propName) as IEnumerable; if (coll == null) //Should happen only if the parent entity is not in db { //TODO: instantiate collection continue; } var collType = coll.GetType(); //Initialize collection in order to prevent flushing if (!NHibernateUtil.IsInitialized(coll)) { NHibernateUtil.Initialize(coll); } if (colType.ReturnedClass.IsGenericType) { var state = childEntityInfo.EntityState; if (saveMap.ContainsKey(manyToOneType.ReturnedClass)) { var parentEntityInfo = saveMap[manyToOneType.ReturnedClass].FirstOrDefault(o => o.Entity == parentEntity); if (parentEntityInfo != null) { switch (parentEntityInfo.EntityState) { case EntityState.Added: //if the parent is added then we need to add child to the collection even if the it is only updated or unmodified if (state != EntityState.Deleted) { state = EntityState.Added; } break; case EntityState.Deleted: //TODO: check for cascade option break; case EntityState.Modified: break; } } } //TODO: check if parent is new switch (state) { case EntityState.Deleted: var removeMethod = collType.GetMethod("Remove") ?? collType.GetInterfaces() .Select(o => o.GetMethod("Remove")) .FirstOrDefault(o => o != null); var removed = false; if (removeMethod != null) { IEqualityComparer comparer = new EntityComparer(childMeta); foreach (var item in coll) { if (comparer.Equals(item, childEntityInfo.Entity)) { removed = (bool)removeMethod.Invoke(coll, new[] { item }); break; } } } childMeta.SetPropertyValue(childEntityInfo.Entity, propertyName, null); //Remove relation on both sides return(removed); case EntityState.Added: var addMethod = collType.GetMethod("Add") ?? collType.GetInterfaces() .Select(o => o.GetMethod("Add")) .FirstOrDefault(o => o != null); if (addMethod != null) { addMethod.Invoke(coll, new[] { childEntityInfo.Entity }); return(true); } break; } } //TODO: non generic collections } return(false); }
public int Update(ArtistForEditContract properties, EntryPictureFileContract pictureData, IUserPermissionContext permissionContext) { ParamIs.NotNull(() => properties); ParamIs.NotNull(() => permissionContext); return(repository.HandleTransaction(ctx => { var artist = ctx.Load(properties.Id); VerifyEntryEdit(artist); var diff = new ArtistDiff(DoSnapshot(artist.GetLatestVersion(), ctx.OfType <User>().GetLoggedUser(permissionContext))); ctx.AuditLogger.SysLog(string.Format("updating properties for {0}", artist)); if (artist.ArtistType != properties.ArtistType) { artist.ArtistType = properties.ArtistType; diff.ArtistType.Set(); } diff.Description.Set(artist.Description.CopyFrom(properties.Description)); if (artist.TranslatedName.DefaultLanguage != properties.DefaultNameLanguage) { artist.TranslatedName.DefaultLanguage = properties.DefaultNameLanguage; diff.OriginalName.Set(); } // Required because of a bug in NHibernate NHibernateUtil.Initialize(artist.Picture); if (pictureData != null) { var parsed = ImageHelper.GetOriginal(pictureData.UploadedFile, pictureData.ContentLength, pictureData.Mime); artist.Picture = new PictureData(parsed); artist.PictureMime = parsed.Mime; pictureData.Id = artist.Id; pictureData.EntryType = EntryType.Artist; var thumbGenerator = new ImageThumbGenerator(imagePersister); thumbGenerator.GenerateThumbsAndMoveImage(pictureData.UploadedFile, pictureData, ImageSizes.Thumb | ImageSizes.SmallThumb | ImageSizes.TinyThumb); diff.Picture.Set(); } if (artist.Status != properties.Status) { artist.Status = properties.Status; diff.Status.Set(); } var nameDiff = artist.Names.Sync(properties.Names, artist); ctx.OfType <ArtistName>().Sync(nameDiff); if (nameDiff.Changed) { diff.Names.Set(); } if (!artist.BaseVoicebank.NullSafeIdEquals(properties.BaseVoicebank)) { var newBase = ctx.NullSafeLoad(properties.BaseVoicebank); if (artist.IsValidBaseVoicebank(newBase)) { diff.BaseVoicebank.Set(); artist.SetBaseVoicebank(ctx.NullSafeLoad(properties.BaseVoicebank)); } } if (!artist.ReleaseDate.Equals(properties.ReleaseDate)) { artist.ReleaseDate = properties.ReleaseDate; diff.ReleaseDate.Set(); } var webLinkDiff = WebLink.Sync(artist.WebLinks, properties.WebLinks, artist); ctx.OfType <ArtistWebLink>().Sync(webLinkDiff); if (webLinkDiff.Changed) { diff.WebLinks.Set(); } if (diff.ArtistType.IsChanged || diff.Names.IsChanged) { foreach (var song in artist.Songs) { song.Song.UpdateArtistString(); ctx.Update(song); } } var newGroups = properties.Groups .Select(g => new ArtistForArtistContract { Parent = g.Parent, LinkType = ArtistLinkType.Group }) .Concat(new[] { new ArtistForArtistContract { Parent = properties.Illustrator, LinkType = ArtistLinkType.Illustrator }, new ArtistForArtistContract { Parent = properties.VoiceProvider, LinkType = ArtistLinkType.VoiceProvider } }) .Concat(properties.AssociatedArtists) .Where(a => a.Parent != null && ArtistHelper.CanHaveRelatedArtists(artist.ArtistType, a.LinkType, LinkDirection.ManyToOne)) .ToArray(); var groupsDiff = CollectionHelper.Diff(artist.Groups, newGroups, (i, i2) => (i.Parent.Id == i2.Parent.Id && i.LinkType == i2.LinkType)); foreach (var grp in groupsDiff.Removed) { grp.Delete(); ctx.Delete(grp); } foreach (var grp in groupsDiff.Added) { var link = artist.AddGroup(ctx.Load(grp.Parent.Id), grp.LinkType); ctx.Save(link); } if (groupsDiff.Changed) { diff.Groups.Set(); } var picsDiff = artist.Pictures.SyncPictures(properties.Pictures, ctx.OfType <User>().GetLoggedUser(permissionContext), artist.CreatePicture); ctx.OfType <ArtistPictureFile>().Sync(picsDiff); var entryPictureFileThumbGenerator = new ImageThumbGenerator(pictureFilePersister); artist.Pictures.GenerateThumbsAndMoveImage(entryPictureFileThumbGenerator, picsDiff.Added, ImageSizes.Original | ImageSizes.Thumb); if (picsDiff.Changed) { diff.Pictures.Set(); } var logStr = string.Format("updated properties for artist {0} ({1})", entryLinkFactory.CreateEntryLink(artist), diff.ChangedFieldsString) + (properties.UpdateNotes != string.Empty ? " " + properties.UpdateNotes : string.Empty) .Truncate(400); var archived = Archive(ctx, artist, diff, ArtistArchiveReason.PropertiesUpdated, properties.UpdateNotes); ctx.Update(artist); ctx.AuditLogger.AuditLog(logStr); AddEntryEditedEntry(ctx.OfType <ActivityEntry>(), artist, EntryEditEvent.Updated, archived); return artist.Id; })); }
public void Merge(int sourceId, int targetId) { PermissionContext.VerifyPermission(PermissionToken.MergeEntries); if (sourceId == targetId) { throw new ArgumentException("Source and target albums can't be the same", "targetId"); } repository.HandleTransaction(session => { var source = session.Load(sourceId); var target = session.Load(targetId); session.AuditLogger.AuditLog(string.Format("Merging {0} to {1}", EntryLinkFactory.CreateEntryLink(source), EntryLinkFactory.CreateEntryLink(target))); NHibernateUtil.Initialize(source.CoverPictureData); NHibernateUtil.Initialize(target.CoverPictureData); foreach (var n in source.Names.Names.Where(n => !target.HasName(n))) { var name = target.CreateName(n.Value, n.Language); session.Save(name); } foreach (var w in source.WebLinks.Where(w => !target.HasWebLink(w.Url))) { var link = target.CreateWebLink(w.Description, w.Url, w.Category); session.Save(link); } var artists = source.Artists.Where(a => !target.HasArtistForAlbum(a)).ToArray(); foreach (var a in artists) { a.Move(target); session.Update(a); } var songs = source.Songs.Where(s => s.Song == null || !target.HasSong(s.Song)).ToArray(); foreach (var s in songs) { s.Move(target); session.Update(s); } var pictures = source.Pictures.ToArray(); foreach (var p in pictures) { p.Move(target); session.Update(p); } var userCollections = source.UserCollections.Where(a => !target.IsInUserCollection(a.User)).ToArray(); foreach (var u in userCollections) { u.Move(target); session.Update(u); } target.Description.CopyIfEmpty(source.Description); if (target.OriginalRelease == null) { target.OriginalRelease = new AlbumRelease(); } if (string.IsNullOrEmpty(target.OriginalRelease.CatNum) && source.OriginalRelease != null) { target.OriginalRelease.CatNum = source.OriginalRelease.CatNum; } if (target.OriginalRelease.ReleaseEvent == null && source.OriginalRelease != null) { target.OriginalRelease.ReleaseEvent = source.OriginalRelease.ReleaseEvent; } if (target.OriginalRelease.ReleaseDate == null) { target.OriginalRelease.ReleaseDate = new OptionalDateTime(); } if (target.OriginalReleaseDate.Year == null && source.OriginalRelease != null) { target.OriginalReleaseDate.Year = source.OriginalReleaseDate.Year; } if (target.OriginalReleaseDate.Month == null && source.OriginalRelease != null) { target.OriginalReleaseDate.Month = source.OriginalReleaseDate.Month; } if (target.OriginalReleaseDate.Day == null && source.OriginalRelease != null) { target.OriginalReleaseDate.Day = source.OriginalReleaseDate.Day; } // Create merge record var mergeEntry = new AlbumMergeRecord(source, target); session.Save(mergeEntry); source.Deleted = true; target.UpdateArtistString(); target.Names.UpdateSortNames(); Archive(session, source, AlbumArchiveReason.Deleted, string.Format("Merged to {0}", target)); Archive(session, target, AlbumArchiveReason.Merged, string.Format("Merged from {0}", source)); session.Update(source); session.Update(target); }); }
private AlbumContract AcceptImportedAlbum(ISession session, ContentLanguageSelection languageSelection, InspectedAlbum acceptedAlbum, int[] selectedSongIds) { Album album; var diff = new AlbumDiff(false); if (acceptedAlbum.MergedAlbum == null) { album = new Album(new LocalizedString(acceptedAlbum.ImportedAlbum.Title, languageSelection)); if (languageSelection != ContentLanguageSelection.Unspecified) { album.Names.SortNames.DefaultLanguage = languageSelection; } album.DiscType = DiscType.Unknown; diff.Names = true; session.Save(album); } else { album = session.Load <Album>(acceptedAlbum.MergedAlbum.Id); NHibernateUtil.Initialize(album.CoverPictureData); if (!album.Names.HasName(acceptedAlbum.ImportedAlbum.Title)) { album.CreateName(acceptedAlbum.ImportedAlbum.Title, languageSelection); diff.Names = true; } } foreach (var inspectedArtist in acceptedAlbum.Artists) { if (inspectedArtist.ExistingArtist != null) { var artist = session.Load <Artist>(inspectedArtist.ExistingArtist.Id); if (!artist.HasAlbum(album)) { session.Save(artist.AddAlbum(album)); diff.Artists = true; } } else { album.AddArtist(inspectedArtist.Name, false, ArtistRoles.Default); diff.Artists = true; } } if (acceptedAlbum.MergedAlbum == null || acceptedAlbum.MergeTracks) { foreach (var inspectedTrack in acceptedAlbum.Tracks) { if (AcceptImportedSong(session, album, inspectedTrack, languageSelection, selectedSongIds)) { diff.Tracks = true; } } } var importedAlbum = session.Load <MikuDbAlbum>(acceptedAlbum.ImportedAlbum.Id); importedAlbum.Status = AlbumStatus.Approved; if (importedAlbum.CoverPicture != null && album.CoverPictureData == null) { album.CoverPictureData = importedAlbum.CoverPicture; using (var stream = new MemoryStream(album.CoverPictureData.Bytes)) { var thumbs = ImageHelper.GenerateThumbs(stream, new[] { 250 }); if (thumbs.Any()) { album.CoverPictureData.Thumb250 = new PictureThumb250(thumbs.First().Bytes); } } diff.Cover = true; } if (acceptedAlbum.ImportedAlbum.Data.ReleaseYear != null && album.OriginalReleaseDate.Year == null) { album.OriginalReleaseDate.Year = acceptedAlbum.ImportedAlbum.Data.ReleaseYear; diff.OriginalRelease = true; } if (!album.WebLinks.Any(w => w.Url.Contains("mikudb.com"))) { album.CreateWebLink("MikuDB", acceptedAlbum.ImportedAlbum.SourceUrl, WebLinkCategory.Reference); diff.WebLinks = true; } album.UpdateArtistString(); AuditLog(string.Format("accepted imported album '{0}'", acceptedAlbum.ImportedAlbum.Title), session); AddEntryEditedEntry(session, album, EntryEditEvent.Created); Services.Albums.Archive(session, album, diff, AlbumArchiveReason.AutoImportedFromMikuDb); session.Update(album); session.Update(importedAlbum); return(new AlbumContract(album, PermissionContext.LanguagePreference)); }
public void ProxyReuse() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); FooProxy foo = new Foo(); FooProxy foo2 = new Foo(); object id = s.Save(foo); object id2 = s.Save(foo2); foo2.Int = 1234567; foo.Int = 1234; t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); foo = (FooProxy)s.Load(typeof(Foo), id); foo2 = (FooProxy)s.Load(typeof(Foo), id2); Assert.IsFalse(NHibernateUtil.IsInitialized(foo)); NHibernateUtil.Initialize(foo2); NHibernateUtil.Initialize(foo); Assert.AreEqual(3, foo.Component.ImportantDates.Length); Assert.AreEqual(3, foo2.Component.ImportantDates.Length); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); foo.Float = 1.2f; foo2.Float = 1.3f; foo2.Dependent.Key = null; foo2.Component.Subcomponent.Fee.Key = null; Assert.IsFalse(foo2.Key.Equals(id)); s.Save(foo, "xyzid"); s.Update(foo2, id); //intentionally id, not id2! Assert.AreEqual(id, foo2.Key); Assert.AreEqual(1234567, foo2.Int); Assert.AreEqual("xyzid", foo.Key); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); foo = (FooProxy)s.Load(typeof(Foo), id); Assert.AreEqual(1234567, foo.Int); Assert.AreEqual(3, foo.Component.ImportantDates.Length); s.Delete(foo); s.Delete(s.Get(typeof(Foo), id2)); s.Delete(s.Get(typeof(Foo), "xyzid")); Assert.AreEqual(3, s.Delete("from System.Object")); t.Commit(); s.Close(); string feekey = foo.Dependent.Key; s = OpenSession(); t = s.BeginTransaction(); foo.Component.Glarch = null; //no id property! s.Replicate(foo, ReplicationMode.Overwrite); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); Foo refoo = (Foo)s.Get(typeof(Foo), id); Assert.AreEqual(feekey, refoo.Dependent.Key); s.Delete(refoo); t.Commit(); s.Close(); }
public KvalifikantiTak2Form(int takmicenjeId) { InitializeComponent(); ISession session = null; try { using (session = NHibernateHelper.Instance.OpenSession()) using (session.BeginTransaction()) { CurrentSessionContext.Bind(session); IList <RezultatskoTakmicenje> svaRezTakmicenja = loadRezTakmicenja(takmicenjeId); if (svaRezTakmicenja.Count == 0) { throw new BusinessException(Strings.NO_KATEGORIJE_I_TAKMICENJA_ERROR_MSG); } rezTakmicenja = new List <RezultatskoTakmicenje>(); foreach (RezultatskoTakmicenje rt in svaRezTakmicenja) { if (rt.odvojenoTak2()) { rezTakmicenja.Add(rt); } } if (rezTakmicenja.Count == 0) { throw new BusinessException("Ne postoji odvojeno takmicenje II ni za jednu kategoriju."); } takmicenje = DAOFactoryFactory.DAOFactory.GetTakmicenjeDAO().FindById(takmicenjeId); NHibernateUtil.Initialize(takmicenje); initUI(); takmicenjeOpened = new bool[rezTakmicenja.Count]; cmbTakmicenje.SelectedIndex = 0; cmbTakmicenje.SelectedIndexChanged += new EventHandler(cmbTakmicenje_SelectedIndexChanged); //onSelectedTakmicenjeChanged(); } } catch (BusinessException) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw; } catch (InfrastructureException) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw; } catch (Exception ex) { if (session != null && session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } throw new InfrastructureException(ex.Message, ex); } finally { CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory); } }
public void SubselectFetchCriteria() { ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); Parent p = new Parent("foo"); p.Children.Add(new Child("foo1")); p.Children.Add(new Child("foo2")); Parent q = new Parent("bar"); q.Children.Add(new Child("bar1")); q.Children.Add(new Child("bar2")); ArrayHelper.AddAll(q.MoreChildren, p.Children); s.Save(p); s.Save(q); t.Commit(); s.Close(); s = OpenSession(); t = s.BeginTransaction(); sessions.Statistics.Clear(); IList parents = s.CreateCriteria(typeof(Parent)) .Add(Expression.Between("Name", "bar", "foo")) .AddOrder(Order.Desc("Name")) .List(); p = (Parent)parents[0]; q = (Parent)parents[1]; Assert.IsFalse(NHibernateUtil.IsInitialized(p.Children)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(p.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(p.Children[0])); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children)); Assert.AreEqual(q.Children.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.Children[0])); Assert.IsFalse(NHibernateUtil.IsInitialized(p.MoreChildren)); Assert.IsFalse(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(p.MoreChildren.Count, 0); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren)); Assert.AreEqual(q.MoreChildren.Count, 2); Assert.IsTrue(NHibernateUtil.IsInitialized(q.MoreChildren[0])); Assert.AreEqual(3, sessions.Statistics.PrepareStatementCount); Child c = (Child)p.Children[0]; NHibernateUtil.Initialize(c.Friends); s.Delete(p); s.Delete(q); t.Commit(); s.Close(); }
public User DoLogin(User user) { MsgResult msg = new MsgResult(); using (ISession session = DbUtils.GetSession()) { user = session .CreateCriteria(typeof(User)) .Add(Restrictions.Eq("Username", user.Username)) .UniqueResult <User>(); if ("admin".Equals(user.Username)) { user.Menus = session .CreateCriteria(typeof(Menu)) .List <Menu>();; } IList <Menu> menus = new List <Menu>(); if (user != null) { //加載懶加載的數據 NHibernateUtil.Initialize(user.Menus); foreach (Menu menu in user.Menus) { NHibernateUtil.Initialize(menu.Prems); menus.Add(menu); } NHibernateUtil.Initialize(user.Roles); foreach (Role role in user.Roles) { NHibernateUtil.Initialize(role.Menus); foreach (Menu menu in role.Menus) { NHibernateUtil.Initialize(menu.Prems); bool flag = true; foreach (Menu m in menus) { if (menu.Id == m.Id) { flag = false; } } if (flag) { menus.Add(menu); } } } NHibernateUtil.Initialize(user.Groups); foreach (Group group in user.Groups) { NHibernateUtil.Initialize(group.Roles); foreach (Role role in group.Roles) { NHibernateUtil.Initialize(role.Menus); foreach (Menu menu in role.Menus) { NHibernateUtil.Initialize(menu.Prems); bool flag = true; foreach (Menu m in menus) { if (menu.Id == m.Id) { flag = false; } } if (flag) { menus.Add(menu); } } } } user.Menus = menus; } return(user); } }