public override void SaveOperation(object sender, RoutedEventArgs e)
        {
            //validations on each row
            foreach (var row in FPTemplateRows)
            {
                //sl no should be unique
                var duplicateRow = FPTemplateRows.FirstOrDefault(p => p.SlNo == row.SlNo && p != row);
                if (duplicateRow != null)
                {
                    MessageBox.Show("Sl no " + row.SlNo + " has been repeated twice, Correct this before saving");
                    return;
                }

                //Location + segment uniqueness validation validation
                var conflictingRow = FPTemplateRows.FirstOrDefault(p => p.SlNo != row.SlNo && p.Location == row.Location && p.Segment == row.Segment);
                if (conflictingRow != null)
                {
                    MessageBox.Show("Rows with Sl No " + row.SlNo + " and " + conflictingRow.SlNo + " have the same location and segments. Correct this before saving");
                    return;
                }
            }

            base.SaveOperation(sender, e);
            //update the energy grid
            UpdateEnergyWiseArea();
        }
Esempio n. 2
0
        private Entity FindBasePrice(EntityCollection basePrices, Entity productEntity)
        {
            int precision = GetPricePrecision(productEntity);
            var price     = GetPrice(productEntity, precision);

            return(basePrices.FirstOrDefault(p => GetPrice(p, precision) == price));
        }
        // TODO: Move to own repository?
        private long GetMedicalVendorUserEventTestLockId(long physicianId, long eventCustomerResultId, bool isActive)
        {
            var medicalVendorUserEventTestLockEntities = new EntityCollection <EventCustomerEvaluationLockEntity>();

            IRelationPredicateBucket bucket = new RelationPredicateBucket(
                EventCustomerEvaluationLockFields.PhysicianId == physicianId);

            bucket.PredicateExpression.Add(EventCustomerEvaluationLockFields.EventCustomerId == eventCustomerResultId);
            //bucket.PredicateExpression.Add(EventCustomerEvaluationLockFields.IsActive == isActive);

            using (var myAdapter = PersistenceLayer.GetDataAccessAdapter())
            {
                myAdapter.FetchEntityCollection(medicalVendorUserEventTestLockEntities, bucket);
            }

            try
            {
                return(medicalVendorUserEventTestLockEntities.FirstOrDefault().PhysicianId);
            }
            catch (NullReferenceException)
            {
                throw new ArgumentException(string.Format
                                                ("No UserEventTestLock exists for the given PhysicianId {0} and EventCustomerResultId {1}.",
                                                physicianId, eventCustomerResultId));
            }
        }
Esempio n. 4
0
        public virtual async Task <TournamentEntity> GetTournamentEntityForMatchPlannerAsync(long tournamentId, CancellationToken cancellationToken)
        {
            var bucket = new RelationPredicateBucket(TournamentFields.Id == tournamentId);

            bucket.Relations.Add(TournamentEntity.Relations.RoundEntityUsingTournamentId);
            bucket.Relations.Add(RoundEntity.Relations.TeamInRoundEntityUsingRoundId);
            bucket.Relations.Add(TeamInRoundEntity.Relations.TeamEntityUsingTeamId);
            bucket.Relations.Add(TeamEntity.Relations.VenueEntityUsingVenueId);

            var prefetchPathTournament = new PrefetchPath2(EntityType.TournamentEntity);

            prefetchPathTournament.Add(TournamentEntity.PrefetchPathRounds);
            prefetchPathTournament[0].SubPath.Add(RoundEntity.PrefetchPathRoundLegs);
            prefetchPathTournament[0].SubPath.Add(RoundEntity.PrefetchPathTeamCollectionViaTeamInRound).SubPath
            .Add(TeamEntity.PrefetchPathVenue);

            var t = new EntityCollection <TournamentEntity>();

            using var da = _dbContext.GetNewAdapter();
            var qp = new QueryParameters(0, 0, 0, bucket)
            {
                CollectionToFetch = t,
                PrefetchPathToUse = prefetchPathTournament
            };
            await da.FetchEntityCollectionAsync(qp, cancellationToken);

            return(t.FirstOrDefault());
        }
