Exemplo n.º 1
0
        /// <summary>
        /// Accepts the specified visitor.
        /// </summary>
        /// <param name="visitor">The visitor.</param>
        /// <param name="options">The options.</param>
        public void Accept(ITargetDeletionVisitor visitor, VisitorOptions options)
        {
            if (!string.IsNullOrEmpty(visitor.TargetType) && !visitor.TargetType.EqualsIgnoreCase(this.ContentType.Name))
            {
                return;
            }

            visitor.Visit(this, options);
        }
        /// <summary>
        /// Deletes the item.
        /// </summary>
        /// <param name="entry">The entry.</param>
        /// <param name="showDeletePrompt">if set to <c>true</c> [show delete prompt].</param>
        private void DeleteItem(Dataset entry, bool showDeletePrompt = true)
        {
            try
            {
                if (TargetLookup == null || !TargetLookup.Any())
                {
                    return;
                }

                if (TargetLookup[entry.ContentType.Name] == null)
                {
                    return;
                }

                if (!TargetLookup[entry.ContentType.Name].IsCustom && string.IsNullOrEmpty(TargetLookup[entry.ContentType.Name].ClrType))
                {
                    return;
                }

                if (showDeletePrompt)
                {
                    var attachedWebsites = Service.GetWebsitesForDataset(entry.Id);
                    if (attachedWebsites.Any())
                    {
                        string websiteNames   = string.Join(",", attachedWebsites);
                        var    warningMessage = string.Format("Unable to delete dataset \"{0}\" because it is associated with the following websites:", entry.Name);
                        warningMessage += string.Format("{0}{0}Associated Websites: {1}", Environment.NewLine, websiteNames);

                        MessageBox.Show(warningMessage, "Dataset Deletion Warning", MessageBoxButton.OK);
                        return;
                    }

                    //  Show blanket warning against dataset deletion.  But only show warning if this Dataset is Finished.
                    if (entry.IsFinished)
                    {
                        var warningMessage = string.Format("Dataset \"{0}\" will be deleted.  Are you sure you want to delete this data set?", entry.Name);
                        var result         = MessageBox.Show(warningMessage, "Dataset Deletion Warning", MessageBoxButton.YesNo);

                        if (result == MessageBoxResult.No ||
                            result == MessageBoxResult.Cancel ||
                            result == MessageBoxResult.None)
                        {
                            return;
                        }
                    }
                }

                if (DataTypesList == null)
                {
                    return;
                }

                foreach (var dataTypeModel in DataTypesList.Where(dataTypeModel => dataTypeModel.RecordsList.Any(ds => ds.Entry.Id == entry.Id)).ToList())
                {
                    dataTypeModel.RecordsList.ToList().RemoveAll(ds => ds.Entry.Id != entry.Id);
                }

                if (SelectedDataType != null)
                {
                    var item = SelectedDataType.RecordsList.FirstOrDefault(model => model.Entry.Id == entry.Id);
                    if (item != null)
                    {
                        SelectedDataType.RecordsList.Remove(item);
                    }
                }

                using (var session = SessionProvider.SessionFactory.OpenSession())
                {
                    using (var trans = session.BeginTransaction())
                    {
                        session.Evict(entry);

                        var target = TargetLookup[entry.ContentType.Name];

                        #region Delete queries
                        string targetDeleteQuery;

                        var tableName = target.IsCustom ? entry.ContentType.DbSchemaName : entry.ContentType.ClrType != null?Type.GetType(entry.ContentType.ClrType).EntityTableName() : string.Empty;

                        if (string.IsNullOrEmpty(tableName))
                        {
                            return;
                        }

                        //Disable Dataset Constraint
                        //var disableConstraint = string.Format("ALTER TABLE  {0} NOCHECK CONSTRAINT FK_TARGETS_{1}_DATASETS", tableName, tableName.Replace("Targets_", ""));
                        var disableConstraint = string.Format("ALTER TABLE  {0} NOCHECK CONSTRAINT ALL;", tableName /*, tableName.Replace("Targets_", "")*/);
                        session.CreateSQLQuery(disableConstraint)
                        .SetTimeout(25000)
                        .ExecuteUpdate();


                        // Delete Transactional record
                        var transactionDelete = string.Format("delete from DatasetTransactionRecord ct where ct.Dataset.Id = {0}", entry.Id);
                        session.CreateQuery(transactionDelete)
                        .SetTimeout(25000)
                        .ExecuteUpdate();

                        //Delete websites with no website_id but have reference to this dataset being deleted
                        var orphanWesbite = string.Format("delete from Websites_WebsiteDatasets where Website_Id IS NULL and Dataset_Id = {0}", entry.Id);
                        session.CreateSQLQuery(orphanWesbite)
                        .SetTimeout(25000)
                        .ExecuteUpdate();

                        // finally delete content item record.
                        var importDelete = string.Format("delete from Dataset c where c.Id = {0}", entry.Id);
                        session.CreateQuery(importDelete)
                        .SetTimeout(25000)
                        .ExecuteUpdate();

                        #endregion

                        if (TargetDeletionVisitors != null)
                        {
                            TargetDeletionVisitors = TargetDeletionVisitors.OrderBy(v => v.Order).ToList();

                            var options = new VisitorOptions()
                            {
                                DataProvider = this.SessionProvider,
                                Logger       = this.Logger
                            };
                            var factory = new TaskFactory(new MonahrqTaskScheduler(2));
                            var token   = new CancellationTokenSource();

                            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
                                                                     new Action(() => ListExtensions.ForEach(TargetDeletionVisitors, visitor => factory.StartNew(() => entry.Accept(visitor, options), token.Token))));
                        }

                        trans.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                Events.GetEvent <ErrorNotificationEvent>().Publish(ex);
            }
        }
        //[Import]
        //public IDomainSessionFactoryProvider DataProvider { get; set; }

        //[Import(LogNames.Session)]
        //ILogWriter Logger { get; set; }

        public void Visit(Monahrq.Infrastructure.Entities.Domain.IEntity entity, VisitorOptions options /*NHibernate.ISession session*/)
        {
            if (options == null || options.DataProvider == null || entity == null)
            {
                return;
            }
            var dataset = entity as Dataset;

            if (dataset == null)
            {
                return;
            }
            if (dataset.ContentType == null || !dataset.ContentType.Name.EqualsIgnoreCase(TargetType))
            {
                return;
            }


            var statesList          = dataset.ProviderStates.Split(',').ToList();
            var itemCounter         = 0;
            var selectStatesSummary = string.Empty;

            using (var sess = options.DataProvider.SessionFactory.OpenSession())
            {
                using (var trans = sess.BeginTransaction())
                {
                    try
                    {
                        foreach (var state in statesList.ToList())
                        {
                            var query = string.Format("if exists (select distinct wd.[Id] from [Wings_Datasets] wd inner join [Wings_Targets] wt on wt.[Id] = wd.[ContentType_Id] Where wd.[Id]!={0} and UPPER(wt.Name) = UPPER('{1}') ", dataset.Id, dataset.ContentType.Name);
                            query += " and ( ";

                            //if (itemCounter > 0)
                            //    query += " or ";

                            query += Environment.NewLine + string.Format(" charindex('{0}',wd.[ProviderStates],0) > 0", state);


                            query += " ))";
                            query += Environment.NewLine + @"begin
	select 1 as result;
end
Else
begin
	select 0 as result;
end";
                            itemCounter++;

                            if (sess.CreateSQLQuery(query).AddScalar("result", NHibernateUtil.Int32).List <int>().Single() == 1)
                            {
                                continue;
                            }

                            //foreach (var state in statesList.ToList())
                            //{
                            //selectStatesSummary += string.Format("'{0}',", state);
                            selectStatesSummary += string.Format("'{0}'", state);
                            //}
                            //if (selectStatesSummary.EndsWith(","))
                            //    selectStatesSummary = selectStatesSummary.SubStrBeforeLast(",");

//                            sess.CreateSQLQuery(string.Format(@"-- Medical Practice Addresses
//                                                DELETE FROM [dbo].[Addresses]
//                                                    WHERE [AddressType] = 'MEDICALPRACTICE'
//                                                    AND [MedicalPractice_Id] in (SELECT DISTINCT mp.[Id] FROM [dbo].[MedicalPractices] mp WHERE mp.[State] in ({0}) AND mp.[IsEdited] = 0);
//                                                    --AND [State] in ({0});
//                                                -- Physician Addresses
//                                                DELETE FROM [dbo].[Addresses]
//                                                    WHERE [AddressType] = 'PHYSICIAN'
//                                                    AND [Physician_Id] in (SELECT DISTINCT p.[Id] FROM [dbo].[Physicians] p WHERE p.[States] in ({0}) AND p.[IsEdited] = 0);
//                                                    --AND [State] in ({0});
//                                                -- Physician Affiliated Hospitals
//                                                DELETE FROM [dbo].[Physicians_AffiliatedHospitals]
//                                                    WHERE [Physician_Id] in (SELECT DISTINCT p.[Id] FROM [dbo].[Physicians] p WHERE p.[States] in ({0}) AND p.[IsEdited] = 0);
//                                                -- Physician Medical Practices
//                                                DELETE FROM [dbo].[Physicians_MedicalPractices]
//                                                    WHERE [Physician_Id] in (SELECT DISTINCT p.[Id] FROM [dbo].[Physicians] p WHERE p.[States] in ({0}) AND p.[IsEdited] = 0)
//                                                    OR [MedicalPractice_Id] in (SELECT DISTINCT mp.[Id] FROM [dbo].[MedicalPractices] mp WHERE mp.[State] in ({0}) AND mp.[IsEdited] = 0);
//                                                DELETE FROM [dbo].[Physicians_MedicalPractices]
//                                                    WHERE [Physician_Id] is null OR [MedicalPractice_Id] is null;
//                                                -- Medical Practices
//                                                DELETE FROM [dbo].[MedicalPractices]
//                                                    WHERE [State] in ({0}) AND [IsEdited] = 0;
//                                                -- Physicians
//                                                DELETE FROM [dbo].[Physicians]
//                                                    WHERE [States] in ({0}) AND [IsEdited] = 0;", selectStatesSummary))
//                                 .SetTimeout(10000)
//                                 .ExecuteUpdate();

                            sess.CreateSQLQuery(string.Format(@"-- Medical Practice Addresses
                                                DELETE FROM [dbo].[Addresses]
                                                    WHERE UPPER([AddressType]) = 'MEDICALPRACTICE' 
                                                    AND [MedicalPractice_Id] in (SELECT DISTINCT mp.[Id] FROM [dbo].[MedicalPractices] mp WHERE mp.[State] in ('{0}') AND mp.[IsEdited] = 0);
                                                    --AND [State] in ({0});

                                                -- Physician Addresses
                                                DELETE FROM [dbo].[Addresses]
                                                    WHERE UPPER([AddressType]) = 'PHYSICIAN' 
                                                    AND [Physician_Id] in (SELECT DISTINCT p.[Id] FROM [dbo].[Physicians] p WHERE p.[States] like '%{0}%' AND p.[IsEdited] = 0);
                                                    --AND [State] in ({0});

                                                -- Physician Affiliated Hospitals
                                                DELETE FROM [dbo].[Physicians_AffiliatedHospitals]
                                                    WHERE [Physician_Id] in (SELECT DISTINCT p.[Id] FROM [dbo].[Physicians] p WHERE p.[States] like '%{0}%' AND p.[IsEdited] = 0);

                                                -- Physician Medical Practices
                                                DELETE FROM [dbo].[Physicians_MedicalPractices]
                                                    WHERE [Physician_Id] in (SELECT DISTINCT p.[Id] FROM [dbo].[Physicians] p WHERE p.[States] like '%{0}%' AND p.[IsEdited] = 0)
                                                    OR [MedicalPractice_Id] in (SELECT DISTINCT mp.[Id] FROM [dbo].[MedicalPractices] mp WHERE mp.[State] in ('{0}') AND mp.[IsEdited] = 0);
                                                    
                                                DELETE FROM [dbo].[Physicians_MedicalPractices]
                                                    WHERE [Physician_Id] is null
                                                     OR [MedicalPractice_Id] is null;
                                                
                                                -- Medical Practices
                                                DELETE FROM [dbo].[MedicalPractices] 
                                                    WHERE [State] = '{0}' AND [IsEdited] = 0;

                                                -- Physicians
                                                DELETE FROM [dbo].[Physicians] 
                                                    WHERE [States] like '%{0}%' AND [IsEdited] = 0;", state))
                            .SetTimeout(30000)
                            .ExecuteUpdate();
                        }

                        trans.Commit();
                    }
                    catch (Exception exc)
                    {
                        trans.Rollback();
                        options.Logger.Write(exc);
                    }
                }
            }
        }