public static IndexSearcher BuildSearcher(ISearchFactoryImplementor searchFactory,
                                                  out ISet <System.Type> classesAndSubclasses,
                                                  params System.Type[] classes)
        {
            IDictionary <System.Type, DocumentBuilder> builders = searchFactory.DocumentBuilders;
            ISet <IDirectoryProvider> directories = new HashedSet <IDirectoryProvider>();

            if (classes == null || classes.Length == 0)
            {
                // no class means all classes
                foreach (DocumentBuilder builder in builders.Values)
                {
                    foreach (IDirectoryProvider provider in builder.DirectoryProvidersSelectionStrategy.GetDirectoryProvidersForAllShards())
                    {
                        directories.Add(provider);
                    }
                }

                // Give them back an empty set
                classesAndSubclasses = null;
            }
            else
            {
                ISet <System.Type> involvedClasses = new HashedSet <System.Type>();
                involvedClasses.AddAll(classes);
                foreach (System.Type clazz in classes)
                {
                    DocumentBuilder builder;
                    builders.TryGetValue(clazz, out builder);
                    if (builder != null)
                    {
                        involvedClasses.AddAll(builder.MappedSubclasses);
                    }
                }

                foreach (System.Type clazz in involvedClasses)
                {
                    DocumentBuilder builder;
                    builders.TryGetValue(clazz, out builder);

                    // TODO should we rather choose a polymorphic path and allow non mapped entities
                    if (builder == null)
                    {
                        throw new HibernateException("Not a mapped entity: " + clazz);
                    }

                    foreach (IDirectoryProvider provider in builder.DirectoryProvidersSelectionStrategy.GetDirectoryProvidersForAllShards())
                    {
                        directories.Add(provider);
                    }
                }

                classesAndSubclasses = involvedClasses;
            }

            IDirectoryProvider[] directoryProviders = new List <IDirectoryProvider>(directories).ToArray();
            return(new IndexSearcher(searchFactory.ReaderProvider.OpenReader(directoryProviders)));
        }
Example #2
0
        public static IndexSearcher BuildSearcher(ISearchFactoryImplementor searchFactory,
                                             out ISet<System.Type> classesAndSubclasses,
                                             params System.Type[] classes)
        {
            IDictionary<System.Type, DocumentBuilder> builders = searchFactory.DocumentBuilders;
            ISet<IDirectoryProvider> directories = new HashedSet<IDirectoryProvider>();
            if (classes == null || classes.Length == 0)
            {
                // no class means all classes
                foreach (DocumentBuilder builder in builders.Values)
                {
                    foreach (IDirectoryProvider provider in builder.DirectoryProvidersSelectionStrategy.GetDirectoryProvidersForAllShards())
                    {
                        directories.Add(provider);
                    }
                }

                // Give them back an empty set
                classesAndSubclasses = null;
            }
            else
            {
                ISet<System.Type> involvedClasses = new HashedSet<System.Type>();
                involvedClasses.AddAll(classes);
                foreach (System.Type clazz in classes)
                {
                    DocumentBuilder builder;
                    builders.TryGetValue(clazz, out builder);
                    if (builder != null)
                    {
                        involvedClasses.AddAll(builder.MappedSubclasses);
                    }
                }

                foreach (System.Type clazz in involvedClasses)
                {
                    DocumentBuilder builder;
                    builders.TryGetValue(clazz, out builder);

                    // TODO should we rather choose a polymorphic path and allow non mapped entities
                    if (builder == null)
                    {
                        throw new HibernateException("Not a mapped entity: " + clazz);
                    }

                    foreach (IDirectoryProvider provider in builder.DirectoryProvidersSelectionStrategy.GetDirectoryProvidersForAllShards())
                    {
                        directories.Add(provider);
                    }
                }

                classesAndSubclasses = involvedClasses;
            }

            IDirectoryProvider[] directoryProviders = new List<IDirectoryProvider>(directories).ToArray();
            return new IndexSearcher(searchFactory.ReaderProvider.OpenReader(directoryProviders));
        }
Example #3
0
        public virtual ISet <Effect> GetAllEffects()
        {
            HashedSet <Effect> effs = new HashedSet <Effect>(Effects);

            foreach (Combination combination in GetAllChildrenCombination())
            {
                effs.AddAll(combination.Effects);
            }
            foreach (EquivalenceClass equivalenceClass in GetAllEquivalenceClasses())
            {
                effs.AddAll(equivalenceClass.Effects);
            }
            return(effs);
        }
        public ISet <string> GetQuerySpaces()
        {
            ISet <string> result = new HashedSet <string>();

            foreach (ICriteriaInfoProvider info in criteriaInfoMap.Values)
            {
                result.AddAll(info.Spaces);
            }

            foreach (ICollectionPersister collectionPersister in criteriaCollectionPersisters)
            {
                result.AddAll(collectionPersister.CollectionSpaces);
            }
            return(result);
        }
Example #5
0
        private void CreateCriteriaLoaders()
        {
            //a criteria can use more than a single query (polymorphic queries), need to have a
            //way to correlate a loader to a result index
            int criteriaIndex = 0;

            foreach (CriteriaImpl criteria in criteriaQueries)
            {
                string[] implementors = factory.GetImplementors(criteria.EntityOrClassName);
                int      size         = implementors.Length;

                CriteriaLoader[] tmpLoaders = new CriteriaLoader[size];
                ISet <string>    spaces     = new HashedSet <string>();

                for (int i = 0; i < size; i++)
                {
                    CriteriaLoader loader = new CriteriaLoader(
                        session.GetOuterJoinLoadable(implementors[i]),
                        factory,
                        criteria,
                        implementors[i],
                        session.EnabledFilters
                        );
                    tmpLoaders[i] = loader;
                    loaderToResultIndex[loader] = criteriaIndex;
                    spaces.AddAll(tmpLoaders[i].QuerySpaces);
                }
                loaders.AddRange(tmpLoaders);
                criteriaIndex += 1;
            }
        }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="includeLeadingComma"></param>
        /// <returns></returns>
        public SqlString ToSqlStringFragment(bool includeLeadingComma)
        {
            StringBuilder buf           = new StringBuilder(columns.Count * 10);
            HashedSet     columnsUnique = new HashedSet();

            if (usedAliases != null)
            {
                columnsUnique.AddAll(usedAliases);
            }

            bool found = false;

            for (int i = 0; i < columns.Count; i++)
            {
                string col         = columns[i] as string;
                string columnAlias = columnAliases[i] as string;

                if (columnsUnique.Add(columnAlias))
                {
                    if (found || includeLeadingComma)
                    {
                        buf.Append(StringHelper.CommaSpace);
                    }

                    buf.Append(col)
                    .Append(" as ")
                    .Append(new Alias(suffix).ToAliasString(columnAlias, dialect));

                    // Set the flag for the next time
                    found = true;
                }
            }
            return(new SqlString(buf.ToString()));
        }
		public NativeSQLQuerySpecification(
			string queryString,
			ISQLQueryReturn[] sqlQueryReturns,
			ICollection querySpaces)
		{
			this.queryString = queryString;
			this.sqlQueryReturns = sqlQueryReturns;

			if (querySpaces == null)
			{
				this.querySpaces = new HashedSet();
			}
			else
			{
				ISet tmp = new HashedSet();
				tmp.AddAll(querySpaces);
				// Can't use ImmutableSet here because it doesn't implement GetHashCode properly.
				this.querySpaces = tmp;
			}

			// pre-determine and cache the hashcode
			int hashCode = queryString.GetHashCode();
			unchecked
			{
				hashCode = 29 * hashCode + this.querySpaces.GetHashCode();
				if (this.sqlQueryReturns != null)
				{
					hashCode = 29 * hashCode + sqlQueryReturns.Length;
				}
			}

			this.hashCode = hashCode;
		}