Esempio n. 5
0
        /// <summary>
        /// Remove First Where
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="coll"></param>
        /// <param name="funct"></param>
        public static void RemoveWhere <T>(this EntityCollection <T> coll, Func <T, bool> funct)
            where T : class
        {
            var t = coll.FirstOrDefault(funct);

            if (t != null)
            {
                coll.Remove(t);
            }
        }
        /// <summary>
        /// Recalculates all scores of current partnership obligation parameters.
        /// </summary>
        /// <param name="partnershipId"><see cref="Guid"/> Id of partnership.</param>
        public void RecalculateAllScore(Guid partnershipId)
        {
            var obligationsEsq = new EntitySchemaQuery(_userConnection.EntitySchemaManager, "PartnershipParameter");

            obligationsEsq.Filters.Add(
                obligationsEsq.CreateFilterWithParameters(FilterComparisonType.Equal, "Partnership", partnershipId));
            obligationsEsq.Filters.Add(
                obligationsEsq.CreateFilterWithParameters(FilterComparisonType.Equal, "ParameterType",
                                                          PRMBaseConstants.ObligationParameterTypeId));
            obligationsEsq.PrimaryQueryColumn.IsAlwaysSelect = true;
            obligationsEsq.AddColumn("PartnershipParameterType");
            obligationsEsq.AddColumn("IntValue");
            obligationsEsq.AddColumn("FloatValue");
            obligationsEsq.AddColumn("PartnerParamCategory");
            obligationsEsq.AddColumn("Score");
            obligationsEsq.UseAdminRights = false;
            EntityCollection obligationsCollection = obligationsEsq.GetEntityCollection(_userConnection);

            foreach (var target in obligationsCollection)
            {
                if (target.GetTypedColumnValue <Guid>("PartnershipParameterTypeId") == PRMBaseConstants.TargetPartnershipParamTypeId)
                {
                    string targetScoreColumnName = target.GetTypedColumnValue <int>("IntValue") != 0
                                                ? "IntValue"
                                                : "FloatValue";
                    var targetValue = target.GetTypedColumnValue <double>(targetScoreColumnName);
                    if (targetValue > 0)
                    {
                        Entity currentParameter =
                            obligationsCollection.FirstOrDefault(
                                x => x.GetTypedColumnValue <Guid>("PartnershipParameterTypeId") == PRMBaseConstants.CurrentPartnershipParamTypeId &&
                                x.GetTypedColumnValue <Guid>("PartnerParamCategoryId") == target.GetTypedColumnValue <Guid>("PartnerParamCategoryId"));
                        if (currentParameter == null)
                        {
                            return;
                        }
                        var targetScore  = target.GetTypedColumnValue <double>("Score");
                        var currentValue = currentParameter.GetTypedColumnValue <double>(targetScoreColumnName);
                        var currentScore = Convert.ToInt32(currentValue >= targetValue ? targetScore : Math.Round((targetScore / targetValue) * currentValue));

                        var currentParameterId = currentParameter.GetTypedColumnValue <Guid>("Id");
                        var update             = new Update(_userConnection, "PartnershipParameter")
                                                 .Set("Score", Column.Parameter(currentScore))
                                                 .Where("Id").IsEqual(Column.Parameter(currentParameterId))
                                                 .Execute();
                    }
                }
            }
        }
Esempio n. 7
0
        public static void DeleteHelper(EntityCollection <TEntity> entityCollection)
        {
            if (entityCollection != null && entityCollection.Any())
            {
                using (var context = (entityCollection.FirstOrDefault() as ERP_Core.BaseEntityObject).GetContext() as TObjectContext)
                {
                    DeleteHelper(context, entityCollection);
                }
                //Int32 count = entityCollection.Count();
                //for (int i = 0; i < count; i++)
                //{
                //    Object entity = entityCollection.Skip(0).Take(1).Single();

                //    context.DeleteObject(entity);
                //}
            }
        }
