public void HqlBulk()
        {
            IStatelessSession ss = sessions.OpenStatelessSession();
            ITransaction      tx = ss.BeginTransaction();
            var doc = new Document("blah blah blah", "Blahs");

            ss.Insert(doc);
            var paper = new Paper {
                Color = "White"
            };

            ss.Insert(paper);
            tx.Commit();

            tx = ss.BeginTransaction();
            int count =
                ss.CreateQuery("update Document set Name = :newName where Name = :oldName").SetString("newName", "Foos").SetString(
                    "oldName", "Blahs").ExecuteUpdate();

            Assert.AreEqual(1, count, "hql-delete on stateless session");
            count = ss.CreateQuery("update Paper set Color = :newColor").SetString("newColor", "Goldenrod").ExecuteUpdate();
            Assert.AreEqual(1, count, "hql-delete on stateless session");
            tx.Commit();

            tx    = ss.BeginTransaction();
            count = ss.CreateQuery("delete Document").ExecuteUpdate();
            Assert.AreEqual(1, count, "hql-delete on stateless session");
            count = ss.CreateQuery("delete Paper").ExecuteUpdate();
            Assert.AreEqual(1, count, "hql-delete on stateless session");
            tx.Commit();
            ss.Close();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Insert data in bulk transaction.
        /// When input is integer many items are randomly generated, when a list of category is given input is saved directly.
        /// </summary>
        /// <param name="input"></param>
        public override void Execute(object input)
        {
            List <Category> itemsToAdd = new List <Category>();

            // this to allow this test to be called from outside with data or used for generate data
            if (input is List <Category> )
            {
                itemsToAdd = (List <Category>)input;
            }
            else
            {
                int addCount = (int)input;
                for (int i = 0; i < addCount; i++)
                {
                    itemsToAdd.Add(DataGenerator.NextCategory());
                }
            }

            using (IStatelessSession s = NHibernateContext.Current.SessionFactory.OpenStatelessSession())
            {
                var v = s.BeginTransaction();

                for (int i = 0; i < itemsToAdd.Count; i++)
                {
                    s.Insert(itemsToAdd[i]);
                    if (i % bulkSize == 0)
                    {
                        v.Commit();
                        v = s.BeginTransaction();
                    }
                }
                v.Commit();
                s.Close();
            }
        }
Exemplo n.º 3
0
 public override void Dispose()
 {
     if (_session != null)
     {
         _session.Close();
         _session.Dispose();
     }
 }
Exemplo n.º 4
0
        public void DoStatelessOpenCloseAndDispose()
        {
            using (IStatelessSession session = sessManager.OpenStatelessSession())
            {
                Assert.IsTrue(session.IsConnected);
                Assert.IsTrue(session.IsOpen);

                session.Close();

                Assert.IsFalse(session.IsConnected);
                Assert.IsFalse(session.IsOpen);
            }
        }
 public void DisposingClosedStatelessSessionShouldNotCauseSessionException()
 {
     try
     {
         IStatelessSession ss = sessions.OpenStatelessSession();
         ss.Close();
         ss.Dispose();
     }
     catch (SessionException)
     {
         Assert.Fail();
     }
 }
Exemplo n.º 6
0
        public bool OnPreUpdate(PreUpdateEvent e)
        {
            if (e.Entity is DomainEntity)
            {
                if (e.OldState == null)
                {
                    throw new AuditException();
                }

                var dirtyFieldIndexes = e.Persister.FindDirty(e.State, e.OldState, e.Entity, e.Session);

                if (dirtyFieldIndexes.Length > 0)
                {
                    var entity = e.Entity as DomainEntity;
                    entity.LastUpdatedAt = DateTime.UtcNow;

                    var changeLogs = new List <AuditChangeLog>();
                    if (e.Entity.GetType().GetInterface(typeof(IAuditable).Name) != null)
                    {
                        foreach (var dirtyFieldIndex in dirtyFieldIndexes)
                        {
                            if (e.OldState[dirtyFieldIndex] == e.State[dirtyFieldIndex])
                            {
                                continue;
                            }

                            //insert audit changelog here
                            var changeLog = new AuditChangeLog
                            {
                                EntityType       = e.Entity.GetType().Name,
                                EntityIdentifier = entity.Id.ToString(),
                                ActionType       = AuditType.Update,
                                PropertyName     = e.Persister.PropertyNames[dirtyFieldIndex]
                            };

                            changeLog.OldPropertyValue = GetPropertyValue(e.OldState[dirtyFieldIndex], changeLog.PropertyName, entity);
                            changeLog.NewPropertyValue = GetPropertyValue(e.State[dirtyFieldIndex], changeLog.PropertyName, entity);

                            changeLogs.Add(changeLog);
                        }

                        IStatelessSession session = e.Session.SessionFactory.OpenStatelessSession();
                        changeLogs.ForEach(log => session.Insert(log));
                        session.Close();
                    }
                }
            }

            return(false);
        }
Exemplo n.º 7
0
        public virtual void Dispose()
        {
            if (_session != null && _session.IsOpen)
            {
                _session.Close();
                _session.Dispose();
            }

            if (_statelessSession != null && _statelessSession.IsOpen)
            {
                _statelessSession.Close();
                _statelessSession.Dispose();
            }
        }
Exemplo n.º 8
0
        public static IList <object[]> StatelessGetBySql(string sql)
        {
            CheckSqlInjection(sql);
            IStatelessSession session = GetStatelessSession();

            try{
                return(session.CreateSQLQuery(sql).List <object[]>());
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                session.Close();
            }
        }
Exemplo n.º 9
0
        public static object StatelessGetScalarBySql(string sql)
        {
            CheckSqlInjection(sql);
            IStatelessSession session = GetStatelessSession();

            try{
                return(session.CreateSQLQuery(sql).UniqueResult());
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                session.Close();
            }
        }
Exemplo n.º 10
0
        public static void StatelessExecuteSql(string sql)
        {
            CheckSqlInjection(sql, true);
            IStatelessSession session = GetStatelessSession();

            try
            {
                session.CreateSQLQuery(sql).ExecuteUpdate();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                session.Close();
            }
        }
Exemplo n.º 11
0
 private void endStatelessSession()
 {
     try
     {
         if (stSession != null && stSession.Transaction != null && stSession.Transaction.IsActive)
         {
             if (commitTransaction)
             {
                 try
                 {
                     if (stSession.Transaction.IsActive)
                     {
                         stSession.Transaction.Commit();
                     }
                 }
                 catch (Exception ex)
                 {
                     //stSession.Transaction.Rollback();
                     throw new Exception("There were some changes submitted to the system that could not be committed!", ex);
                 }
             }
             else
             {
                 stSession.Transaction.Rollback();
             }
         }
     }
     finally
     {
         if (stSession.IsOpen)
         {
             stSession.Close();
         }
         if (showQueries)
         {
             Trace.WriteLine("SQL output at:" + DateTime.Now.ToString() + "--> " + "A conversation was closed. ID: " + stSession.GetHashCode());
         }
         stSession.Dispose();
         stSession = null;
         GC.Collect();
     }
 }
Exemplo n.º 12
0
        /// <summary>
        /// Flushes the queue of stored attribute updates and commits the changes to the database
        /// </summary>
        private void CommitCurrentAttributeUpdates()
        {
            if (GlobalSession.IsOpen)
            {
                GlobalSession.Close();
            }

            using (IStatelessSession session = SessionFactory.OpenStatelessSession())
            {
                var transaction = session.BeginTransaction();
                foreach (KeyValuePair <Guid, Dictionary <string, object> > componentUpdate in ComponentAttributesToPersist)
                {
                    Guid componentGuid = componentUpdate.Key;
                    foreach (KeyValuePair <string, object> attributeUpdate in componentUpdate.Value)
                    {
                        String updateQuery = "update attributes_to_components set value = :newValue where componentID = :componentGuid AND attributeName = :attributeName";
                        IQuery sqlQuery    = session.CreateSQLQuery(updateQuery)
                                             .SetBinary("newValue", ObjectToByteArray(attributeUpdate.Value))
                                             .SetParameter("componentGuid", componentGuid)
                                             .SetParameter("attributeName", attributeUpdate.Key);
                        sqlQuery.ExecuteUpdate();
                    }
                }
                try
                {
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    logger.WarnException("Failed to update Attribute", e);
                    transaction.Rollback();
                }
                finally
                {
                    session.Close();
                }
            }
        }
Exemplo n.º 13
0
        public static IList <object[]> StatelessGetBySql(string sql, IDictionary <string, Object> namedParameters)
        {
            CheckSqlInjection(sql);
            IStatelessSession session = GetStatelessSession();

            try{
                var q = session.CreateSQLQuery(sql);
                foreach (var namedParameter in namedParameters)
                {
                    q.SetParameter(namedParameter.Key, namedParameter.Value);
                }
                var l = q.List <object[]>();
                return(l);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                session.Close();
            }
        }
Exemplo n.º 14
0
        public static void StatelessExecuteSql(String sql, IDictionary <string, Object> namedParameters)
        {
            CheckSqlInjection(sql, true);
            IStatelessSession session = GetStatelessSession();

            try
            {
                var q = session.CreateSQLQuery(sql);
                foreach (var namedParameter in namedParameters)
                {
                    q.SetParameter(namedParameter.Key, namedParameter.Value);
                }
                q.ExecuteUpdate();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                session.Close();
            }
        }
 public void Close()
 {
     _Session.Close();
 }
Exemplo n.º 16
0
 /// <summary>
 /// Close the stateless session and release the ADO.NET connection.
 /// </summary>
 public void Close()
 {
     innerSession.Close();
 }
Exemplo n.º 17
0
        public int Synchronise(int installationID, CloudStatusDB cloudStatusDB, int mode)
        {
            // mode 0 = partial, 1 = full (i.e. mergeorReplace become replace)
            int               result              = 0;
            ISession          IMSSession          = null;
            IStatelessSession IMSStatelessSession = null;
            ISession          tufmanSession       = null;
            SyncDirection     syncDirection;
            SyncType          syncType;

            // retrieve a list of the synchronisation items
            List <TUFStatus.Domain.Cloud.App.Sync> syncList;

            try
            {
                var repository = new TUFStatus.DAL.Repositories.Repository <ISession, Domain.Cloud.App.Sync>(cloudStatusDB.session);
                //var xa = cloudStatusDB.session.BeginTransaction();
                syncList = repository.FilterBy(x => x.installation.installation_id == installationID && x.application.application_id == (int)TUFStatus.TUFMANInstallation.ApplicationList.TUFStatus).OrderBy(x => x.sync_order).ToList();

                //xa.Dispose();
                //xa.Rollback();
                // Cloud IMS session
                IMSSession          = TUFStatus.DAL.Configuration.IMSNHibernateHelper.CreateSessionFactory().OpenSession();
                IMSStatelessSession = TUFStatus.DAL.Configuration.IMSNHibernateHelper.CreateSessionFactory().OpenStatelessSession();


                foreach (TUFStatus.Domain.Cloud.App.Sync syncItem in syncList)
                {
                    string tablename;
                    int    tableResult = 0;
                    string countryCode;

                    //Type open = typeof(TableSynchroniser<>);
                    ////Type closed = open.MakeGenericType(typeof(TUFMAN.Domain.Ves.VesselCategories));

                    //Type closed = open.MakeGenericType(Type.GetType(GetTableClass(tablename)));
                    //// Type closed2 = open.MakeGenericType(x.GetType());
                    //dynamic ts = Activator.CreateInstance(closed);

                    //TUFMAN.Domain.Ves.VesselActAnnual v;


                    // create the TUFMAN session

                    //UnitOfWork unitOfWorkTUFMAN = new UnitOfWork(TufmanNHibernateHelper.CreateSessionFactory("Server=NOUSQL50\\SQLEXPRESS;Database=tufman_ws;Trusted_Connection=True"));
                    tufmanSession = TufmanNHibernateHelper.CreateSessionFactory().OpenSession();

                    tablename = syncItem.schemaname + "." + syncItem.tablename;

                    countryCode = Program.tufmanInstallation.CountryCode();

                    // Check the direction of syncronisation to do
                    switch (syncItem.direction_code)
                    {
                    case "up":     // merge or replace
                        syncDirection = SyncDirection.Up;
                        break;

                    case "dn":     // replace
                        syncDirection = SyncDirection.Down;
                        break;

                    default:     // anything else, only "up" is supported at present though
                        syncDirection = SyncDirection.Up;
                        break;
                    }

                    // Check the type of syncronisation to do
                    switch (syncItem.sync_type_code)
                    {
                    case "mr":     // merge or replace
                        syncType = SyncType.Merge;
                        break;

                    case "rp":     // replace
                        syncType = SyncType.Replace;
                        break;

                    case "dl":     // delete
                        syncType = SyncType.Delete;
                        break;

                    default:     // 'mg' - merge only
                        syncType = SyncType.MergeOrReplace;
                        break;
                    }

                    // set sync mode to replace if mode is 'full' and sync type is merge or replace
                    if (mode == 1)
                    {
                        if (syncType == SyncType.MergeOrReplace)
                        {
                            syncType = SyncType.Replace;
                        }
                    }

                    // checked the last sync date, if null then sync becomes 'replace'
                    if (syncItem.sync_date == null & syncType != SyncType.Delete)
                    {
                        syncType = SyncType.Replace;
                    }



                    // ********************* need to add filtering to this **************************** //
                    if (syncType == SyncType.Delete)
                    {
                        switch (tablename.ToLower())
                        {
                        case "lic.agr_rep_period":
                            TableSynchroniser <TUFMAN.Domain.Lic.AgrRepPeriod> ts11 = new TableSynchroniser <TUFMAN.Domain.Lic.AgrRepPeriod>();
                            tableResult = ts11.SynchroniseTableDeletes(tufmanSession, IMSSession, x => (x.changed_date >= syncItem.sync_date), syncItem.sync_date, syncItem.table_id);
                            break;

                        default:
                            // report an error here, table is not recognised and won't be synchronised
                            break;
                        }
                    }
                    else
                    {
                        switch (tablename.ToLower())
                        {
                        case "ves.vessel_categories":
                            TableSynchroniser <TUFMAN.Domain.Ves.VesselCategories> ts0 = new TableSynchroniser <TUFMAN.Domain.Ves.VesselCategories>();
                            tableResult = ts0.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "ves.vessels":
                            TableSynchroniser <TUFMAN.Domain.Ves.Vessels> ts1 = new TableSynchroniser <TUFMAN.Domain.Ves.Vessels>();
                            //ts1.SynchroniseTable(tufmanSession, IMSSession);
                            //tableResult = ts1.SynchroniseTableInserts(tufmanSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType);

                            tableResult = ts1.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "ref.agreement_ownership":
                            TableSynchroniser <TUFMAN.Domain.Ref.AgreementOwnership> ts2 = new TableSynchroniser <TUFMAN.Domain.Ref.AgreementOwnership>();
                            tableResult = ts2.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "ref.agreement_types":
                            TableSynchroniser <TUFMAN.Domain.Ref.AgreementTypes> ts3 = new TableSynchroniser <TUFMAN.Domain.Ref.AgreementTypes>();
                            tableResult = ts3.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "ref.license_status":
                            TableSynchroniser <TUFMAN.Domain.Ref.LicenseStatus> ts4 = new TableSynchroniser <TUFMAN.Domain.Ref.LicenseStatus>();
                            tableResult = ts4.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "ref.license_types":
                            TableSynchroniser <TUFMAN.Domain.Ref.LicenseTypes> ts5 = new TableSynchroniser <TUFMAN.Domain.Ref.LicenseTypes>();
                            tableResult = ts5.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "ref.iaf_zones":
                            TableSynchroniser <TUFMAN.Domain.Ref.IafZones> ts6 = new TableSynchroniser <TUFMAN.Domain.Ref.IafZones>();
                            tableResult = ts6.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "tufman.license_profiles":
                            TableSynchroniser <TUFMAN.Domain.Tufman.LicenseProfiles> ts7 = new TableSynchroniser <TUFMAN.Domain.Tufman.LicenseProfiles>();
                            tableResult = ts7.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "tufman.payment_types":
                            TableSynchroniser <TUFMAN.Domain.Tufman.PaymentTypes> ts8 = new TableSynchroniser <TUFMAN.Domain.Tufman.PaymentTypes>();
                            tableResult = ts8.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "tufman.companies":
                            TableSynchroniser <TUFMAN.Domain.Tufman.Companies> ts9 = new TableSynchroniser <TUFMAN.Domain.Tufman.Companies>();
                            tableResult = ts9.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "lic.agreements":
                            TableSynchroniser <TUFMAN.Domain.Lic.Agreements> ts10 = new TableSynchroniser <TUFMAN.Domain.Lic.Agreements>();
                            tableResult = ts10.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "lic.agr_rep_period":
                            TableSynchroniser <TUFMAN.Domain.Lic.AgrRepPeriod> ts11 = new TableSynchroniser <TUFMAN.Domain.Lic.AgrRepPeriod>();
                            tableResult = ts11.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "lic.agr_lic_profile":
                            TableSynchroniser <TUFMAN.Domain.Lic.AgrLicProfile> ts12 = new TableSynchroniser <TUFMAN.Domain.Lic.AgrLicProfile>();
                            tableResult = ts12.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "lic.license_history":
                            TableSynchroniser <TUFMAN.Domain.Lic.LicenseHistory> ts13 = new TableSynchroniser <TUFMAN.Domain.Lic.LicenseHistory>();
                            tableResult = ts13.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "lic.licenses":
                            TableSynchroniser <TUFMAN.Domain.Lic.Licenses> ts14 = new TableSynchroniser <TUFMAN.Domain.Lic.Licenses>();
                            tableResult = ts14.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "lic.nat_fleet_iaf":
                            TableSynchroniser <TUFMAN.Domain.Lic.NatFleetIaf> ts15 = new TableSynchroniser <TUFMAN.Domain.Lic.NatFleetIaf>();
                            tableResult = ts15.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "lic.nat_fleet_lic":
                            TableSynchroniser <TUFMAN.Domain.Lic.NatFleetLic> ts16 = new TableSynchroniser <TUFMAN.Domain.Lic.NatFleetLic>();
                            tableResult = ts16.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "lic.nat_fleet_reg":
                            TableSynchroniser <TUFMAN.Domain.Lic.NatFleetReg> ts17 = new TableSynchroniser <TUFMAN.Domain.Lic.NatFleetReg>();
                            tableResult = ts17.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "lic.national_fleets":
                            TableSynchroniser <TUFMAN.Domain.Lic.NationalFleets> ts18 = new TableSynchroniser <TUFMAN.Domain.Lic.NationalFleets>();
                            tableResult = ts18.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        case "recon.view_log_yy_mm_eez_all_id":
                            TableSynchroniser <TUFMAN.Domain.Recon.ViewLogYyMmEezAllID> ts19 = new TableSynchroniser <TUFMAN.Domain.Recon.ViewLogYyMmEezAllID>();
                            tableResult = ts19.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.YY >= (DateTime.Now.Year - 4) & x.eez_code == countryCode), syncDirection, syncType, true);
                            break;

                        case "recon.view_unloads_yy_mm_all_id":
                            TableSynchroniser <TUFMAN.Domain.Recon.ViewUnloadsYyMmAllID> ts20 = new TableSynchroniser <TUFMAN.Domain.Recon.ViewUnloadsYyMmAllID>();
                            tableResult = ts20.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.YY >= (DateTime.Now.Year - 4)), syncDirection, syncType, true);
                            break;

                        case "recon.view_samples_yy_mm_all_id":
                            TableSynchroniser <TUFMAN.Domain.Recon.ViewSamplesYyMmAllID> ts21 = new TableSynchroniser <TUFMAN.Domain.Recon.ViewSamplesYyMmAllID>();
                            tableResult = ts21.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.YY >= (DateTime.Now.Year - 4)), syncDirection, syncType, true);
                            break;

                        case "unload.unloadings_ps":
                            TableSynchroniser <TUFMAN.Domain.Unload.UnloadingsPs> ts22 = new TableSynchroniser <TUFMAN.Domain.Unload.UnloadingsPs>();
                            tableResult = ts22.SynchroniseTable(tufmanSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                            break;

                        default:
                            // report an error here, table is not recognised and won't be synchronised
                            break;
                        }
                    }
                    var xa = cloudStatusDB.session.BeginTransaction();
                    syncItem.last_run_date   = DateTime.Now;
                    syncItem.last_run_result = tableResult;
                    if (tableResult >= 0)
                    {
                        result            += tableResult;
                        syncItem.sync_date = DateTime.Now;
                    }
                    xa.Commit();
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.Instance.HandleError(ActionLog.ActionTypes.Application, "", "There was an error running the synchroniser:", ex.Message);
                return(-1);
            }
            finally
            {
                if (IMSSession != null && IMSSession.IsOpen)
                {
                    IMSSession.Close();
                }

                if (IMSStatelessSession != null && IMSStatelessSession.IsOpen)
                {
                    IMSStatelessSession.Close();
                }

                //IMSNHibernateHelper.SessionFactory.Close();

                if (tufmanSession != null && tufmanSession.IsOpen)
                {
                    tufmanSession.Close();
                }
            }

            return(result);
        }
