Пример #1
0
        protected BindedEntityQuery TemplateQueryBuild(EntityMetadata entityMetadata, InternalQueryRequest queryParameter, QueryCacheKey.QueryMode queryMode)
        {
            string queryString;
            var    before = Stopwatch.StartNew();
            var    compositeWhereBuilder = GetCompositeBuilder(entityMetadata, queryParameter);
            var    cacheKey = GetCacheKey(queryParameter, queryMode);

            if (!entityMetadata.QueryStringCache.TryGetValue(cacheKey, out queryString) || !queryParameter.Cacheable())
            {
                queryString = DoBuildQueryString(entityMetadata, queryParameter, queryMode, compositeWhereBuilder,
                                                 cacheKey);
            }
            else
            {
                //where clauses should always be rebuild independent of cache, due to context variation, like modules, profiles, etc...
                var whereBuilder    = SimpleInjectorGenericFactory.Instance.GetObject <DataConstraintsWhereBuilder>(typeof(DataConstraintsWhereBuilder));
                var whereConstraint = whereBuilder.BuildWhereClause(entityMetadata.Name, queryMode, queryParameter.SearchDTO);
                queryString = String.Format(queryString, whereConstraint);
            }
            if (entityMetadata.HasUnion())
            {
                return(HandleUnion(entityMetadata as SlicedEntityMetadata, queryParameter, queryString, queryMode, compositeWhereBuilder.GetParameters()));
            }

            Log.Debug(LoggingUtil.BaseDurationMessageFormat(before, "query for {0}:{1} built", entityMetadata.Name, queryMode.ToString()));

            return(new BindedEntityQuery(queryString, compositeWhereBuilder.GetParameters()));
        }
Пример #2
0
        public int CountByNativeQuery(String queryst, ExpandoObject parameters, string queryAlias = null)
        {
            var before = Stopwatch.StartNew();

            using (var session = GetSessionManager().OpenSession()) {
                var query  = BuildQuery(queryst, parameters, session, true, null, queryAlias);
                var result = (int)query.UniqueResult();
                LogPaginationQuery(queryst, queryAlias, before, parameters);
                GetLog().Debug(LoggingUtil.BaseDurationMessageFormat(before, "{0}: done count query".Fmt(queryAlias ?? "")));
                return(result);
            }
        }
Пример #3
0
        public IList <dynamic> FindByNativeQuery(String queryst, ExpandoObject parameters, PaginationData paginationData = null, string queryAlias = null)
        {
            var before = Stopwatch.StartNew();

            using (var session = GetSessionManager().OpenSession()) {
                var query = BuildQuery(queryst, parameters, session, true, paginationData, queryAlias);
                query.SetResultTransformer(NhTransformers.ExpandoObject);
                var result = query.List <dynamic>();
                LogPaginationQuery(queryst, queryAlias, before, parameters);
                GetLog().Debug(LoggingUtil.BaseDurationMessageFormat(before, "{0}: done query".Fmt(queryAlias ?? "")));
                return(result);
            }
        }
Пример #4
0
        protected void DoExecute()
        {
            LogicalThreadContext.SetData("user", "swjobuser");
            var before = Stopwatch.StartNew();

            try {
                Log.InfoFormat("Starting execution of {0}", Name());
                ExecuteJob();
            } catch (Exception e) {
                Log.Error(String.Format("error executing job {0} ", Name()), e);
            } finally {
                Log.Info(LoggingUtil.BaseDurationMessageFormat(before, "Finished execution of {0}", Name()));
                LogicalThreadContext.SetData("user", null);
            }
        }
Пример #5
0
        public Dictionary <string, EntityRepository.SearchEntityResult> ResolveCollections(SlicedEntityMetadata entityMetadata, IDictionary <string, ApplicationCompositionSchema> compositionSchemas,
                                                                                           IReadOnlyList <AttributeHolder> entitiesList, PaginatedSearchRequestDto paginatedSearch = null)
        {
            if (!compositionSchemas.Any())
            {
                return(new Dictionary <string, EntityRepository.SearchEntityResult>());
            }
            var before = Stopwatch.StartNew();

            _log.DebugFormat("Init Collection Resolving for {0} Collections", String.Join(",", compositionSchemas.Keys));

            var collectionAssociations = new List <EntityAssociation>();

            foreach (var entityListAssociation in entityMetadata.ListAssociations())
            {
                if (compositionSchemas.Keys.Contains(entityListAssociation.Qualifier))
                {
                    collectionAssociations.Add(entityListAssociation);
                }
            }

            var results = new Dictionary <string, EntityRepository.SearchEntityResult>();

            var tasks = new Task[collectionAssociations.Count];
            var i     = 0;
            var ctx   = ContextLookuper.LookupContext();

            foreach (var collectionAssociation in collectionAssociations)
            {
                var association              = collectionAssociation;
                var shouldPaginate           = ShouldPaginate(compositionSchemas[association.Qualifier], paginatedSearch) && paginatedSearch != null;
                var perThreadPaginatedSearch = shouldPaginate ? (PaginatedSearchRequestDto)paginatedSearch.ShallowCopy() : null;
                //this will avoid that one thread impacts any other
                var perThreadContext = ctx.ShallowCopy();
                tasks[i++] = Task.Factory.NewThread(() => FetchAsync(entityMetadata, association, compositionSchemas, entitiesList, perThreadContext, results, perThreadPaginatedSearch));
            }
            Task.WaitAll(tasks);
            _log.Debug(LoggingUtil.BaseDurationMessageFormat(before, "Finish Collection Resolving for {0} Collections",
                                                             String.Join(",", compositionSchemas.Keys)));


            return(results);
        }