Esempio n. 8
0
        public Entity FindEntity(string entitySchemaName, Dictionary <string, object> conditions,
                                 Dictionary <string, OrderDirection> orderByColumns)
        {
            var esq = new EntitySchemaQuery(_userConnection.EntitySchemaManager, entitySchemaName);

            esq.AddAllSchemaColumns();
            foreach (KeyValuePair <string, object> condition in conditions)
            {
                IEntitySchemaQueryFilterItem columnFilter = esq.CreateFilterWithParameters(FilterComparisonType.Equal,
                                                                                           condition.Key, condition.Value);
                esq.Filters.Add(columnFilter);
            }
            foreach (KeyValuePair <string, OrderDirection> orderByColumn in orderByColumns)
            {
                EntitySchemaQueryColumn column = esq.Columns.GetByName(orderByColumn.Key);
                column.OrderDirection = orderByColumn.Value;
            }
            EntityCollection entities = esq.GetEntityCollection(_userConnection);

            return(entities.FirstOrDefault());
        }
Esempio n. 9
0
        private void LoadEntities()
        {
            var bucket = new RelationPredicateBucket(TournamentFields.Id == _tournament.Id);

            bucket.Relations.Add(TournamentEntity.Relations.RoundEntityUsingTournamentId);
            bucket.Relations.Add(RoundEntity.Relations.TeamInRoundEntityUsingRoundId);
            bucket.Relations.Add(TeamInRoundEntity.Relations.TeamEntityUsingTeamId);
            bucket.Relations.Add(TeamEntity.Relations.VenueEntityUsingVenueId);

            var prefetchPathTournament = new PrefetchPath2(EntityType.TournamentEntity);

            prefetchPathTournament.Add(TournamentEntity.PrefetchPathRounds);
            prefetchPathTournament[1].SubPath.Add(RoundEntity.PrefetchPathRoundLegs);
            prefetchPathTournament[1].SubPath.Add(RoundEntity.PrefetchPathTeamCollectionViaTeamInRound).SubPath.Add(TeamEntity.PrefetchPathVenue);

            var t = new EntityCollection <TournamentEntity>();

            _appDb.DbContext.GetNewAdapter().FetchEntityCollection(t, bucket, prefetchPathTournament);
            _tournament = t.FirstOrDefault();

            _entitiesLoaded = true;
        }
Esempio n. 10
0
        /// <summary>
        /// Searches for the city entity.
        /// </summary>
        /// <param name="cityNames">The variants of the city name.</param>
        /// <returns>The found city entity or <c>null</c>.</returns>
        /// <remarks>Tries to identify the city name language and searches for this language's culture.</remarks>
        public Entity SearchForCity(IEnumerable <string> cityNames)
        {
            if (cityNames.IsNullOrEmpty())
            {
                return(null);
            }
            var esq = new EntitySchemaQuery(_citySchema)
            {
                RowCount            = 1,
                Cache               = _userConnection.ApplicationCache,
                IgnoreDisplayValues = true
            };
            string primaryDisplayColumnName = _citySchema.PrimaryDisplayColumn.Name;

            esq.AddColumn(_citySchema.PrimaryDisplayColumn.Name);
            esq.PrimaryQueryColumn.IsVisible = true;
            SetCityQueryCulture(cityNames, esq);
            esq.Filters.Add(
                esq.CreateFilterWithParameters(FilterComparisonType.Equal, primaryDisplayColumnName, cityNames));
            EntityCollection entities = esq.GetEntityCollection(_userConnection);

            return(entities.FirstOrDefault());
        }