Exemplo n.º 18
0
        private void WriteAudit(object entity, object[] oldState, IEntityPersister persister, object[] state, IEventSource eventSource, object id)
        {
            IStatelessSession session     = null;
            ITransaction      transaction = null;

            try
            {
                if (entity is AuditLogEntry)
                {
                    return;
                }
                var entityFullName = entity.GetType().FullName;
                if (oldState == null)
                {
                    //Hack to overcome bad saving practice!
                    oldState = Enumerable.Repeat(UnknownString as object, state.Length).ToArray();
                    //throw new ArgumentNullException("No old state available for entity type '" + entityFullName + "'. Make sure you're loading it into Session before modifying and saving it.");
                }


                bool insert = oldState.Length < 1;
                //ISessionImplementor implementor = eventSource.GetSession(EntityMode.Poco).SessionFactory.OpenStatelessSession().GetSessionImplementation();
                int[]  dirtyFieldIndexes = insert ? Enumerable.Range(0, state.Length).ToArray() : persister.FindDirty(state, oldState, entity, eventSource);
                var    auditEntryType    = insert ? "Insert" : "Update";
                string username          = Environment.UserName;

                var haveModifiedBy = entity as IHaveModifiedBy;
                if (haveModifiedBy != null)
                {
                    username = haveModifiedBy.LastModifiedBy;
                }

                session = eventSource.GetSession(EntityMode.Poco).SessionFactory.OpenStatelessSession();
                session.BeginTransaction();
                foreach (var dirtyFieldIndex in dirtyFieldIndexes)
                {
                    string oldValue = NoValueString;
                    if (!insert)
                    {
                        oldValue = GetStringValueFromStateArray(oldState, dirtyFieldIndex);
                    }
                    var newValue     = GetStringValueFromStateArray(state, dirtyFieldIndex);
                    var propertyName = persister.PropertyNames[dirtyFieldIndex];
                    if (oldValue == newValue || propertyName == "LastModifiedBy" || propertyName == "LastModifiedDate")
                    {
                        continue;
                    }

                    session.Insert(new AuditLogEntry
                    {
                        EntityShortName = entity.GetType().Name,
                        FieldName       = propertyName,
                        OldValue        = oldValue,
                        NewValue        = newValue,
                        Username        = username,
                        EntityId        = (int)id,
                        AuditEntryType  = auditEntryType,
                        Timestamp       = DateTime.Now
                    });
                }
                session.Transaction.Commit();
                session.Close();
            }
            catch (Exception)
            {
                //Don't let audit log make us fail.
                //if (session != null)
                //{
                //    if (session.Transaction.IsActive) session.Transaction.Rollback();
                //    session.Close();
                //    session = null;
                //}
                //if (eventSource != null)
                //{
                //    //if (transaction != null && transaction.IsActive) eventSource.Transaction.Rollback();
                //    //if (eventSource.Transaction.IsActive) eventSource.Transaction.Rollback();
                //    //eventSource.Close();
                //}
            }
        }