Example #8
0
        public NativeSQLQuerySpecification(
            string queryString,
            INativeSQLQueryReturn[] sqlQueryReturns,
            ICollection <string> querySpaces)
        {
            this.queryString     = queryString;
            this.sqlQueryReturns = sqlQueryReturns;

            if (querySpaces == null)
            {
                this.querySpaces = new HashedSet <string>();
            }
            else
            {
                ISet <string> tmp = new HashedSet <string>();
                tmp.AddAll(querySpaces);
                // Can't use ImmutableSet here because it doesn't implement GetHashCode properly.
                this.querySpaces = tmp;
            }

            // pre-determine and cache the hashcode
            int hCode = queryString.GetHashCode();

            unchecked
            {
                hCode = 29 * hCode + CollectionHelper.GetHashCode(this.querySpaces);
                if (this.sqlQueryReturns != null)
                {
                    hCode = 29 * hCode + CollectionHelper.GetHashCode(this.sqlQueryReturns);
                }
            }

            hashCode = hCode;
        }
        public GetPriorsResponse GetPriors(GetPriorsRequest request)
        {
            Platform.CheckForNullReference(request, "request");
            if (request.OrderRef == null && request.ReportRef == null)
            {
                throw new ArgumentException("Either OrderRef or ReportRef must be non-null");
            }

            var priorReports = new HashedSet <Prior>();
            var broker       = this.PersistenceContext.GetBroker <IPriorReportBroker>();

            // if an order was supplied, find relevant priors for the order
            if (request.OrderRef != null)
            {
                var order = this.PersistenceContext.Load <Order>(request.OrderRef, EntityLoadFlags.Proxy);
                priorReports.AddAll(broker.GetPriors(order, request.RelevantOnly));
            }
            // if a report was supplied, find relevent priors for the report
            else if (request.ReportRef != null)
            {
                var report = this.PersistenceContext.Load <Report>(request.ReportRef, EntityLoadFlags.Proxy);
                priorReports.AddAll(broker.GetPriors(report, request.RelevantOnly));
            }

            // assemble results
            var procedureTypeAssembler     = new ProcedureTypeAssembler();
            var diagnosticServiceAssembler = new DiagnosticServiceAssembler();

            // Note: we use the ProcedureCheckin.CheckOutTime as the PerformedDate
            // because it is the closest to the end of modality procedure step completion time.
            // However, if we change the definition of CheckOutTime in the future, this won't be accurate
            var priorSummaries = CollectionUtils.Map(priorReports,
                                                     (Prior prior) => new PriorProcedureSummary(
                                                         prior.Order.GetRef(),
                                                         prior.Procedure.GetRef(),
                                                         prior.Report.GetRef(),
                                                         prior.Order.AccessionNumber,
                                                         diagnosticServiceAssembler.CreateSummary(prior.Order.DiagnosticService),
                                                         procedureTypeAssembler.CreateSummary(prior.ProcedureType),
                                                         prior.Procedure.Portable,
                                                         EnumUtils.GetEnumValueInfo(prior.Procedure.Laterality, PersistenceContext),
                                                         EnumUtils.GetEnumValueInfo(prior.Report.Status, PersistenceContext),
                                                         prior.Procedure.ProcedureCheckIn.CheckOutTime));

            return(new GetPriorsResponse(priorSummaries));
        }
Example #10
0
        public static AssociationHelperResult BuildAssociationsToPrefetch(IAssociationPrefetcherRequest request, ApplicationSchemaDefinition schema)
        {
            var schemaAssociations = schema.GetProperty(ApplicationSchemaPropertiesCatalog.PreFetchAssociations);
            var requestToFetch     = request.AssociationsToFetch;
            var result             = new AssociationHelperResult();
            var toFetch            = new HashedSet <string>();
            var toAvoid            = new HashedSet <string>();

            result.ToFetch = toFetch;
            result.ToAvoid = toAvoid;

            if (schemaAssociations == null && requestToFetch == null)
            {
                toFetch.AddReturn(None);
                return(result);
            }
            if (All.Equals(schemaAssociations))
            {
                toFetch.Add(None.Equals(requestToFetch) ? None : All);
                return(result);
            }
            if (All.Equals(requestToFetch))
            {
                toFetch.AddReturn(All);
                return(result);
            }

            if (schemaAssociations != null)
            {
                toFetch.AddAll(schemaAssociations.Split(','));
                if (AllButSchema.Equals(requestToFetch))
                {
                    toAvoid.AddAll(schemaAssociations.Split(','));
                }
            }

            if (requestToFetch != null)
            {
                toFetch.AddAll(requestToFetch.Split(','));
            }

            return(result);
        }
Example #11
0
        public virtual ISet <EquivalenceClass> GetChildrenCombinationEquivalenceClasses()
        {
            HashedSet <EquivalenceClass> eqs = new HashedSet <EquivalenceClass>();

            foreach (Combination combination in Combinations)
            {
                eqs.AddAll(combination.GetAllEquivalenceClasses());
            }
            return(eqs);
        }
Example #12
0
        public virtual ISet <Combination> GetAllChildrenCombination()
        {
            HashedSet <Combination> combis = new HashedSet <Combination>(Combinations);

            foreach (Combination combination in Combinations)
            {
                combis.AddAll(combination.GetAllChildrenCombination());
            }
            return(combis);
        }
Example #13
0
        public static Iesi.Collections.Generic.ISet <T> ToSet <T>(this IEnumerable <T> list)
        {
            var set = new HashedSet <T>();

            if (list != null)
            {
                set.AddAll(list.ToList());
            }
            return(set);
        }
        public BulkOperationCleanupAction(ISessionImplementor session, IQueryable[] affectedQueryables)
        {
            this.session = session;
            List <string> tmpSpaces = new List <string>();

            for (int i = 0; i < affectedQueryables.Length; i++)
            {
                if (affectedQueryables[i].HasCache)
                {
                    affectedEntityNames.Add(affectedQueryables[i].EntityName);
                }
                ISet <string> roles = session.Factory.GetCollectionRolesByEntityParticipant(affectedQueryables[i].EntityName);
                if (roles != null)
                {
                    affectedCollectionRoles.AddAll(roles);
                }
                for (int y = 0; y < affectedQueryables[i].QuerySpaces.Length; y++)
                {
                    tmpSpaces.Add(affectedQueryables[i].QuerySpaces[y]);
                }
            }
            spaces = new List <string>(tmpSpaces);
        }
Example #15
0
        public IList <PersistentCollectionChangeData> MapCollectionChanges(String referencingPropertyName,
                                                                           IPersistentCollection newColl,
                                                                           object oldColl, object id)
        {
            if (!commonCollectionMapperData.CollectionReferencingPropertyData.Name
                .Equals(referencingPropertyName))
            {
                return(null);
            }

            IList <PersistentCollectionChangeData> collectionChanges = new List <PersistentCollectionChangeData>();

            // Comparing new and old collection content.
            ICollection <object> newCollection = GetNewCollectionContent(newColl);
            ICollection <object> oldCollection = GetOldCollectionContent(oldColl);

            ISet <Object> added = new HashedSet <Object>();

            if (newColl != null)
            {
                added.AddAll(newCollection);
            }
            // Re-hashing the old collection as the hash codes of the elements there may have changed, and the
            // removeAll in AbstractSet has an implementation that is hashcode-change sensitive (as opposed to addAll).
            if (oldColl != null)
            {
                added.RemoveAll(new HashedSet <object>(oldCollection));
            }

            addCollectionChanges(collectionChanges, added, RevisionType.ADD, id);

            Set <Object> deleted = new HashedSet <Object>();

            if (oldColl != null)
            {
                deleted.AddAll(oldCollection);
            }
            // The same as above - re-hashing new collection.
            if (newColl != null)
            {
                deleted.RemoveAll(new HashedSet <object>(newCollection));
            }

            addCollectionChanges(collectionChanges, deleted, RevisionType.DEL, id);

            return(collectionChanges);
        }
Example #16
0
            public List <InterpretationStep> Execute(ReportingProcedureStep step, Staff executingStaff, Staff assignStaff, IWorkflow workflow)
            {
                step.Discontinue();

                // cancel the report part if exists
                if (step.ReportPart != null)
                {
                    step.ReportPart.Cancel();
                }

                var interpretationSteps = new List <InterpretationStep>();

                if (!IsAddendumStep(step))
                {
                    var procedures = new HashedSet <Procedure> {
                        step.Procedure
                    };

                    // if there are linked procedures, schedule a new interpretation for each procedure being reported
                    if (step.ReportPart != null)
                    {
                        procedures.AddAll(step.ReportPart.Report.Procedures);
                    }

                    // schedule new interpretations
                    foreach (var procedure in procedures)
                    {
                        var interpretationStep = new InterpretationStep(procedure);

                        // Bug: #5128 - if the procedure is not document, do not schedule the replacement interpretation step,
                        // since interpretation steps aren't scheduled until documentation is complete.
                        if (procedure.IsDocumented)
                        {
                            interpretationStep.Schedule(procedure.PerformedTime);
                        }

                        if (assignStaff != null)
                        {
                            interpretationStep.Assign(assignStaff);
                        }

                        interpretationSteps.Add(interpretationStep);
                        workflow.AddEntity(interpretationStep);
                    }
                }
                return(interpretationSteps);
            }
Example #17
0
        /// <summary>
        /// Sets error message that should be displayed in the case
        /// of a non-fatal binding error.
        /// </summary>
        /// <param name="messageId">
        /// Resource ID of the error message.
        /// </param>
        /// <param name="errorProviders">
        /// List of error providers message should be added to.
        /// </param>
        public void SetErrorMessage(string messageId, params string[] errorProviders)
        {
            AssertUtils.ArgumentHasText(messageId, "messageId");
            if (errorProviders == null || errorProviders.Length == 0)
            {
                throw new ArgumentException("At least one error provider has to be specified.", "providers");
            }

            this.errorMessage = new BindingErrorMessage(this.BINDING_ID, messageId, null);
            Set providers = new HashedSet();

            providers.Add(ALL_BINDINGERRORS_PROVIDER);
            providers.AddAll(errorProviders);
            errorProviders = new string[providers.Count];
            providers.CopyTo(errorProviders, 0);
            this.errorProviders = errorProviders;
        }