Esempio n. 11
0
        /// <summary>
        /// Searches for the country entity.
        /// </summary>
        /// <param name="code">The code of the country.</param>
        /// <remarks>Uses alpha3 code of the country.</remarks>
        /// <returns>The found country entity or <c>null</c>.</returns>
        public Entity SearchForCountry(string code)
        {
            if (code.IsNullOrEmpty())
            {
                return(null);
            }
            string cacheItemName =
                string.Format("EmailMining_LocationHelper_SearchForCountry_{0}_{1}", code, _userCultureId);
            var esq = new EntitySchemaQuery(_countrySchema)
            {
                RowCount            = 1,
                Cache               = _userConnection.ApplicationCache,
                CacheItemName       = cacheItemName,
                IgnoreDisplayValues = true
            };

            esq.AddColumn(_countrySchema.PrimaryDisplayColumn.Name);
            esq.PrimaryQueryColumn.IsVisible = true;
            esq.Filters.Add(esq.CreateFilterWithParameters(FilterComparisonType.Equal, "Code", code));
            EntityCollection entities = esq.GetEntityCollection(_userConnection);

            return(entities.FirstOrDefault());
        }
Esempio n. 12
0
        /// <summary>
        /// Merge collection of entities into golden entity.
        /// </summary>
        /// <param name="schemaName">Schema name.</param>
        /// <param name="groupId">Identifier of the group of search results.</param>
        /// <param name="goldenRecordId">Golden entity record identifier.</param>
        /// <param name="duplicateRecordIds">Collection of entity unique identifiers.</param>
        /// <param name="resolvedConflicts">Config for resolving conflicts.</param>
        public virtual void MergeEntityDublicates(string schemaName, int groupId, List <Guid> duplicateRecordIds, Dictionary <string, string> resolvedConflicts)
        {
            EntitySchema     entitySchema = UserConnection.EntitySchemaManager.GetInstanceByName(schemaName);
            EntityCollection duplicates   = GetEntityDublicates(schemaName, duplicateRecordIds);
            Entity           goldenEntity = duplicates.FirstOrDefault();

            if (goldenEntity == null)
            {
                return;
            }
            duplicates.RemoveFirst();
            duplicateRecordIds.Remove(goldenEntity.PrimaryColumnValue);
            if (duplicates.Count == 0)
            {
                return;
            }
            Dictionary <string, string>         detailMergeRules = GetDetailMergeRules(schemaName);
            Dictionary <string, List <string> > referencedTables = GetReferencedTablesInfo(schemaName);
            var entitySchemaOpposites = GetEntitySchemaOpposites(entitySchema.UId);

            using (DBExecutor dbExecutor = UserConnection.EnsureDBConnection()) {
                dbExecutor.CommandTimeout = 3600;
                dbExecutor.StartTransaction();
                foreach (var table in referencedTables)
                {
                    string tableName = table.Key;
                    _log.Info($"schemaName: ${schemaName}, ref. tableName: ${tableName}, ref. columns: ${string.Join(", ", table.Value)}");
                    Guid goldRecordId = goldenEntity.PrimaryColumnValue;
                    try {
                        if (detailMergeRules.ContainsKey(tableName))
                        {
                            string mergeRule = detailMergeRules[tableName];
                            MergeDetailRecordsByRule(mergeRule, tableName, goldRecordId, duplicateRecordIds,
                                                     dbExecutor, entitySchemaOpposites);
                        }
                        else
                        {
                            UpdateReferencedRecords(tableName, table.Value, goldRecordId, duplicateRecordIds,
                                                    dbExecutor);
                        }
                    } catch {
                        dbExecutor.RollbackTransaction();
                        throw;
                    }
                }
                try {
                    MergeDuplicatesWithGoldRecord(goldenEntity, duplicates, resolvedConflicts);
                    DeleteMasterRecords(schemaName, duplicateRecordIds, dbExecutor);
                    SendDataToExternalServices(entitySchema, duplicateRecordIds);
                    goldenEntity.Save();
                } catch {
                    dbExecutor.RollbackTransaction();
                    RevertSearchResultGroupToPositive(schemaName, groupId);
                    throw;
                }
                dbExecutor.CommitTransaction();
            }
            DeleteSearchResultGroup(schemaName, groupId);
            DeleteMergedEntitiesFromSearchResult(schemaName, duplicateRecordIds);
            PerformAfterDeduplicationActions(goldenEntity);
            if (UserConnection.GetIsFeatureEnabled("UseDuplicatesHistory"))
            {
                LogMergeDuplicatesRecords(schemaName, duplicateRecordIds, goldenEntity.PrimaryColumnValue);
            }
        }
