private void _RemoveFromGroup(NHibernate.ISession session) { var user = session.QueryOver <UserModel>().Where(u => u.UserId == _removeFromGroupUserId).List().FirstOrDefault(); if (user == null) { throw new InvalidOperationException($"User (UserId: {_removeFromGroupUserId}) does not exist."); } var group = session.QueryOver <GroupModel>().Where(g => g.GroupId == _removeFromGroupGroupId).List().FirstOrDefault(); if (group == null) { throw new InvalidOperationException($"Group (GroupId: {_removeFromGroupGroupId}) does not exist."); } // Zgłoś błąd jeśli użytkownik nie jest przypisany do grupy z której próbujesz go usunąć. if (!user.Groups.Contains(group)) { throw new InvalidOperationException($"User is not in a group: {group.Name}"); } user.Groups.Remove(group); session.Update(user); }
private void _Read(NHibernate.ISession session) { var query = session.QueryOver <T>(); SearchCriteria.ApplyToQuery(query); _resourcesFound = query.List(); }
public void removeStagione(Stagione stagione) { stagioni.Remove(stagione); DB.deleteStagione(stagione); if (isStagioneCorrente(stagione)) { // refresh stagioni stagione_corrente = null; stagioni.Clear(); using (NHibernate.ISession session = HibernateHelper.Open()) using (NHibernate.ITransaction transaction = session.BeginTransaction()) try { IList <Stagione> dbstagioni = session.QueryOver <Stagione>().OrderBy(x => x.DataFine).Desc.List(); foreach (Stagione p in dbstagioni) { stagioni.Add(p); if (stagione_corrente == null || p.DataInizio > stagione_corrente.DataInizio) // calcola stagione corrente { stagione_corrente = p; } } } catch (Exception exc) { String errorString = "removeStagione(" + (stagione != null?(stagione.Descrizione ?? string.Empty):"null") + "): " + exc.Message; Log.Instance.WriteLine(Log.LogLevel.Error, errorString); } } }
public int GetCount <T>(Expression <Func <T, bool> > query) where T : class, new() { int PiadUser = 0; try { using (NHibernate.ISession session = SessionFactory.GetNewSession(_env)) { var futureCount = session.QueryOver <T>().Where(query) .Select(NHibernate.Criterion.Projections.RowCount()) .FutureValue <int>() .Value; PiadUser = Convert.ToInt32(futureCount); } } catch (Exception ex) { _logger.LogCritical(ex.Message); _logger.LogError(ex.StackTrace); try { _logger.LogError(ex.InnerException.Message); } catch { } } return(PiadUser); }
/// <summary> /// Indexes the specified id. /// </summary> /// <param name="id">The id.</param> /// <returns>ActionResult.</returns> public ActionResult Index(int id) { Event evt; using (var trans = _session.BeginTransaction()) { evt = _session.QueryOver <Event>() .Where(e => e.Id == id) .SingleOrDefault(); trans.Commit(); } return(View(new BoardView { Event = evt })); }
public IList <Role> GetSearchedRole(string searchItem) { Role roleAlias = null; IList <Role> RoleList = NHSession.QueryOver(() => roleAlias) .Where(() => roleAlias.Name.IsInsensitiveLike(searchItem, MatchMode.Anywhere)) .List <Role>(); return(RoleList); }
//[Route("[Action]")] public ActionResult Get(string naziv) { var query = _session.QueryOver<Parametar>(); if(! string.IsNullOrEmpty(naziv)) query.WhereRestrictionOn(x => x.Naziv).IsInsensitiveLike(naziv); var result = query.List<Parametar>(); return Ok(result); }
private static List <string> GetDBResponses <T>(NHibernate.ISession session, Expression <Func <T, bool> > clause) where T : EnumLookupEntity <int> { return (session.QueryOver <T>().OrderBy(x => x.Value).Asc.List().Select((x, index) => String.Format("{0},{1},{2},{3}", x.Id, Inflector.Titleize(x.Name), index + 1, clause.Compile()(x) ? "Include" : "Exclude")).ToList()); }
public static NotaDePedido RecuperarUltima(NHibernate.ISession nhSesion) { try { NotaDePedido notaDePedido = nhSesion.QueryOver <NotaDePedido>().OrderBy(x => x.Codigo).Desc.Take(1).SingleOrDefault(); return(notaDePedido); } catch (Exception ex) { throw ex; } }
public static Factura RecuperarUltima(NHibernate.ISession nhSesion) { try { Factura factura = nhSesion.QueryOver <Factura>().OrderBy(x => x.Codigo).Desc.Take(1).SingleOrDefault(); return(factura); } catch (Exception ex) { throw ex; } }
public IEnumerator <Models.Contact> GetEnumerator() { var contacts = session.QueryOver <Contact>().List().Select(contactEntity => new Models.Contact { Id = contactEntity.Id, Name = contactEntity.Name, Address = contactEntity.Address, Phone = contactEntity.Phone }); return(contacts.GetEnumerator()); }
private void _AddToGroup(NHibernate.ISession session) { var user = session.QueryOver <UserModel>().Where(u => u.UserId == _addToGroupUserId).List().FirstOrDefault(); if (user == null) { throw new InvalidOperationException($"User (UserId: {_addToGroupUserId}) does not exist."); } var group = session.QueryOver <GroupModel>().Where(g => g.GroupId == _addToGroupGroupId).List().FirstOrDefault(); if (group == null) { throw new InvalidOperationException($"Group (GroupId: {_addToGroupGroupId}) does not exist."); } // Zgłoś błąd jeśli użytkownik jest już przypisany do tej grupy. if (user.Groups.Contains(group)) { throw new InvalidOperationException($"User is already in a group: {group.Name}"); } user.Groups.Add(group); session.Update(user); }
public int GetInstagramCommentCount(string ProfileIds, int days) { //Creates a database connection and opens up a session using (NHibernate.ISession session = SessionFactory.GetNewSession()) { try { string[] arrsrt = ProfileIds.Split(','); var likecount = session.QueryOver <Domain.Socioboard.Domain.InstagramPostComments>().Where(U => U.Created_Time <DateTime.Now && U.Created_Time> DateTime.Now.AddDays(-days).Date.AddSeconds(-1)).AndRestrictionOn(m => m.Profile_Id).IsIn(arrsrt).Select(Projections.RowCount()).FutureValue <int>().Value; return(Int32.Parse(likecount.ToString())); } catch (Exception ex) { return(0); } } }
public int GetInboxMessageCount(Guid UserId, string profileids) { //Creates a database connection and opens up a session using (NHibernate.ISession session = SessionFactory.GetNewSession()) { try { string[] arrsrt = profileids.Split(','); var results = session.QueryOver <Domain.Socioboard.Domain.InboxMessages>().Where(U => U.UserId == UserId && U.Status == 0).AndRestrictionOn(m => m.ProfileId).IsIn(arrsrt).Select(Projections.RowCount()).FutureValue <int>().Value; return(Int16.Parse(results.ToString())); } catch (Exception ex) { return(0); } } }
public int GetInsagramFollowingCount(Guid UserId, string ProfileIds, int days) { using (NHibernate.ISession session = SessionFactory.GetNewSession()) { try { string[] arrsrt = ProfileIds.Split(','); var results = session.QueryOver <Domain.Socioboard.Domain.InboxMessages>().Where(U => U.UserId == UserId && U.MessageType == "insta_following" && U.Status == 0 && U.CreatedTime <DateTime.Now && U.CreatedTime> DateTime.Now.AddDays(-days).Date.AddSeconds(-1)).AndRestrictionOn(m => m.ProfileId).IsIn(arrsrt).Select(Projections.RowCount()).FutureValue <int>().Value; return(Int16.Parse(results.ToString())); } catch (Exception ex) { logger.Error("GetInstagramFollowersCount => " + ex.Message); return(0); } } }
public int GetTwitterDirectMessageRecievedCount(Guid UserId, string profileids, int days) { //Creates a database connection and opens up a session using (NHibernate.ISession session = SessionFactory.GetNewSession()) { try { string[] arrsrt = profileids.Split(','); var results = session.QueryOver <Domain.Socioboard.Domain.TwitterDirectMessages>().Where(U => U.UserId == UserId && U.Type == "twt_directmessages_received" && U.CreatedDate <DateTime.Now && U.CreatedDate> DateTime.Now.AddDays(-days).Date.AddSeconds(-1)).AndRestrictionOn(m => m.RecipientId).IsIn(arrsrt).Select(Projections.RowCount()).FutureValue <int>().Value; return(Int16.Parse(results.ToString())); } catch (Exception ex) { logger.Error("GetTwitterDirectMessageRecievedCount => " + ex.Message); return(0); } } }
public static List <Match> ToDb(this NHibernate.ISession session, IList <Entity.NHibernate.EventParent> competitions, DateTime dt) { PrepareForDb(ref competitions); List <Match> matches = new List <Match>(); // save both stores, this saves everything else via cascading // save both stores, this saves everything else via cascading var gcomps = competitions.GroupBy(_ => _.Key); // populate the database foreach (var competition in gcomps) { using (var transaction = session.BeginTransaction()) { var fcompetition = competition.First(); var gmatches = gcomps.SelectMany(_ => _.SelectMany(c => c.Matches.Where(m => new DateTime(m.Start) < dt))).ToList(); //foreach (var match in gmatches) // match.EventParent = fcompetition; if (session.QueryOver <Entity.NHibernate.EventParent>().RowCount() == 0 || session.QueryOver <Entity.NHibernate.EventParent>().Where(x => x.Key == competition.Key).RowCount() == 0) { session.SaveOrUpdate(competition.First()); } //var gmatches = gcomps.SelectMany(_ => _.SelectMany(c => c.Matches)); //foreach (var m in gmatches) // m.EventParent = fcompetition; var gml = gmatches.ToList(); matches.AddRange(gml); session.ToDb(gml); transaction.Commit(); } } return(matches); }
public int GetCount <T>(Expression <Func <T, bool> > query) where T : class, new() { int PiadUser = 0; try { using (NHibernate.ISession session = SessionFactory.GetNewSession()) { var futureCount = session.QueryOver <T>().Where(query) .Select(NHibernate.Criterion.Projections.RowCount()) .FutureValue <int>() .Value; PiadUser = Convert.ToInt32(futureCount); } } catch (Exception ex) { } return(PiadUser); }
/// <summary> /// Gets the messages. /// </summary> /// <param name="evt">The evt.</param> /// <returns>List{BoardMessage}.</returns> public List <BoardMessage> GetMessages(Event evt) { var messages = _database.List <Message, object>("[dbo].[Message_GetMessageByEventId]", new { eventId = evt.Id }).ToList(); using (var trans = _session.BeginTransaction()) { _aliasLookup = _session.QueryOver <Alias>() .Where(a => a.Event.Id == evt.Id) .List() .ToDictionary(a => a.Number); trans.Commit(); } messages = SetHashTag(evt, messages); var items = messages.Select(m => ConvertToBoardMessage(m, evt.Timezone)); return(items.ToList()); }
public static bool ToDb(this NHibernate.ISession session, IList <Entity.NHibernate.EventParent> competitions) { // save both stores, this saves everything else via cascading var gcomps = competitions.GroupBy(_ => _.Key); foreach (var competition in gcomps) { var fcompetition = competition.First(); var competitionId = fcompetition.Id; if (session.QueryOver <Entity.NHibernate.EventParent>().RowCount() == 0 || session.QueryOver <Entity.NHibernate.EventParent>().Where(x => x.Key == competition.Key).RowCount() == 0) { session.SaveOrUpdate(competition.First()); } var gmatches = gcomps.SelectMany(_ => _.SelectMany(c => c.Matches)); session.ToDb(gmatches.ToList()); } return(true); }
public static Stagione getStagioneCorrente() { Stagione ret = null; using (NHibernate.ISession session = HibernateHelper.Open()) using (NHibernate.ITransaction transaction = session.BeginTransaction()) try { IList <Stagione> stag = session.QueryOver <Stagione>().OrderBy(x => x.DataInizio).Desc.List(); ret = stag.Count == 0 ? null : stag.ElementAt(0); transaction.Commit(); } catch (Exception exc) { Log.Instance.WriteLine(Log.LogLevel.Error, "getStagioneCorrente::" + exc.Message); return(null); } return(ret); }
public int GetFeedCountByProfileIdAndUserId(Guid UserId, string profileids) { //Creates a database connection and opens up a session using (NHibernate.ISession session = SessionFactory.GetNewSession()) { //Begin session trasaction and opens up. using (NHibernate.ITransaction transaction = session.BeginTransaction()) { try { string[] arrsrt = profileids.Split(','); var results = session.QueryOver <Domain.Myfashion.Domain.FacebookFeed>().Where(U => U.UserId == UserId).AndRestrictionOn(m => m.ProfileId).IsIn(arrsrt).Select(Projections.RowCount()).FutureValue <int>().Value; return(Int16.Parse(results.ToString())); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); return(0); } } //End Transaction } // End se }
public List <ToolStripItem> LoadLayoutMenu() { var noDatabase = _session == null; var currentMenuLevel = new List <ToolStripItem>(); ToolStripMenuItem saveMenu; ToolStripMenuItem loadMenu; ToolStripMenuItem deleteMenu = null; var menuList = new List <ToolStripItem>(); #region Load Options //set up user load options foreach (var item in _userLayoutList) { var tempItem = item; var newOption = new ToolStripMenuItem { Text = item.Name + (CurrentLayout.Name == item.Name ? " (current)" : "") }; newOption.Click += (s, e) => CurrentLayout = tempItem; currentMenuLevel.Add(newOption); } //check if more needs to be done if (noDatabase) { loadMenu = new ToolStripMenuItem("Load", null, currentMenuLevel.ToArray()); } else { currentMenuLevel.Add(new ToolStripSeparator()); IList <LayoutProperty> databaseLayouts; lock (_session) databaseLayouts = _session.QueryOver <LayoutProperty>().List(); foreach (var item in databaseLayouts) { var tempItem = item; var newOption = new ToolStripMenuItem { Text = item.Name + (CurrentLayout.Name == item.Name ? " (current)" : "") }; newOption.Click += (s, e) => CurrentLayout = tempItem; currentMenuLevel.Add(newOption); } loadMenu = new ToolStripMenuItem("Load", null, currentMenuLevel.ToArray()); } #endregion #region Save Options //create user save list currentMenuLevel = new List <ToolStripItem>(); foreach (var item in _userLayoutList) { var tempItem = item; var newOption = new ToolStripMenuItem { Text = item.Name + (CurrentLayout.Name == item.Name ? " (current)" : "") }; newOption.Click += (s, e) => { var saveColumns = false; var formProperties = new Dictionary <string, FormProperty>(); if (MessageBox.Show("Save column settings as well?", "Save", MessageBoxButtons.YesNo) == DialogResult.Yes) { saveColumns = true; foreach (var form in _persistentForms) { formProperties[form.Name] = form.GetCurrentProperties(false); } } updateLayout(tempItem, saveColumns, false, formProperties); }; currentMenuLevel.Add(newOption); } //replace system default (not editable) with new layout option { var newLayout = new ToolStripMenuItem("New Local Layout"); newLayout.Click += (s, e) => { var textInput = new TextInputPrompt("Layout Name", true, string.Empty); if (textInput.ShowDialog() == DialogResult.OK) { var formProperties = new Dictionary <string, FormProperty>(); if (textInput.GetCheckState()) { foreach (var form in _persistentForms) { formProperties[form.Name] = form.GetCurrentProperties(false); } } saveNewLayout(textInput.GetText(), textInput.GetCheckState(), false, formProperties); } }; currentMenuLevel.RemoveAt(0); currentMenuLevel.Insert(0, newLayout); } //check if more needs to be done if (noDatabase) { saveMenu = new ToolStripMenuItem("Save", null, currentMenuLevel.ToArray()); } else { var currentDatabaseMenuLevel = new List <ToolStripItem>(); currentMenuLevel.Add(new ToolStripSeparator()); IList <LayoutProperty> databaseLayouts; lock (_session) databaseLayouts = _session.QueryOver <LayoutProperty>().List(); foreach (var item in databaseLayouts) { var newOption = new ToolStripMenuItem { Text = item.Name + (CurrentLayout.Name == item.Name ? " (current)" : "") }; LayoutProperty tempItem = item; newOption.Click += (s, e) => { var saveColumns = false; var formProperties = new Dictionary <string, FormProperty>(); if (MessageBox.Show("Save column settings as well?", "Save", MessageBoxButtons.YesNo) == DialogResult.Yes) { saveColumns = true; foreach (var form in _persistentForms) { formProperties[form.Name] = form.GetCurrentProperties(false); } } updateLayout(tempItem, saveColumns, true, formProperties); }; currentDatabaseMenuLevel.Add(newOption); } //Add new layout option { var newLayout = new ToolStripMenuItem("New Database Layout"); newLayout.Click += (s, e) => { var textInput = new TextInputPrompt("Layout Name", true, string.Empty); if (textInput.ShowDialog() == DialogResult.OK) { var formProperties = new Dictionary <string, FormProperty>(); if (textInput.GetCheckState()) { foreach (var form in _persistentForms) { formProperties[form.Name] = form.GetCurrentProperties(false); } } saveNewLayout(textInput.GetText(), textInput.GetCheckState(), true, formProperties); } }; currentDatabaseMenuLevel.Insert(0, newLayout); } currentMenuLevel.AddRange(currentDatabaseMenuLevel); saveMenu = new ToolStripMenuItem("Save", null, currentMenuLevel.ToArray()); } #endregion #region Delete Options //set up user delete options currentMenuLevel = new List <ToolStripItem>(); foreach (var item in _userLayoutList) { var tempItem = item; var newOption = new ToolStripMenuItem { Text = item.Name }; newOption.Click += (s, e) => { if (MessageBox.Show(string.Format("Are you sure you want to delete '{0}'?", tempItem.Name), "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes) { _userLayoutList.Remove(tempItem); SaveUserLayoutList(); } }; currentMenuLevel.Add(newOption); } //Dont allow user to delete defaults currentMenuLevel.RemoveRange(0, 2); //dont delete if nothing to delete, but check for database first if (noDatabase) { deleteMenu = currentMenuLevel.Count > 0 ? new ToolStripMenuItem("Delete", null, currentMenuLevel.ToArray()) : null; } else { var currentDatabaseMenuLevel = new List <ToolStripItem>(); if (currentMenuLevel.Count > 0) { currentMenuLevel.Add(new ToolStripSeparator()); } IList <LayoutProperty> databaseLayouts; lock (_session) databaseLayouts = _session.QueryOver <LayoutProperty>().List(); foreach (var item in databaseLayouts) { var tempItem = item; var newOption = new ToolStripMenuItem { Text = item.Name }; newOption.Click += (s, e) => { if (MessageBox.Show(string.Format("Are you sure you want to delete '{0}'?", tempItem.Name), "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes) { _session.Delete(tempItem); _session.Flush(); } }; currentDatabaseMenuLevel.Add(newOption); } currentDatabaseMenuLevel.RemoveAt(0); currentMenuLevel.AddRange(currentDatabaseMenuLevel); if (currentMenuLevel.Count > 0) { deleteMenu = new ToolStripMenuItem("Delete", null, currentMenuLevel.ToArray()); } } #endregion menuList.Add(saveMenu); menuList.Add(loadMenu); if (deleteMenu != null) { menuList.Add(deleteMenu); } return(menuList); }
public void ImportFromDb() { using (NHibernate.ISession session = HibernateHelper.Open()) using (NHibernate.ITransaction transaction = session.BeginTransaction()) try { stagione_corrente = null; IList <Stagione> dbstagioni = session.QueryOver <Stagione>().OrderBy(x => x.DataFine).Desc.List(); foreach (Stagione p in dbstagioni) { fetchStagione(p); stagioni.Add(p); if (stagione_corrente == null || p.DataInizio > stagione_corrente.DataInizio) // calcola stagione corrente { stagione_corrente = p; } } IList <ListinoCorsi> dblistino = session.QueryOver <ListinoCorsi>().List(); foreach (ListinoCorsi p in dblistino) { fetchListino(p); listini.Add(p); } IList <Chiusura> dbchiusure = session.QueryOver <Chiusura>().OrderBy(x => x.DataFine).Desc.List(); foreach (Chiusura p in dbchiusure) { chiusure.Add(p); } IList <Persona> dbpersone = session.QueryOver <Persona>().OrderBy(x => x.Cognome).Asc.ThenBy(x => x.Nome).Asc.ThenBy(x => x.DataNascita).Desc.List(); foreach (Persona p in dbpersone) { fetchPersona(p); persone.Add(p); } IList <Corso> dbcorsi = session.QueryOver <Corso>().OrderBy(x => x.Attivo).Desc.ThenBy(x => x.Codice).Asc.ThenBy(x => x.DataFine).Desc.List(); //.ThenBy(x => x.DataFine).Asc.ThenBy(x => x.DataInizio).Asc.List(); foreach (Corso p in dbcorsi) { fetchCorso(p); corsi.Add(p); } IList <Istruttore> dbistruttori = session.QueryOver <Istruttore>().OrderBy(x => x.Cognome).Asc.ThenBy(x => x.Nome).Asc.List(); foreach (Istruttore p in dbistruttori) { fetchIstruttore(p); istruttori.Add(p); } IList <Iscrizione> dbiscrizioni = session.QueryOver <Iscrizione>().List(); foreach (Iscrizione p in dbiscrizioni) { iscrizioni.Add(p); } transaction.Commit(); } catch (Exception exc) { String errorString = "ImportFromDb::" + exc.Message; Log.Instance.WriteLine(Log.LogLevel.Error, errorString); } }
/// <summary> /// Contacts the server from our beacon loop /// </summary> /// <param name="session"></param> /// <returns></returns> public bool ContactServer(NHibernate.ISession session) { bool ContactedServer = false; // Get info about all the new process events var processEvents = session.QueryOver <ProcessEvent>() .Where(e => e.HasInformedServer == false) .List <ProcessEvent>(); if (processEvents.Count() != 0) { foreach (var processEvent in processEvents) { // Get info about the exe associated ith this process Executable executable = null; try { executable = session.QueryOver <Executable>() .Where(e => e.Id == processEvent.ExecutableId) .List <Executable>().First(); } catch (Exception e) { // TODO Need to log this error Log.Exception(e, "Unable to find an executable for process event {0}", processEvent.Id); // I'll record in the DB that we already informed the server about this broken event } using (var transaction = session.BeginTransaction()) { if (executable == null) { // The executable for this process event was not found, so something broke, so just ignore it processEvent.HasInformedServer = true; session.Save(processEvent); transaction.Commit(); } else { if (Event.PostProcessEvent(processEvent, executable)) { // Record that we sent this data to the server so we don't try sending it again processEvent.HasInformedServer = true; session.Save(processEvent); transaction.Commit(); } ContactedServer = true; } } } } // Get info about all the new catalog files var catalogFiles = session.QueryOver <CatalogFile>() .Where(e => e.HasInformedServer == false) .List <CatalogFile>(); if (catalogFiles.Count() != 0) { foreach (var catalogFile in catalogFiles) { using (var transaction = session.BeginTransaction()) { if (Event.PostCatalogFile(catalogFile)) { // Record that we sent this data to the server so we don't try sending it again catalogFile.HasInformedServer = true; session.Save(catalogFile); transaction.Commit(); } } ContactedServer = true; } } if (!ContactedServer) { Log.Info("Posting heartbeat"); dynamic eventResponse = Event.PostHeartbeatEvent(); int avoidInfiniteLoop = 100; while (eventResponse != null) { // Sanity check, want to avoid infinite loop avoidInfiniteLoop--; if (avoidInfiniteLoop < 0) { break; } eventResponse = HandleServerResponse(eventResponse); } } return(ContactedServer); }