Example #18
0
        private IList ListUsingQueryCache()
        {
            IQueryCache queryCache = session.Factory.GetQueryCache(cacheRegion);

            ISet <FilterKey> filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters, session.EntityMode);

            ISet <string>  querySpaces     = new HashedSet <string>();
            List <IType[]> resultTypesList = new List <IType[]>(Translators.Count);

            for (int i = 0; i < Translators.Count; i++)
            {
                ITranslator queryTranslator = Translators[i];
                querySpaces.AddAll(queryTranslator.QuerySpaces);
                resultTypesList.Add(queryTranslator.ReturnTypes);
            }
            int[] firstRows = new int[Parameters.Count];
            int[] maxRows   = new int[Parameters.Count];
            for (int i = 0; i < Parameters.Count; i++)
            {
                RowSelection rowSelection = Parameters[i].RowSelection;
                firstRows[i] = rowSelection.FirstRow;
                maxRows[i]   = rowSelection.MaxRows;
            }

            MultipleQueriesCacheAssembler assembler = new MultipleQueriesCacheAssembler(resultTypesList);

            QueryKey key = new QueryKey(session.Factory, SqlString, combinedParameters, filterKeys)
                           .SetFirstRows(firstRows)
                           .SetMaxRows(maxRows);

            IList result = assembler.GetResultFromQueryCache(session, combinedParameters, querySpaces, queryCache, key);

            if (result == null)
            {
                log.Debug("Cache miss for multi query");
                var list = DoList();
                queryCache.Put(key, new ICacheAssembler[] { assembler }, new object[] { list }, false, session);
                result = list;
            }

            return(GetResultList(result));
        }
Example #19
0
        private IList ListUsingQueryCache()
        {
            IQueryCache queryCache = session.Factory.GetQueryCache(cacheRegion);

            ISet filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters, session.EntityMode);

            ISet <string>  querySpaces     = new HashedSet <string>();
            List <IType[]> resultTypesList = new List <IType[]>();

            int[] maxRows   = new int[loaders.Count];
            int[] firstRows = new int[loaders.Count];
            for (int i = 0; i < loaders.Count; i++)
            {
                querySpaces.AddAll(loaders[i].QuerySpaces);
                resultTypesList.Add(loaders[i].ResultTypes);
                firstRows[i] = parameters[i].RowSelection.FirstRow;
                maxRows[i]   = parameters[i].RowSelection.MaxRows;
            }

            MultipleQueriesCacheAssembler assembler = new MultipleQueriesCacheAssembler(resultTypesList);
            QueryParameters combinedParameters      = CreateCombinedQueryParameters();
            QueryKey        key = new QueryKey(session.Factory, SqlString, combinedParameters, filterKeys)
                                  .SetFirstRows(firstRows)
                                  .SetMaxRows(maxRows);

            IList result =
                assembler.GetResultFromQueryCache(session,
                                                  combinedParameters,
                                                  querySpaces,
                                                  queryCache,
                                                  key);

            if (result == null)
            {
                log.Debug("Cache miss for multi criteria query");
                IList list = DoList();
                queryCache.Put(key, new ICacheAssembler[] { assembler }, new object[] { list }, combinedParameters.NaturalKeyLookup, session);
                result = list;
            }

            return(GetResultList(result));
        }
        public ListPerformedProcedureStepsResponse ListPerformedProcedureSteps(ListPerformedProcedureStepsRequest request)
        {
            var order = this.PersistenceContext.Load <Order>(request.OrderRef);

            var assembler = new ModalityPerformedProcedureStepAssembler();

            var mppsSet = new HashedSet <PerformedStep>();

            foreach (var procedure in order.Procedures)
            {
                foreach (var mps in procedure.ModalityProcedureSteps)
                {
                    mppsSet.AddAll(mps.PerformedSteps);
                }
            }

            return(new ListPerformedProcedureStepsResponse(
                       CollectionUtils.Map <ModalityPerformedProcedureStep, ModalityPerformedProcedureStepDetail>(
                           mppsSet,
                           mpps => assembler.CreateModalityPerformedProcedureStepDetail(mpps, this.PersistenceContext))));
        }
        private IList<Type> EntityPropertyAndCollectionTypes()
        {
            ISet<Type> types = new HashedSet<Type>();
            foreach(var type in Assembly.GetTypes())
            {
                if (!DomainFilter(type)) continue;
                foreach(var property in type.GetProperties())
                {

                    var referred = new List<Type>(
                        property.PropertyType.IsGenericType
                            ? property.PropertyType.GetGenericArguments()
                            : new[] {property.PropertyType});

                    referred.Remove(type); // remove self-reference

                    types.AddAll(referred);
                }
            }
            return new List<Type>(types);
        }
Example #22
0
        private static Combination FindRootCombination(IEnumerable <Combination> combinations)
        {
            HashedSet <EquivalenceClass> equivalenceClasses = new HashedSet <EquivalenceClass>();

            foreach (Combination combination in combinations)
            {
                equivalenceClasses.AddAll(combination.GetAllEquivalenceClasses());
            }

            foreach (Combination combination1 in combinations)
            {
                CombinationManager cm = new CombinationManager(combination1);
                foreach (EquivalenceClass equivalenceClass in equivalenceClasses)
                {
                    if (cm.FindMergeableCombinations(equivalenceClass).Count > 0)
                    {
                        return(combination1);
                    }
                }
            }
            return(null);
        }
        public override IAuditWorkUnit Merge(FakeBidirectionalRelationWorkUnit second)
        {
            // First merging the nested work units.
            IAuditWorkUnit mergedNested = second.getNestedWorkUnit().Dispatch(nestedWorkUnit);

            // Now merging the fake relation changes from both work units.
            IDictionary <String, FakeRelationChange> secondFakeRelationChanges = second.getFakeRelationChanges();
            IDictionary <String, FakeRelationChange> mergedFakeRelationChanges = new Dictionary <String, FakeRelationChange>();
            //TODO Simon - decide if we use IESI.Collections in the end.
            ISet <String> allPropertyNames = new HashedSet <String>(fakeRelationChanges.Keys);

            allPropertyNames.AddAll(secondFakeRelationChanges.Keys);

            foreach (String propertyName in allPropertyNames)
            {
                mergedFakeRelationChanges.Add(propertyName,
                                              FakeRelationChange.Merge(
                                                  fakeRelationChanges[propertyName],
                                                  secondFakeRelationChanges[propertyName]));
            }

            return(new FakeBidirectionalRelationWorkUnit(this, mergedFakeRelationChanges, mergedNested));
        }
        public IList<UnitaImmobiliare> GetUnitaContoModello(MovimentoContabile movimento, int index)
        {
            try
            {
                Iesi.Collections.Generic.ISet<UnitaImmobiliare> listaUnita = new HashedSet<UnitaImmobiliare>();
                if (movimento.Spesa != null)
                {
                    if (movimento.Spesa.Utenza.ModelloRegistrazione.Conti.Count > index)
                    {
                        var dettaglioModello = movimento.Spesa.Utenza.ModelloRegistrazione.Conti.ToList()[index];
                        listaUnita.AddAll(getUnitaByConto(dettaglioModello));
                    }
                    else
                        listaUnita.AddAll(movimento.Testata.EsercizioRiferimento.CondominioRiferimento.GetUnitaImmobiliari());
                }

                return listaUnita.ToList();
            }
            catch (Exception ex)
            {
                
                _log.Error("Errore nella lettura delle unità - " + Library.Utility.GetMethodDescription() + " - movimento:" + movimento.ID + " - index:" + index, ex);
                throw;
            }
        }
        public AssignmentSpecification(IASTNode eq, IQueryable persister)
        {
            if (eq.Type != HqlSqlWalker.EQ)
            {
                throw new QueryException("assignment in set-clause not associated with equals");
            }

            _eq      = eq;
            _factory = persister.Factory;

            // Needed to bump this up to DotNode, because that is the only thing which currently
            // knows about the property-ref path in the correct format; it is either this, or
            // recurse over the DotNodes constructing the property path just like DotNode does
            // internally
            DotNode lhs;

            try
            {
                lhs = (DotNode)eq.GetFirstChild();
            }
            catch (InvalidCastException e)
            {
                throw new QueryException(
                          string.Format("Left side of assigment should be a case sensitive property or a field (depending on mapping); found '{0}'", eq.GetFirstChild()), e);
            }
            var rhs = (SqlNode)lhs.NextSibling;

            ValidateLhs(lhs);

            string propertyPath = lhs.PropertyPath;
            var    temp         = new HashedSet <string>();
            // yuck!
            var usep = persister as UnionSubclassEntityPersister;

            if (usep != null)
            {
                temp.AddAll(persister.ConstraintOrderedTableNameClosure);
            }
            else
            {
                temp.Add(persister.GetSubclassTableName(persister.GetSubclassPropertyTableNumber(propertyPath)));
            }
            _tableNames = new ImmutableSet <string>(temp);

            if (rhs == null)
            {
                _hqlParameters = new IParameterSpecification[0];
            }
            else if (IsParam(rhs))
            {
                _hqlParameters = new[] { ((ParameterNode)rhs).HqlParameterSpecification };
            }
            else
            {
                var parameterList = ASTUtil.CollectChildren(rhs, IsParam);
                _hqlParameters = new IParameterSpecification[parameterList.Count];
                int i = 0;
                foreach (ParameterNode parameterNode in parameterList)
                {
                    _hqlParameters[i++] = parameterNode.HqlParameterSpecification;
                }
            }
        }
        public override IAuditWorkUnit Merge(FakeBidirectionalRelationWorkUnit second)
        {
            // First merging the nested work units.
            IAuditWorkUnit mergedNested = second.getNestedWorkUnit().Dispatch(nestedWorkUnit);

            // Now merging the fake relation changes from both work units.
            IDictionary<String, FakeRelationChange> secondFakeRelationChanges = second.getFakeRelationChanges();
            IDictionary<String, FakeRelationChange> mergedFakeRelationChanges = new Dictionary<String, FakeRelationChange>();
            //TODO Simon - decide if we use IESI.Collections in the end.
            ISet<String> allPropertyNames = new HashedSet<String>(fakeRelationChanges.Keys);
            allPropertyNames.AddAll(secondFakeRelationChanges.Keys);

            foreach (String propertyName in allPropertyNames) {
                mergedFakeRelationChanges.Add(propertyName,
                        FakeRelationChange.Merge(
                                fakeRelationChanges[propertyName],
                                secondFakeRelationChanges[propertyName]));
            }

            return new FakeBidirectionalRelationWorkUnit(this, mergedFakeRelationChanges, mergedNested);
        }