Пример #6
0
        public FileContentResult Export(string application, [FromUri] ApplicationMetadataSchemaKey key,
                                        [FromUri] PaginatedSearchRequestDto searchDTO, string module)
        {
            searchDTO.PageSize = searchDTO.TotalCount + 1;
            if (module != null)
            {
                _contextLookuper.LookupContext().Module = module;
            }


            var before  = Stopwatch.StartNew();
            var before2 = Stopwatch.StartNew();

            var user = SecurityFacade.CurrentUser();
            var applicationMetadata = MetadataProvider
                                      .Application(application)
                                      .ApplyPolicies(key, user, ClientPlatform.Web);


            var dataResponse = _dataController.Get(application, new DataRequestAdapter {
                Key       = key,
                SearchDTO = searchDTO
            });

            Log.Debug(LoggingUtil.BaseDurationMessageFormat(before, "finished gathering export excel data"));
            var excelBytes = _excelUtil.ConvertGridToExcel(user, applicationMetadata.Schema, ((ApplicationListResult)dataResponse).ResultObject);

            Log.Info(LoggingUtil.BaseDurationMessageFormat(before2, "finished export excel data"));
            var fileName = GetFileName(application, key.SchemaId) + ".xls";
            var result   = new FileContentResult(excelBytes, System.Net.Mime.MediaTypeNames.Application.Octet)
            {
                FileDownloadName = (string)StringUtil.FirstLetterToUpper(fileName)
            };

            return(result);
        }
Пример #7
0
        protected virtual IDictionary <string, BaseAssociationUpdateResult> DoUpdateAssociation(ApplicationMetadata application, AssociationUpdateRequest request,
                                                                                                AttributeHolder cruddata)
        {
            var before = LoggingUtil.StartMeasuring(Log, "starting update association options fetching for application {0} schema {1}", application.Name, application.Schema.Name);
            IDictionary <string, BaseAssociationUpdateResult> resultObject =
                new Dictionary <string, BaseAssociationUpdateResult>();
            ISet <string> associationsToUpdate = null;

            // Check if 'self' (for lazy load) or 'dependant' (for dependant combos) association update
            if (!String.IsNullOrWhiteSpace(request.AssociationFieldName))
            {
                associationsToUpdate = new HashSet <String> {
                    request.AssociationFieldName
                };
            }
            else if (!String.IsNullOrWhiteSpace(request.TriggerFieldName))
            {
                var triggerFieldName = request.TriggerFieldName;
                if (!application.Schema.DependantFields.TryGetValue(triggerFieldName, out associationsToUpdate))
                {
                    throw new InvalidOperationException();
                }
            }

            if (associationsToUpdate == null)
            {
                return(resultObject);
            }

            var tasks = new List <Task>();
            var ctx   = ContextLookuper.LookupContext();

            //there might be some associations/optionfields to be updated after the first value is selected
            foreach (var associationToUpdate in associationsToUpdate)
            {
                var association = application.Schema.Associations.FirstOrDefault(f => (
                                                                                     EntityUtil.IsRelationshipNameEquals(f.AssociationKey, associationToUpdate)));
                if (association == null)
                {
                    var optionField = application.Schema.OptionFields.First(f => f.AssociationKey == associationToUpdate);
                    tasks.Add(Task.Factory.NewThread(c => {
                        Quartz.Util.LogicalThreadContext.SetData("context", c);
                        var data = _dynamicOptionFieldResolver.ResolveOptions(application, optionField, cruddata);
                        resultObject.Add(optionField.AssociationKey, new LookupAssociationUpdateResult(data, 100, PaginatedSearchRequestDto.DefaultPaginationOptions));
                    }, ctx));
                }
                else
                {
                    var associationApplicationMetadata =
                        ApplicationAssociationResolver.GetAssociationApplicationMetadata(association);

                    var searchRequest = BuildSearchDTO(request, association, cruddata);

                    if (searchRequest == null)
                    {
                        //this would only happen if association is lazy and there´s no default value
                        //(cause we´d need to fetch one-value list for displaying)
                        continue;
                    }
                    var threadSafeContext = new ContextHolderWithSearchDto(ctx, searchRequest);
                    tasks.Add(Task.Factory.NewThread(c => {
                        Quartz.Util.LogicalThreadContext.SetData("context", threadSafeContext.Context);
                        var options = _associationOptionResolver.ResolveOptions(application, cruddata, association,
                                                                                threadSafeContext.Dto);

                        resultObject.Add(association.AssociationKey,
                                         new LookupAssociationUpdateResult(searchRequest.TotalCount, searchRequest.PageNumber,
                                                                           searchRequest.PageSize, options, associationApplicationMetadata, PaginatedSearchRequestDto.DefaultPaginationOptions));
                    }, threadSafeContext));
                }
            }

            Task.WaitAll(tasks.ToArray());

            if (Log.IsDebugEnabled)
            {
                var keys = String.Join(",", resultObject.Keys.Where(k => resultObject[k].AssociationData != null));
                Log.Debug(LoggingUtil.BaseDurationMessageFormat(before,
                                                                "Finished execution of options fetching. Resolved collections: {0}", keys));
            }
            return(resultObject);
        }