Esempio n. 13
0
        /// <summary>
        ///  Validates duplicate entities.
        /// </summary>
        /// <param name="schemaName">Schema name.</param>
        /// <param name="duplicateRecordIds">Collection of identifiers of duplicate entities.</param>
        /// <param name="resolvedConflicts">Config for resolving conflicts.</param>
        /// <returns>Validation result.</returns>
        public ValidateDuplicatesResponse ValidateDuplicates(string schemaName, List <Guid> duplicateRecordIds,
                                                             Dictionary <string, string> resolvedConflicts)
        {
            ValidateDuplicatesResponse response = new ValidateDuplicatesResponse();
            EntitySchema     entitySchema       = UserConnection.EntitySchemaManager.GetInstanceByName(schemaName);
            EntityCollection entityCollection   = GetEntityDublicates(schemaName, duplicateRecordIds);
            Entity           goldenEntity       = entityCollection.FirstOrDefault();

            if (goldenEntity == null)
            {
                return(response);
            }
            entityCollection.RemoveFirst();
            List <string> resolvedColumns = new List <string>();

            if (resolvedConflicts != null)
            {
                resolvedColumns = resolvedConflicts.Keys.ToList();
            }
            List <string> conflictColumns = new List <string>();

            foreach (EntitySchemaColumn column in goldenEntity.Schema.Columns)
            {
                if (IsColumnInIgnoreList(column.Name))
                {
                    continue;
                }
                if (GetIsSystemColumn(entitySchema, column))
                {
                    continue;
                }
                if (resolvedColumns.Contains(column.Name))
                {
                    continue;
                }
                bool isConflictColumn = false;
                EntityColumnValue goldenColumnValue = goldenEntity.FindEntityColumnValue(column.ColumnValueName);
                foreach (Entity entity in entityCollection)
                {
                    EntityColumnValue columnValue = entity.FindEntityColumnValue(column.ColumnValueName);
                    if (DataTypeUtilities.ValueIsNullOrEmpty(goldenColumnValue.Value))
                    {
                        goldenColumnValue = columnValue;
                        continue;
                    }
                    if (DataTypeUtilities.ValueIsNullOrEmpty(columnValue.Value))
                    {
                        continue;
                    }
                    if (IsEquals(goldenColumnValue.Value, columnValue.Value) == false)
                    {
                        isConflictColumn = true;
                        break;
                    }
                }
                if (isConflictColumn)
                {
                    conflictColumns.Add(column.Name);
                }
            }
            if (conflictColumns.Any())
            {
                conflictColumns.AddRange(resolvedColumns);
                EntityCollection              conflicts         = GetEntityDublicates(schemaName, duplicateRecordIds, conflictColumns);
                Dictionary <string, string>   columnMap         = GetQueryColumns(conflicts.Schema.Columns);
                DataContract.EntityCollection convertedEntities =
                    QueryExtension.GetEntityCollection(conflicts, columnMap);
                response.Conflicts = convertedEntities;
            }
            return(response);
        }
Esempio n. 14
0
        private Entity FindBaseUnit(EntityCollection baseUnits, Entity productEntity)
        {
            var productUnitId = productEntity.GetTypedColumnValue <Guid>("UnitId");

            return(baseUnits.FirstOrDefault(u => u.GetTypedColumnValue <Guid>("UnitId").Equals(productUnitId)));
        }
Esempio n. 15
0
 public T this[byte slot]
 {
     get { return(_items.FirstOrDefault(item => item.Slot == slot)); }
 }
Esempio n. 16
0
 public TEntity GetById(int id)
 {
     return(EntityCollection
            .FirstOrDefault(x => x.Id == id));
 }