Example #27
0
 public static bool AddAll(ICollection source, HashedSet dest)
 {
     return(dest.AddAll(source));
 }
Example #28
0
		public GetPriorsResponse GetPriors(GetPriorsRequest request)
		{
			Platform.CheckForNullReference(request, "request");
			if (request.OrderRef == null && request.ReportRef == null)
				throw new ArgumentException("Either OrderRef or ReportRef must be non-null");

			var priorReports = new HashedSet<Prior>();
			var broker = this.PersistenceContext.GetBroker<IPriorReportBroker>();

			// if an order was supplied, find relevant priors for the order
			if (request.OrderRef != null)
			{
				var order = this.PersistenceContext.Load<Order>(request.OrderRef, EntityLoadFlags.Proxy);
				priorReports.AddAll(broker.GetPriors(order, request.RelevantOnly));
			}
			// if a report was supplied, find relevent priors for the report
			else if (request.ReportRef != null)
			{
				var report = this.PersistenceContext.Load<Report>(request.ReportRef, EntityLoadFlags.Proxy);
				priorReports.AddAll(broker.GetPriors(report, request.RelevantOnly));
			}

			// assemble results
			var procedureTypeAssembler = new ProcedureTypeAssembler();
			var diagnosticServiceAssembler = new DiagnosticServiceAssembler();

			// Note: we use the ProcedureCheckin.CheckOutTime as the PerformedDate
			// because it is the closest to the end of modality procedure step completion time.
			// However, if we change the definition of CheckOutTime in the future, this won't be accurate
			var priorSummaries = CollectionUtils.Map(priorReports,
				(Prior prior) => new PriorProcedureSummary(
							prior.Order.GetRef(),
							prior.Procedure.GetRef(),
				         	prior.Report.GetRef(),
							prior.Order.AccessionNumber,
							diagnosticServiceAssembler.CreateSummary(prior.Order.DiagnosticService),
							procedureTypeAssembler.CreateSummary(prior.ProcedureType),
							prior.Procedure.Portable,
							EnumUtils.GetEnumValueInfo(prior.Procedure.Laterality, PersistenceContext),
							EnumUtils.GetEnumValueInfo(prior.Report.Status, PersistenceContext),
							prior.Procedure.ProcedureCheckIn.CheckOutTime));

			return new GetPriorsResponse(priorSummaries);
		}
Example #29
0
		private IList ListUsingQueryCache()
		{
			IQueryCache queryCache = session.Factory.GetQueryCache(cacheRegion);

			ISet filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters, session.EntityMode);

			Iesi.Collections.Generic.ISet<string> querySpaces = new HashedSet<string>();
			ArrayList resultTypesList = new ArrayList();
			int[] maxRows = new int[loaders.Count];
			int[] firstRows = new int[loaders.Count];
			for (int i = 0; i < loaders.Count; i++)
			{
				querySpaces.AddAll(loaders[i].QuerySpaces);
				resultTypesList.Add(loaders[i].ResultTypes);
				firstRows[i] = parameters[i].RowSelection.FirstRow;
				maxRows[i] = parameters[i].RowSelection.MaxRows;
			}

			MultipleQueriesCacheAssembler assembler = new MultipleQueriesCacheAssembler(resultTypesList);
			QueryParameters combinedParameters = CreateCombinedQueryParameters();
			QueryKey key = new QueryKey(session.Factory, SqlString, combinedParameters, filterKeys)
				.SetFirstRows(firstRows)
				.SetMaxRows(maxRows);

			IList result =
				assembler.GetResultFromQueryCache(session,
				                                  combinedParameters,
				                                  querySpaces,
				                                  queryCache,
				                                  key);

			if (result == null)
			{
				log.Debug("Cache miss for multi criteria query");
				IList list = DoList();
				queryCache.Put(key, new ICacheAssembler[] {assembler}, new object[] {list}, session);
				result = list;
			}

			return GetResultList(result);
		}
Example #30
0
        /**
         * Bir eke iliskin ardisil ekler belirlenir. ardisil ekler
         * a) ek kumelerinden
         * b) normal tek olarak
         * c) dogrudan baska bir ekin ardisil eklerinden kopyalanarak
         * elde edilir.
         * Ayrica eger oncelikli ekler belirtilmis ise bu ekler ardisil ek listeisnin en basina koyulur.
         *
         * @param ekElement :  ek xml bileseni..
         * @return Ek referans Listesi.
         * @param anaEk ardisil ekler eklenecek asil ek
         */
        private List <Ek> ardisilEkleriOlustur(Ek anaEk, XmlElement ekElement)
        {
            Set <Ek>   ardisilEkSet   = new HashedSet <Ek>();
            XmlElement ardisilEklerEl = (XmlElement)ekElement.SelectNodes("ardisil-ekler")[0];

            if (ardisilEklerEl == null)
            {
                return(new List <Ek>());
            }

            // tek ekleri ekle.
            XmlNodeList tekArdisilEkler = ardisilEklerEl.SelectNodes("aek");

            foreach (XmlElement element in tekArdisilEkler)
            {
                String ekAdi = element.InnerText;
                Ek     ek    = this.ekler[ekAdi];
                if (ek == null)
                {
                    exit(anaEk.ad() + " icin ardisil ek bulunamiyor! " + ekAdi);
                }
                ardisilEkSet.Add(ek);
            }

            // kume eklerini ekle.
            XmlNodeList kumeEkler = ardisilEklerEl.SelectNodes("kume");

            foreach (XmlElement element in kumeEkler)
            {
                String   kumeAdi    = element.InnerText;
                Set <Ek> kumeEkleri = ekKumeleri[kumeAdi];
                if (kumeEkleri == null)
                {
                    exit("kume bulunamiyor..." + kumeAdi);
                }
                ardisilEkSet.AddAll(kumeEkleri);
            }

            //varsa baska bir ekin ardisil eklerini kopyala.
            XmlAttribute attr = ardisilEklerEl.GetAttributeNode("kopya-ek");

            if (attr != null)
            {
                String kopyaEkadi = attr.Value;
                Ek     ek         = this.ekler[kopyaEkadi];
                if (ek == null)
                {
                    exit(anaEk.ad() + " icin kopyalanacak ek bulunamiyor! " + kopyaEkadi);
                }
                ardisilEkSet.AddAll(ek.ardisilEkler());
            }

            List <Ek> ardisilEkler = new List <Ek>(ardisilEkSet.Count);

            //varsa oncelikli ekleri oku ve ardisil ekler listesinin ilk basina koy.
            // bu tamamen performans ile iliskili bir islemdir.
            XmlElement oncelikliEklerEl = (XmlElement)ekElement.SelectNodes("oncelikli-ekler")[0];

            if (oncelikliEklerEl != null)
            {
                XmlNodeList oncelikliEkler = oncelikliEklerEl.SelectNodes("oek");
                foreach (XmlElement element in oncelikliEkler)
                {
                    String ekAdi = element.InnerText;
                    Ek     ek    = this.ekler[ekAdi];
                    if (ek == null)
                    {
                        exit(anaEk.ad() + " icin oncelikli ek bulunamiyor! " + ekAdi);
                    }
                    if (ardisilEkSet.Contains(ek))
                    {
                        ardisilEkler.Add(ek);
                        ardisilEkSet.Remove(ek);
                    }
                    else
                    {
                        logger.Warn(anaEk.ad() + "icin oncelikli ek:" + ekAdi + " bu ekin ardisil eki degil!");
                    }
                }
            }

            ardisilEkler.AddRange(ardisilEkSet);
            return(ardisilEkler);
        }