Exemplo n.º 19
0
 public System.Data.IDbConnection Close()
 {
     statelessSession.Close();
     return(null);
 }
Exemplo n.º 20
0
 public IDbConnection Close()
 {
     RealSession.Close();
     return(null);
 }
Exemplo n.º 21
0
        public int SynchroniseWithSPC(CloudStatusDB cloudStatusDB)
        {
            // synchronises from the cloud portal db to tufsync_xx at SPC. The tables to be synchronised are stored in the app.sync folder of the tufsync_control db.
            int               result              = 0;
            ISession          IMSSession          = null;
            IStatelessSession IMSStatelessSession = null;
            ISession          spcSession          = null;
            IStatelessSession spcStatelessSession = null;
            SyncDirection     syncDirection;
            SyncType          syncType;

            // retrieve a list of the synchronisation items
            List <TUFStatus.Domain.Cloud.App.Sync> syncList;

            try
            {
                var repository = new TUFStatus.DAL.Repositories.Repository <ISession, Domain.Cloud.App.Sync>(cloudStatusDB.session);
                //var xa = cloudStatusDB.session.BeginTransaction();
                syncList = repository.FilterBy(x => x.application.application_id == (int)TUFStatus.TUFMANInstallation.ApplicationList.TUFStatusSPC).OrderBy(x => x.installation.installation_id).ThenBy(x => x.sync_order).ToList();

                //xa.Dispose();
                //xa.Rollback();

                foreach (TUFStatus.Domain.Cloud.App.Sync syncItem in syncList)
                {
                    string tablename;
                    int    tableResult = 0;
                    string countryCode;
                    string portalDatabase;
                    string portalServer;
                    string spcSyncDB;

                    // Tufman installation information comes from the 'installation' object of the sync item, i.e. the installation_id field of the sync table
                    portalDatabase = syncItem.installation.portal_database;
                    portalServer   = syncItem.installation.portal_server;
                    spcSyncDB      = "tufsync_" + syncItem.installation.country_code.ToLower();

                    // Cloud IMS session
                    IMSSession          = TUFStatus.DAL.Configuration.IMSNHibernateHelper.CreateSessionFactory(portalServer, portalDatabase).OpenSession();
                    IMSStatelessSession = TUFStatus.DAL.Configuration.IMSNHibernateHelper.CreateSessionFactory(portalServer, portalDatabase).OpenStatelessSession();

                    spcSession          = SPCNHibernateHelper.CreateSessionFactory(spcSyncDB).OpenSession();
                    spcStatelessSession = SPCNHibernateHelper.CreateSessionFactory(spcSyncDB).OpenStatelessSession();

                    tablename = syncItem.schemaname + "." + syncItem.tablename;

                    countryCode = Program.tufmanInstallation.CountryCode();

                    // Check the direction of syncronisation to do
                    switch (syncItem.direction_code)
                    {
                    case "up":     // merge or replace
                        syncDirection = SyncDirection.Up;
                        break;

                    case "dn":     // replace
                        syncDirection = SyncDirection.Down;
                        break;

                    default:     // anything else, only "up" is supported at present though
                        syncDirection = SyncDirection.Up;
                        break;
                    }

                    // Check the type of syncronisation to do
                    switch (syncItem.sync_type_code)
                    {
                    case "mr":     // merge or replace
                        syncType = SyncType.Merge;
                        break;

                    case "rp":     // replace
                        syncType = SyncType.Replace;
                        break;

                    case "dl":     // delete
                        syncType = SyncType.Delete;
                        break;

                    default:     // 'mg' - merge only
                        syncType = SyncType.MergeOrReplace;
                        break;
                    }

                    // set sync mode to replace if mode is 'full' and sync type is merge or replace
                    //if (mode == 1)
                    //{
                    //    if (syncType == SyncType.MergeOrReplace)
                    //        syncType = SyncType.Replace;
                    //}

                    // checked the last sync date, if null then sync becomes 'replace'
                    if (syncItem.sync_date == null & syncType != SyncType.Delete)
                    {
                        syncType = SyncType.Replace;
                    }



                    // ********************* need to add filtering to this **************************** //
                    if (syncType == SyncType.Delete)
                    {
                        if (syncDirection == SyncDirection.Down)
                        {
                            switch (tablename.ToLower())
                            {
                            case "lic.agr_rep_period":
                                TableSynchroniser <TUFMAN.Domain.Lic.AgrRepPeriod> ts11 = new TableSynchroniser <TUFMAN.Domain.Lic.AgrRepPeriod>();
                                tableResult = ts11.SynchroniseTableDeletes(IMSSession, spcSession, x => (x.changed_date >= syncItem.sync_date), syncItem.sync_date, syncItem.table_id);
                                break;

                            default:
                                // report an error here, table is not recognised and won't be synchronised
                                break;
                            }
                        }
                        else           // up is the default
                        {
                            switch (tablename.ToLower())
                            {
                            case "lic.agr_rep_period":
                                TableSynchroniser <TUFMAN.Domain.Lic.AgrRepPeriod> ts11 = new TableSynchroniser <TUFMAN.Domain.Lic.AgrRepPeriod>();
                                tableResult = ts11.SynchroniseTableDeletes(spcSession, IMSSession, x => (x.changed_date >= syncItem.sync_date), syncItem.sync_date, syncItem.table_id);
                                break;

                            default:
                                // report an error here, table is not recognised and won't be synchronised
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (syncDirection == SyncDirection.Down)
                        {
                            switch (tablename.ToLower())
                            {
                            case "ves.vessels":
                                TableSynchroniser <TUFMAN.Domain.Ves.Vessels> ts1 = new TableSynchroniser <TUFMAN.Domain.Ves.Vessels>();

                                tableResult = ts1.SynchroniseTable(IMSSession, spcSession, spcStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                                break;

                            default:
                                // report an error here, table is not recognised and won't be synchronised
                                break;
                            }
                        }
                        else           // up is the default
                        {
                            switch (tablename.ToLower())
                            {
                            case "ves.vessels":
                                TableSynchroniser <TUFMAN.Domain.Ves.Vessels> ts1 = new TableSynchroniser <TUFMAN.Domain.Ves.Vessels>();

                                tableResult = ts1.SynchroniseTable(spcSession, IMSSession, IMSStatelessSession, x => (x.changed_date >= syncItem.sync_date), syncDirection, syncType, false);
                                break;

                            default:
                                // report an error here, table is not recognised and won't be synchronised
                                break;
                            }
                        }
                    }
                    var xa = cloudStatusDB.session.BeginTransaction();
                    syncItem.last_run_date   = DateTime.Now;
                    syncItem.last_run_result = tableResult;
                    if (tableResult >= 0)
                    {
                        result            += tableResult;
                        syncItem.sync_date = DateTime.Now;
                    }
                    xa.Commit();
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.Instance.HandleError(ActionLog.ActionTypes.Application, "", "There was an error running the synchroniser:", ex.Message);
                return(-1);
            }
            finally
            {
                if (IMSSession != null && IMSSession.IsOpen)
                {
                    IMSSession.Close();
                }

                if (IMSStatelessSession != null && IMSStatelessSession.IsOpen)
                {
                    IMSStatelessSession.Close();
                }

                //IMSNHibernateHelper.SessionFactory.Close();

                if (spcSession != null && spcSession.IsOpen)
                {
                    spcSession.Close();
                }
            }

            return(result);
        }