Пример #8
0
        //TODO: add locale,and format options
        public IDictionary <string, BaseAssociationUpdateResult> BuildAssociationOptions(AttributeHolder dataMap, ApplicationMetadata application, IAssociationPrefetcherRequest request)
        {
            var associationsToFetch = AssociationHelper.BuildAssociationsToPrefetch(request, application.Schema);

            if (associationsToFetch.IsNone)
            {
                return(new Dictionary <string, BaseAssociationUpdateResult>());
            }


            IDictionary <string, BaseAssociationUpdateResult> associationOptionsDictionary = new ConcurrentDictionary <string, BaseAssociationUpdateResult>();
            var before = LoggingUtil.StartMeasuring(Log, "starting association options fetching for application {0} schema {1}", application.Name, application.Schema.Name);

            var associations = application.Schema.Associations;
            var tasks        = new List <Task>();
            var ctx          = ContextLookuper.LookupContext();

            #region associations

            foreach (var applicationAssociation in associations)
            {
                if (!associationsToFetch.ShouldResolve(applicationAssociation.AssociationKey))
                {
                    Log.Debug("ignoring association fetching: {0}".Fmt(applicationAssociation.AssociationKey));
                    continue;
                }

                //only resolve the association options for non lazy associations or lazy loaded with value set.
                SearchRequestDto search;
                if (!applicationAssociation.IsLazyLoaded())
                {
                    search = new SearchRequestDto();
                }
                else if (dataMap != null && dataMap.GetAttribute(applicationAssociation.Target) != null)
                {
                    //if the field has a value, fetch only this single element, for showing eventual extra label fields... ==> lookup with a selected value
                    search = new SearchRequestDto();
                    var toAttribute    = applicationAssociation.EntityAssociation.PrimaryAttribute().To;
                    var prefilledValue = dataMap.GetAttribute(applicationAssociation.Target).ToString();
                    search.AppendSearchEntry(toAttribute, prefilledValue);
                }
                else
                {
                    //lazy association with no default value
                    continue;
                }
                var association = applicationAssociation;

                tasks.Add(Task.Factory.NewThread(c => {
                    //this will avoid that one thread impacts any other, for ex: changing metadataid of the query
                    var perThreadContext = ctx.ShallowCopy();
                    Quartz.Util.LogicalThreadContext.SetData("context", perThreadContext);
                    var associationOptions = _associationOptionResolver.ResolveOptions(application, dataMap, association, search);
                    associationOptionsDictionary.Add(association.AssociationKey, new BaseAssociationUpdateResult(associationOptions));
                }, ctx));
            }
            #endregion

            #region optionfields
            foreach (var optionField in application.Schema.OptionFields)
            {
                if (!associationsToFetch.ShouldResolve(optionField.AssociationKey))
                {
                    Log.Debug("ignoring association fetching: {0}".Fmt(optionField.AssociationKey));
                    continue;
                }

                if (optionField.ProviderAttribute == null)
                {
                    //if there´s no provider, there´s nothing to do --> static list
                    continue;
                }
                var field = optionField;
                tasks.Add(Task.Factory.NewThread(c => {
                    Quartz.Util.LogicalThreadContext.SetData("context", c);
                    var associationOptions = _dynamicOptionFieldResolver.ResolveOptions(application, field, dataMap);
                    if (associationOptionsDictionary.ContainsKey(field.AssociationKey))
                    {
                        associationOptionsDictionary.Remove(field.AssociationKey);
                    }
                    associationOptionsDictionary.Add(field.AssociationKey, new BaseAssociationUpdateResult(associationOptions));
                }, ctx));
            }
            #endregion

            Task.WaitAll(tasks.ToArray());
            if (Log.IsDebugEnabled)
            {
                var keys = String.Join(",", associationOptionsDictionary.Keys.Where(k => associationOptionsDictionary[k].AssociationData != null));
                Log.Debug(LoggingUtil.BaseDurationMessageFormat(before, "Finished execution of options fetching. Resolved collections: {0}", keys));
            }


            return(associationOptionsDictionary);
        }