Example #31
0
 protected void UpdateBoundarySuffixes(HashedSet <int> newBoundarySuffix)
 {
     boundarySuffix.Clear();
     boundarySuffix.AddAll(newBoundarySuffix);
 }
Example #32
0
		public ListPerformedProcedureStepsResponse ListPerformedProcedureSteps(ListPerformedProcedureStepsRequest request)
		{
			var order = this.PersistenceContext.Load<Order>(request.OrderRef);

			var assembler = new ModalityPerformedProcedureStepAssembler();

			var mppsSet = new HashedSet<PerformedStep>();
			foreach (var procedure in order.Procedures)
			{
				foreach (var mps in procedure.ModalityProcedureSteps)
				{
					mppsSet.AddAll(mps.PerformedSteps);
				}
			}

			return new ListPerformedProcedureStepsResponse(
				CollectionUtils.Map<ModalityPerformedProcedureStep, ModalityPerformedProcedureStepDetail>(
					mppsSet,
					mpps => assembler.CreateModalityPerformedProcedureStepDetail(mpps, this.PersistenceContext)));
		}
Example #33
0
 public static bool AddAll(ICollection source, HashedSet dest)
 {
     return dest.AddAll(source);
 }
		public AssignmentSpecification(IASTNode eq, IQueryable persister)
		{
			if (eq.Type != HqlSqlWalker.EQ)
			{
				throw new QueryException("assignment in set-clause not associated with equals");
			}

			_eq = eq;
			_factory = persister.Factory;

			// Needed to bump this up to DotNode, because that is the only thing which currently
			// knows about the property-ref path in the correct format; it is either this, or
			// recurse over the DotNodes constructing the property path just like DotNode does
			// internally
			DotNode lhs;
			try
			{
				lhs = (DotNode)eq.GetFirstChild();
			}
			catch (InvalidCastException e)
			{
				throw new QueryException(
					string.Format("Left side of assigment should be a case sensitive property or a field (depending on mapping); found '{0}'", eq.GetFirstChild()), e);
			}
			var rhs = (SqlNode)lhs.NextSibling;

			ValidateLhs(lhs);

			string propertyPath = lhs.PropertyPath;
			var temp = new HashedSet<string>();
			// yuck!
			var usep = persister as UnionSubclassEntityPersister;
			if (usep!=null)
			{
				temp.AddAll(persister.ConstraintOrderedTableNameClosure);
			}
			else
			{
				temp.Add(persister.GetSubclassTableName(persister.GetSubclassPropertyTableNumber(propertyPath)));
			}
			_tableNames = new ImmutableSet<string>(temp);

			if (rhs == null)
			{
				_hqlParameters = new IParameterSpecification[0];
			}
			else if (IsParam(rhs))
			{
				_hqlParameters = new[] { ((ParameterNode)rhs).HqlParameterSpecification };
			}
			else
			{
				var parameterList = ASTUtil.CollectChildren(rhs, IsParam);
				_hqlParameters = new IParameterSpecification[parameterList.Count];
				int i = 0;
				foreach (ParameterNode parameterNode in parameterList)
				{
					_hqlParameters[i++] = parameterNode.HqlParameterSpecification;
				}
			}
		}
 private void BuildClusters()
 {
     try
     {
         buildClustersLock.Lock();
         int numUsers = this.DataModel.GetNumUsers();
         if (numUsers > 0)
         {
             List <ICollection <User> > newClusters = new List <ICollection <User> >(numUsers);
             if (numUsers == 1)
             {
                 IEnumerable <User> users = this.DataModel.GetUsers();
                 User onlyUser            = null;
                 foreach (User user in users)
                 {
                     onlyUser = user;
                     break;
                 }
                 List <User> single = new List <User>(1);
                 single.Add(onlyUser);
                 newClusters.Add(single);
             }
             else
             {
                 // Begin with a cluster for each user:
                 foreach (User user in this.DataModel.GetUsers())
                 {
                     ICollection <User> newCluster = new HashedSet <User>();
                     newCluster.Add(user);
                     newClusters.Add(newCluster);
                 }
                 if (clusteringByThreshold)
                 {
                     Pair <ICollection <User>, ICollection <User> > nearestPair = FindNearestClusters(newClusters);
                     if (nearestPair != null)
                     {
                         ICollection <User> cluster1 = nearestPair.First;
                         ICollection <User> cluster2 = nearestPair.Second;
                         while (clusterSimilarity.GetSimilarity(cluster1, cluster2) >= clusteringThreshold)
                         {
                             newClusters.Remove(cluster1);
                             newClusters.Remove(cluster2);
                             HashedSet <User> merged = new HashedSet <User>(/*cluster1.Count + cluster2.Count*/);
                             merged.AddAll(cluster1);
                             merged.AddAll(cluster2);
                             newClusters.Add(merged);
                             nearestPair = FindNearestClusters(newClusters);
                             if (nearestPair == null)
                             {
                                 break;
                             }
                             cluster1 = nearestPair.First;
                             cluster2 = nearestPair.Second;
                         }
                     }
                 }
                 else
                 {
                     while (newClusters.Count > numClusters)
                     {
                         Pair <ICollection <User>, ICollection <User> > nearestPair =
                             FindNearestClusters(newClusters);
                         if (nearestPair == null)
                         {
                             break;
                         }
                         ICollection <User> cluster1 = nearestPair.First;
                         ICollection <User> cluster2 = nearestPair.Second;
                         newClusters.Remove(cluster1);
                         newClusters.Remove(cluster2);
                         HashedSet <User> merged = new HashedSet <User>(/*cluster1.Count + cluster2.Count*/);
                         merged.AddAll(cluster1);
                         merged.AddAll(cluster2);
                         newClusters.Add(merged);
                     }
                 }
             }
             topRecsByUserID  = ComputeTopRecsPerUserID(newClusters);
             clustersByUserID = ComputeClustersPerUserID(newClusters);
         }
         else
         {
             topRecsByUserID  = new Dictionary <object, IList <RecommendedItem> >();
             clustersByUserID = new Dictionary <object, ICollection <User> >();
         }
         clustersBuilt = true;
     } finally {
         buildClustersLock.Unlock();
     }
 }
		public ISet GetQuerySpaces()
		{
			ISet result = new HashedSet();

			foreach (System.Type entityName in criteriaEntityNames.Values)
			{
				result.AddAll(Factory.GetEntityPersister(entityName).QuerySpaces);
			}

			foreach (ICollectionPersister collectionPersister in criteriaCollectionPersisters)
			{
				result.Add(collectionPersister.CollectionSpace);
			}
			return result;
		}
        public IList<UnitaImmobiliare> GetUnitaModello(ModelloRegistrazioneContabile modello)
        {
            Iesi.Collections.Generic.ISet<UnitaImmobiliare> listaUnita = new HashedSet<UnitaImmobiliare>();
            foreach (var dettaglioModello in modello.Conti)
                listaUnita.AddAll(getUnitaByConto(dettaglioModello));

            return listaUnita.ToList();
        }
Example #38
0
        private void BuildClusters()
        {
            try
            {
                buildClustersLock.Lock();

                DataModel model    = this.DataModel;
                int       numUsers = model.GetNumUsers();

                if (numUsers == 0)
                {
                    topRecsByUserID  = new Dictionary <object, IList <RecommendedItem> >();
                    clustersByUserID = new Dictionary <object, ICollection <User> >();
                }
                else
                {
                    LinkedList <ICollection <User> > clusters = new LinkedList <ICollection <User> >();
                    // Begin with a cluster for each user:
                    foreach (User user in model.GetUsers())
                    {
                        ICollection <User> newCluster = new HashedSet <User>();
                        newCluster.Add(user);
                        clusters.AddLast(newCluster);
                    }

                    bool done = false;
                    while (!done)
                    {
                        // We find a certain number of closest clusters...
                        bool full = false;
                        LinkedList <ClusterClusterPair> queue = new LinkedList <ClusterClusterPair>();
                        int i = 0;
                        LinkedListNode <ICollection <User> > it2 = clusters.First;
                        foreach (ICollection <User> cluster1 in clusters)
                        {
                            i++;
                            //ListIterator<ICollection<User>> it2 = clusters.listIterator(i);
                            it2 = it2.Next;
                            while (it2.Next != null)
                            {
                                it2 = it2.Next;
                                ICollection <User> cluster2   = it2.Value;
                                double             similarity = clusterSimilarity.GetSimilarity(cluster1, cluster2);
                                if (!double.IsNaN(similarity) &&
                                    (!full || similarity > queue.Last.Value.Similarity))
                                {
                                    LinkedListNode <ClusterClusterPair> qit = queue.Last;

                                    /// loop looks fishy
                                    while (qit.Previous != null)
                                    {
                                        if (similarity <= qit.Previous.Value.Similarity)
                                        {
                                            break;
                                        }
                                        qit = qit.Previous;
                                    }
                                    queue.AddAfter(qit, new ClusterClusterPair(cluster1, cluster2, similarity));
                                    if (full)
                                    {
                                        queue.RemoveLast();
                                    }
                                    else if (queue.Count > numUsers)
                                    {
                                        // use numUsers as queue size limit
                                        full = true;
                                        queue.RemoveLast();
                                    }
                                }
                            }
                        }

                        // The first one is definitely the closest pair in existence so we can cluster
                        // the two together, put it back into the set of clusters, and start again. Instead
                        // we assume everything else in our list of closest cluster pairs is still pretty good,
                        // and we cluster them too.

                        while (queue.Count > 0)
                        {
                            if (!clusteringByThreshold && clusters.Count <= numClusters)
                            {
                                done = true;
                                break;
                            }

                            ClusterClusterPair top = queue.First.Value;
                            queue.RemoveFirst();

                            if (clusteringByThreshold && top.Similarity < clusteringThreshold)
                            {
                                done = true;
                                break;
                            }

                            ICollection <User> cluster1 = top.Cluster1;
                            ICollection <User> cluster2 = top.Cluster2;

                            // Pull out current two clusters from clusters
                            clusters.Remove(cluster1);
                            clusters.Remove(cluster2);

                            // The only catch is if a cluster showed it twice in the list of best cluster pairs;
                            // have to remove the others. Pull out anything referencing these clusters from queue
                            for (LinkedListNode <ClusterClusterPair> qit = queue.First; qit != null; qit = qit.Next)
                            {
                                ClusterClusterPair pair  = qit.Value;
                                ICollection <User> pair1 = pair.Cluster1;
                                ICollection <User> pair2 = pair.Cluster2;

                                if (pair1 == cluster1 || pair1 == cluster2 || pair2 == cluster1 || pair2 == cluster2)
                                {
                                    if (qit == queue.First)
                                    {
                                        queue.RemoveFirst();
                                        qit = queue.First;
                                        continue;
                                    }
                                    else
                                    {
                                        LinkedListNode <ClusterClusterPair> temp = qit;
                                        qit = qit.Previous;
                                        queue.Remove(temp);
                                    }
                                }
                            }

                            // Make new merged cluster
                            HashedSet <User> merged = new HashedSet <User>(/*cluster1.Count + cluster2.Count*/);
                            merged.AddAll(cluster1);
                            merged.AddAll(cluster2);

                            // Compare against other clusters; update queue if needed
                            // That new pair we're just adding might be pretty close to something else, so
                            // catch that case here and put it back into our queue
                            foreach (ICollection <User> cluster in clusters)
                            {
                                double similarity = clusterSimilarity.GetSimilarity(merged, cluster);
                                if (similarity > queue.Last.Value.Similarity)
                                {
                                    // Iteration needs to be validated agains Java version
                                    LinkedListNode <ClusterClusterPair> qit = queue.First;
                                    while (qit.Next != null)
                                    {
                                        if (similarity > qit.Next.Value.Similarity)
                                        {
                                            break;
                                        }
                                        qit = qit.Next;
                                    }
                                    queue.AddAfter(qit, new ClusterClusterPair(merged, cluster, similarity));
                                }
                            }

                            // Finally add new cluster to list
                            clusters.AddLast(merged);
                        }
                    }

                    topRecsByUserID  = ComputeTopRecsPerUserID(clusters);
                    clustersByUserID = ComputeClustersPerUserID(clusters);
                }

                clustersBuilt = true;
            } finally {
                buildClustersLock.Unlock();
            }
        }
        /// <summary>
        /// Creates a new practitioner that is the result of merging the two specified practitioners.
        /// </summary>
        /// <param name="right"></param>
        /// <param name="left"></param>
        /// <param name="name"></param>
        /// <param name="licenseNumber"></param>
        /// <param name="billingNumber"></param>
        /// <param name="extendedProperties"></param>
        /// <param name="defaultContactPoint"></param>
        /// <param name="deactivatedContactPoints"></param>
        /// <param name="contactPointReplacements"></param>
        /// <returns></returns>
        public static ExternalPractitioner MergePractitioners(
            ExternalPractitioner right,
            ExternalPractitioner left,
            PersonName name,
            string licenseNumber,
            string billingNumber,
            IDictionary <string, string> extendedProperties,
            ExternalPractitionerContactPoint defaultContactPoint,
            ICollection <ExternalPractitionerContactPoint> deactivatedContactPoints,
            IDictionary <ExternalPractitionerContactPoint, ExternalPractitionerContactPoint> contactPointReplacements)
        {
            // sanity check
            if (Equals(right, left))
            {
                throw new WorkflowException("Cannot merge a practitioner with itself.");
            }
            if (right.Deactivated || left.Deactivated)
            {
                throw new WorkflowException("Cannot merge a practitioner that is de-activated.");
            }
            if (right.IsMerged || left.IsMerged)
            {
                throw new WorkflowException("Cannot merge a practitioner that has already been merged.");
            }
            if (defaultContactPoint != null && defaultContactPoint.IsMerged)
            {
                throw new WorkflowException("Cannot assigned a merged contact point as default");
            }

            // update properties on result record
            var result = new ExternalPractitioner {
                Name = name, LicenseNumber = licenseNumber, BillingNumber = billingNumber
            };

            ExtendedPropertyUtils.Update(result.ExtendedProperties, extendedProperties);

            // construct the set of retained contact points
            var retainedContactPoints = new HashedSet <ExternalPractitionerContactPoint>();

            retainedContactPoints.AddAll(contactPointReplacements.Values);

            // some of the replacement contact points are merged.  This should not be allowed.
            if (CollectionUtils.Contains(contactPointReplacements.Values, cp => cp.IsMerged))
            {
                throw new WorkflowException("Cannot replace a contact point with another that has already been merged.");
            }

            // add any existing contact point that was not in the replacement list (because it is implicitly being retained)
            foreach (var contactPoint in CollectionUtils.Concat(right.ContactPoints, left.ContactPoints))
            {
                // No need to retain a merged contact point.  Because its replacement would already be retained.
                if (!contactPointReplacements.ContainsKey(contactPoint) && !contactPoint.IsMerged)
                {
                    retainedContactPoints.Add(contactPoint);
                }
            }

            // for all retained contact points, create a copy attached to the result practitioner,
            // and mark the original as having been merged into the copy
            foreach (var original in retainedContactPoints)
            {
                var copy = original.CreateCopy(result);
                result.ContactPoints.Add(copy);

                copy.IsDefaultContactPoint = original.Equals(defaultContactPoint);
                copy.MarkDeactivated(original.Deactivated || deactivatedContactPoints.Contains(original));
                original.SetMergedInto(copy);
            }

            // for all replaced contact points, mark the original as being merged into the
            // copy of the replacement
            foreach (var kvp in contactPointReplacements)
            {
                kvp.Key.SetMergedInto(kvp.Value.MergedInto);
            }

            // mark both left and right as edited and merged
            foreach (var practitioner in new[] { right, left })
            {
                practitioner.MarkEdited();
                practitioner.SetMergedInto(result);
            }

            // mark the result as being edited
            result.MarkEdited();
            return(result);
        }
Example #40
0
		public string ToSqlStringFragment(bool includeLeadingComma)
		{
			StringBuilder buf = new StringBuilder(columns.Count * 10);
			HashedSet columnsUnique = new HashedSet();

			if (usedAliases != null)
			{
				columnsUnique.AddAll(usedAliases);
			}

			bool found = false;
			for (int i = 0; i < columns.Count; i++)
			{
				string col = columns[i] as string;
				string columnAlias = columnAliases[i] as string;

				if (columnsUnique.Add(columnAlias))
				{
					if (found || includeLeadingComma)
					{
						buf.Append(StringHelper.CommaSpace);
					}

					buf.Append(col)
						.Append(" as ")
						.Append(new Alias(suffix).ToAliasString(columnAlias, dialect));

					// Set the flag for the next time
					found = true;
				}
			}

			if (extraSelectList != null)
			{
				if (found || includeLeadingComma)
				{
					buf.Append(StringHelper.CommaSpace);
				}

				buf.Append(extraSelectList);
			}

			return buf.ToString();
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="criteria"></param>
		/// <returns></returns>
		public IList Find( CriteriaImpl criteria )
		{
			// The body of this method is modified from H2.1 version, because the Java version
			// used factory.GetImplementors which returns a list of implementor class names
			// obtained from IClassPersister.ClassName property.
			//
			// In Java, calling ReflectHelper.ClassForName( IClassPersister.ClassName )
			// works, but in .NET it does not, because the class name does not include the assembly
			// name. .NET tries to load the class from NHibernate assembly and fails.
			//
			// The solution was to add SessionFactoryImpl.GetImplementorClasses method
			// which returns an array of System.Types instead of just class names.
			System.Type[ ] implementors = factory.GetImplementorClasses( criteria.CriteriaClass );
			int size = implementors.Length;

			CriteriaLoader[ ] loaders = new CriteriaLoader[size];
			ISet spaces = new HashedSet();

			for( int i = 0; i < size; i++ )
			{
				System.Type newCriteriaClazz = implementors[ i ];

				loaders[ i ] = new CriteriaLoader(
					GetOuterJoinLoadable( newCriteriaClazz ),
					factory,
					new CriteriaImpl( newCriteriaClazz, criteria )
					);

				spaces.AddAll( loaders[ i ].QuerySpaces );
			}

			AutoFlushIfRequired( spaces );

			IList results = new ArrayList();
			dontFlushFromFind++;
			try
			{
				for( int i = 0; i < size; i++ )
				{
					IList currentResults;
					try
					{
						currentResults = loaders[ i ].List( this );
					}
					catch( HibernateException )
					{
						// Do not call Convert on HibernateExceptions
						throw;
					}
					catch( Exception sqle )
					{
						throw Convert( sqle, "Unable to perform find" );
					}
					foreach( object result in results )
					{
						currentResults.Add( result );
					}
					results = currentResults;
				}
			}
			finally
			{
				dontFlushFromFind--;
			}

			return results;
		}
Example #42
0
        public BindingList<RichiedentePraticaDTO> GetSoggettiAttiviByCondominio(CondominioDTO condominio, IFornitoreService fornitoreService, IReferenteService referenteService, IPersonaService personaService)
        {
            BindingList<FornitoreDTO> fornitoriCompleti = fornitoreService.GetFornitoriCompletiByCondominio(condominio);
            BindingList<PersonaListaDTO> listaPersone = personaService.GetAll();

            IList<RichiedentePraticaDTO> fornitori = (from fornitore in fornitoriCompleti
                                                      select new RichiedentePraticaDTO() 
                                                      {
                                                          Id = fornitore.ID,
                                                          DisplayNominativo = fornitore.DisplayNominativo,
                                                          IdCondominio = condominio.ID,
                                                          IdPersona = fornitore.PersonaRiferimento.ID,
                                                          Tipo = fornitore.DescrizioneTipoFornitore
                                                      }).ToList();

            IList<RichiedentePraticaDTO> referenti = (from referente in referenteService.GetAllEffettivi()
                                                      join persona in listaPersone
                                                      on referente.PersonaId equals persona.ID
                                                      select new RichiedentePraticaDTO() 
                                                      {
                                                          Id = referente.ID,
                                                          DisplayNominativo = referente.NominativoPersona,
                                                          IdCondominio = condominio.ID,
                                                          IdPersona = referente.PersonaId,
                                                          Tipo = "Referente"
                                                      }).ToList();

            ISet<RichiedentePraticaDTO> soggetti = new HashedSet<RichiedentePraticaDTO>(referenti);
            soggetti.AddAll(fornitori);

            return new BindingList<RichiedentePraticaDTO>(soggetti.ToList());
        }
		private QueryTranslator[ ] GetQueries( string query, bool scalar )
		{
			// take the union of the query spaces (ie the queried tables)
			QueryTranslator[ ] q = factory.GetQuery( query, scalar );
			HashedSet qs = new HashedSet();
			for( int i = 0; i < q.Length; i++ )
			{
				qs.AddAll( q[ i ].QuerySpaces );
			}

			AutoFlushIfRequired( qs );

			return q;
		}
        public override IAuditWorkUnit Merge(FakeBidirectionalRelationWorkUnit second)
        {
            // First merging the nested work units.
            var mergedNested = second.NestedWorkUnit.Dispatch(NestedWorkUnit);

            // Now merging the fake relation changes from both work units.
            var secondFakeRelationChanges = second.fakeRelationChanges;
            var mergedFakeRelationChanges = new Dictionary<string, FakeRelationChange>();
            var allPropertyNames = new HashedSet<string>(fakeRelationChanges.Keys);
            allPropertyNames.AddAll(secondFakeRelationChanges.Keys);

            foreach (var propertyName in allPropertyNames)
            {
                mergedFakeRelationChanges.Add(propertyName,
                        FakeRelationChange.Merge(
                                fakeRelationChanges[propertyName],
                                secondFakeRelationChanges[propertyName]));
            }

            return new FakeBidirectionalRelationWorkUnit(this, mergedFakeRelationChanges, mergedNested);
        }
		public Iesi.Collections.Generic.ISet<string> GetQuerySpaces()
		{
			Iesi.Collections.Generic.ISet<string> result = new HashedSet<string>();

			foreach (ICriteriaInfoProvider info in criteriaInfoMap.Values)
			{
				result.AddAll(info.Spaces);
			}

			foreach (ICollectionPersister collectionPersister in criteriaCollectionPersisters)
			{
				result.AddAll(collectionPersister.CollectionSpaces);
			}
			return result;
		}
Example #46
0
		private void CreateCriteriaLoaders()
		{
			//a criteria can use more than a single query (polymorphic queries), need to have a 
			//way to correlate a loader to a result index
			int criteriaIndex = 0;
			foreach (CriteriaImpl criteria in criteriaQueries)
			{
				string[] implementors = factory.GetImplementors(criteria.EntityOrClassName);
				int size = implementors.Length;

				CriteriaLoader[] tmpLoaders = new CriteriaLoader[size];
				Iesi.Collections.Generic.ISet<string> spaces = new HashedSet<string>();

				for (int i = 0; i < size; i++)
				{
					CriteriaLoader loader = new CriteriaLoader(
						session.GetOuterJoinLoadable(implementors[i]),
						factory,
						criteria,
						implementors[i],
						session.EnabledFilters
						);
					tmpLoaders[i] = loader;
					loaderToResultIndex[loader] = criteriaIndex;
					spaces.AddAll(tmpLoaders[i].QuerySpaces);
				}
				loaders.AddRange(tmpLoaders);
				criteriaIndex += 1;
			}
		}
Example #47
0
        public BindingList<RichiedentePraticaDTO> GetAllSoggettiFornitori(CondominioDTO condominio)
        {
            IList<RichiedentePraticaDTO> fornitoriPreferiti = (from fornitore in _fornitoreService.GetPreferitiByCondominio(condominio.ID)
                                                               select new RichiedentePraticaDTO() 
                                                               {
                                                                   Id = fornitore.ID,
                                                                   DisplayNominativo = fornitore.PersonaRiferimento.DisplayName,
                                                                   IdCondominio = condominio.ID,
                                                                   IdPersona = fornitore.PersonaRiferimento.ID,
                                                                   Tipo = "Fornitore"
                                                               }).ToList();

            IList<RichiedentePraticaDTO> soggetti = (from soggetto in _soggettoService.GetByCondominio(condominio)
                                                     select new RichiedentePraticaDTO()
                                                     {
                                                         Id = soggetto.ID,
                                                         DisplayNominativo = soggetto.DisplayNominativo,
                                                         DescrizioneUnitaImmobiliare = soggetto.DescrizioneUnitaImmobiliare,
                                                         IdCondominio = condominio.ID,
                                                         IdPersona = soggetto.IdPersona,
                                                         IdUnitaImmobiliare = soggetto.IdUnitaImmobiliare,
                                                         OrdineUnitaImmobiliare = soggetto.OrdineUnitaImmobiliare,
                                                         Tipo = soggetto.Tipo.ToString()
                                                     }).ToList();

            ISet<RichiedentePraticaDTO> richiedenti = new HashedSet<RichiedentePraticaDTO>(soggetti);
            richiedenti.AddAll(fornitoriPreferiti);

            return new BindingList<RichiedentePraticaDTO>(richiedenti.ToList());
        }
		/// <summary>
		/// Creates a new practitioner that is the result of merging the two specified practitioners.
		/// </summary>
		/// <param name="right"></param>
		/// <param name="left"></param>
		/// <param name="name"></param>
		/// <param name="licenseNumber"></param>
		/// <param name="billingNumber"></param>
		/// <param name="extendedProperties"></param>
		/// <param name="defaultContactPoint"></param>
		/// <param name="deactivatedContactPoints"></param>
		/// <param name="contactPointReplacements"></param>
		/// <returns></returns>
		public static ExternalPractitioner MergePractitioners(
			ExternalPractitioner right,
			ExternalPractitioner left,
			PersonName name,
			string licenseNumber,
			string billingNumber,
			IDictionary<string, string> extendedProperties,
			ExternalPractitionerContactPoint defaultContactPoint,
			ICollection<ExternalPractitionerContactPoint> deactivatedContactPoints,
			IDictionary<ExternalPractitionerContactPoint, ExternalPractitionerContactPoint> contactPointReplacements)
		{
			// sanity check
			if (Equals(right, left))
				throw new WorkflowException("Cannot merge a practitioner with itself.");
			if (right.Deactivated || left.Deactivated)
				throw new WorkflowException("Cannot merge a practitioner that is de-activated.");
			if (right.IsMerged || left.IsMerged)
				throw new WorkflowException("Cannot merge a practitioner that has already been merged.");
			if (defaultContactPoint != null && defaultContactPoint.IsMerged)
				throw new WorkflowException("Cannot assigned a merged contact point as default");

			// update properties on result record
			var result = new ExternalPractitioner { Name = name, LicenseNumber = licenseNumber, BillingNumber = billingNumber };

			ExtendedPropertyUtils.Update(result.ExtendedProperties, extendedProperties);

			// construct the set of retained contact points
			var retainedContactPoints = new HashedSet<ExternalPractitionerContactPoint>();
			retainedContactPoints.AddAll(contactPointReplacements.Values);

			// some of the replacement contact points are merged.  This should not be allowed.
			if (CollectionUtils.Contains(contactPointReplacements.Values, cp => cp.IsMerged))
				throw new WorkflowException("Cannot replace a contact point with another that has already been merged.");

			// add any existing contact point that was not in the replacement list (because it is implicitly being retained)
			foreach (var contactPoint in CollectionUtils.Concat(right.ContactPoints, left.ContactPoints))
			{
				// No need to retain a merged contact point.  Because its replacement would already be retained.
				if (!contactPointReplacements.ContainsKey(contactPoint) && !contactPoint.IsMerged)
					retainedContactPoints.Add(contactPoint);
			}

			// for all retained contact points, create a copy attached to the result practitioner,
			// and mark the original as having been merged into the copy
			foreach (var original in retainedContactPoints)
			{
				var copy = original.CreateCopy(result);
				result.ContactPoints.Add(copy);

				copy.IsDefaultContactPoint = original.Equals(defaultContactPoint);
				copy.MarkDeactivated(original.Deactivated || deactivatedContactPoints.Contains(original));
				original.SetMergedInto(copy);
			}

			// for all replaced contact points, mark the original as being merged into the 
			// copy of the replacement
			foreach (var kvp in contactPointReplacements)
			{
				kvp.Key.SetMergedInto(kvp.Value.MergedInto);
			}

			// mark both left and right as edited and merged
			foreach (var practitioner in new[] { right, left })
	{
				practitioner.MarkEdited();
				practitioner.SetMergedInto(result);
			}

			// mark the result as being edited
			result.MarkEdited();
			return result;
		}
        /// <summary>
        /// Sets error message that should be displayed in the case 
        /// of a non-fatal binding error.
        /// </summary>
        /// <param name="messageId">
        /// Resource ID of the error message.
        /// </param>
        /// <param name="errorProviders">
        /// List of error providers message should be added to.
        /// </param>
        public void SetErrorMessage(string messageId, params string[] errorProviders)
        {
            AssertUtils.ArgumentHasText(messageId, "messageId");
            if (errorProviders == null || errorProviders.Length == 0)
            {
                throw new ArgumentException("At least one error provider has to be specified.", "providers");
            }

            this.errorMessage = new BindingErrorMessage(this.BINDING_ID, messageId, null);
            Set providers = new HashedSet();
            providers.Add(ALL_BINDINGERRORS_PROVIDER);
            providers.AddAll(errorProviders);
            errorProviders = new string[providers.Count];
            providers.CopyTo(errorProviders, 0);
            this.errorProviders = errorProviders;
        }
Example #50
0
		private IList ListUsingQueryCache()
		{
			IQueryCache queryCache = session.Factory.GetQueryCache(cacheRegion);

			ISet filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters, session.EntityMode);

			ISet<string> querySpaces = new HashedSet<string>();
			ArrayList resultTypesList = new ArrayList();
			for (int i = 0; i < Translators.Count; i++)
			{
				QueryTranslator queryTranslator = (QueryTranslator)Translators[i];
				querySpaces.AddAll(queryTranslator.QuerySpaces);
				resultTypesList.Add(queryTranslator.ActualReturnTypes);
			}
			int[] firstRows = new int[Parameters.Count];
			int[] maxRows = new int[Parameters.Count];
			for (int i = 0; i < Parameters.Count; i++)
			{
				RowSelection rowSelection = ((QueryParameters)Parameters[i]).RowSelection;
				firstRows[i] = rowSelection.FirstRow;
				maxRows[i] = rowSelection.MaxRows;
			}

			MultipleQueriesCacheAssembler assembler = new MultipleQueriesCacheAssembler(resultTypesList);

			QueryKey key = new QueryKey(session.Factory, SqlString, combinedParameters, filterKeys)
				.SetFirstRows(firstRows)
				.SetMaxRows(maxRows);

			IList result =
				assembler.GetResultFromQueryCache(session,
										combinedParameters,
										querySpaces,
										queryCache,
										key);

			if (result == null)
			{
				log.Debug("Cache miss for multi query");
				ArrayList list = DoList();
				queryCache.Put(key, new ICacheAssembler[] { assembler }, new object[] { list }, session);
				result = list;
			}

			return GetResultList(result);
		}
        private IList<UnitaImmobiliare> getUnitaByConto(ContiModelloRegistrazioneContabile dettaglioModello)
        {
            Iesi.Collections.Generic.ISet<UnitaImmobiliare> listaUnita = new HashedSet<UnitaImmobiliare>();
            if (dettaglioModello.Unita.Count > 0)
            {
                foreach (var dettaglioRiparto in dettaglioModello.Unita)
                {
                    if (dettaglioRiparto.LottoRiferimento != null)
                        listaUnita.AddAll(dettaglioRiparto.LottoRiferimento.GetUnitaImmobiliari());
                    else if (dettaglioRiparto.PalazzinaRiferimento != null)
                        listaUnita.AddAll(dettaglioRiparto.PalazzinaRiferimento.GetUnitaImmobiliari());
                    else if (dettaglioRiparto.GruppoStabileRiferimento != null)
                        listaUnita.AddAll(dettaglioRiparto.GruppoStabileRiferimento.UnitaImmobiliari);
                    else if (dettaglioRiparto.UnitaRiferimento != null)
                        listaUnita.Add(dettaglioRiparto.UnitaRiferimento);
                    else
                        listaUnita.AddAll(dettaglioModello.Modello.CondominioRiferimento.GetUnitaImmobiliari());
                }
            }
            else
                listaUnita.AddAll(dettaglioModello.Modello.CondominioRiferimento.GetUnitaImmobiliari());

            return listaUnita.ToList();
        }
Example #52
0
			public List<InterpretationStep> Execute(ReportingProcedureStep step, Staff executingStaff, Staff assignStaff, IWorkflow workflow)
			{
				step.Discontinue();

				// cancel the report part if exists
				if (step.ReportPart != null)
					step.ReportPart.Cancel();

				var interpretationSteps = new List<InterpretationStep>();
				if (!IsAddendumStep(step))
				{
					var procedures = new HashedSet<Procedure> { step.Procedure };

					// if there are linked procedures, schedule a new interpretation for each procedure being reported
					if (step.ReportPart != null)
					{
						procedures.AddAll(step.ReportPart.Report.Procedures);
					}

					// schedule new interpretations
					foreach (var procedure in procedures)
					{
						var interpretationStep = new InterpretationStep(procedure);

						// Bug: #5128 - if the procedure is not document, do not schedule the replacement interpretation step,
						// since interpretation steps aren't scheduled until documentation is complete.
						if (procedure.IsDocumented)
							interpretationStep.Schedule(procedure.PerformedTime);

						if (assignStaff != null)
							interpretationStep.Assign(assignStaff);

						interpretationSteps.Add(interpretationStep);
						workflow.AddEntity(interpretationStep);
					}
				}
				return interpretationSteps;
			}