Exemplo n.º 1
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.get_Filters());
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.get_Bundles());
 }
Exemplo n.º 2
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">IServiceCollection object instance</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddControllers(opt => GlobalFilters.Configure(opt))
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    return(factory.Create(typeof(Resource)));
                };
            })
            .AddJsonOptions(opt =>
            {
                opt.JsonSerializerOptions.IgnoreNullValues = true;
                opt.JsonSerializerOptions.WriteIndented    = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == Environments.Development;
            })
            .ConfigureApiBehaviorOptions(opt => opt.SuppressModelStateInvalidFilter = true);
            services.AddApiVersioning();
            services.AddHttpContextAccessor();
            services.AddCors();
            services.AddResponseCaching();

            var assemblyName = Assembly.GetExecutingAssembly().GetName().Name;

            services.AddJwtToken(Configuration);
            services.AddSwaggerGenerator(Configuration, assemblyName);
            services.AddAuthRegister(Configuration);
            services.AddAppPolicies(Configuration);
            services.AddMiddlewareLoggingOption(Configuration);
            services.AddApplicationHealthChecks(Configuration);
            services.AddScoped <ITokenHelper, TokenHelper>();
            services.AddCultureLanguage(Configuration);
        }
Exemplo n.º 3
0
    static Task <Connection <TItem> > Last <TSource, TItem>(
        IQueryable <TItem> list,
        int last,
        int?after,
        int?before,
        int count,
        ResolveFieldContext <TSource> context,
        GlobalFilters filters,
        CancellationToken cancellation)
    {
        int skip;

        if (after == null)
        {
            // last before
            skip = before.GetValueOrDefault(count) - last;
        }
        else
        {
            // last after
            skip = after.Value + 1;
        }

        return(Range(list, skip, take: last, count, context, filters, cancellation, true));
    }
    public void Simple()
    {
        GlobalFilters.Add <Target>((o, target) => target.Property != "Ignore");
        Assert.True(GlobalFilters.ShouldInclude(null, new Target()));
        Assert.False(GlobalFilters.ShouldInclude(null, null));
        Assert.True(GlobalFilters.ShouldInclude(null, new Target {
            Property = "Include"
        }));
        Assert.False(GlobalFilters.ShouldInclude(null, new Target {
            Property = "Ignore"
        }));

        GlobalFilters.Add <BaseTarget>((o, target) => target.Property != "Ignore");
        Assert.True(GlobalFilters.ShouldInclude(null, new ChildTarget()));
        Assert.True(GlobalFilters.ShouldInclude(null, new ChildTarget {
            Property = "Include"
        }));
        Assert.False(GlobalFilters.ShouldInclude(null, new ChildTarget {
            Property = "Ignore"
        }));

        GlobalFilters.Add <ITarget>((o, target) => target.Property != "Ignore");
        Assert.True(GlobalFilters.ShouldInclude(null, new ImplementationTarget()));
        Assert.True(GlobalFilters.ShouldInclude(null, new ImplementationTarget {
            Property = "Include"
        }));
        Assert.False(GlobalFilters.ShouldInclude(null, new ImplementationTarget {
            Property = "Ignore"
        }));

        Assert.True(GlobalFilters.ShouldInclude(null, new NonTarget {
            Property = "Foo"
        }));
    }
    public static async Task <object> ExecuteQuery <TDbContext>(
        string query,
        ServiceCollection services,
        TDbContext dbContext,
        Inputs inputs,
        GlobalFilters filters)
        where TDbContext : DbContext
    {
        query = query.Replace("'", "\"");
        EfGraphQLConventions.RegisterInContainer(
            services,
            dbContext,
            userContext => (TDbContext)userContext,
            filters);
        using (var provider = services.BuildServiceProvider())
            using (var schema = new Schema(new FuncDependencyResolver(provider.GetRequiredService)))
            {
                var documentExecuter = new EfDocumentExecuter();

                #region ExecutionOptionsWithFixIdTypeRule
                var executionOptions = new ExecutionOptions
                {
                    Schema          = schema,
                    Query           = query,
                    UserContext     = dbContext,
                    Inputs          = inputs,
                    ValidationRules = FixIdTypeRule.CoreRulesWithIdFix
                };
                #endregion

                var executionResult = await documentExecuter.ExecuteWithErrorCheck(executionOptions);

                return(executionResult.Data);
            }
    }
Exemplo n.º 6
0
    static async Task <object> RunQuery(
        SqlDatabase <IntegrationDbContext> database,
        string query,
        Inputs inputs,
        GlobalFilters filters,
        params object[] entities)
    {
        using (var dbContext = database.NewDbContext())
        {
            dbContext.AddRange(entities);
            await dbContext.SaveChangesAsync();
        }

        using (var dbContext = database.NewDbContext())
        {
            var services = new ServiceCollection();

            services.AddSingleton <Query>();
            foreach (var type in GetGraphQlTypes())
            {
                services.AddSingleton(type);
            }

            return(await QueryExecutor.ExecuteQuery(query, services, dbContext, inputs, filters));
        }
    }
Exemplo n.º 7
0
        /// <summary>Gets the filter associated with the specified key from the context.</summary>
        /// <param name="key">The filter key associated to the filter.</param>
        /// <returns>The filter associated with the specified key from the context.</returns>
        public static AliasBaseQueryFilter Filter(object key)
        {
            AliasBaseQueryFilter filter;

            GlobalFilters.TryGetValue(key, out filter);

            return(filter);
        }
Exemplo n.º 8
0
    static GlobalFilters BuildFilters()
    {
        var filters = new GlobalFilters();

        filters.Add <FilterParentEntity>((context, item) => item.Property != "Ignore");
        filters.Add <FilterChildEntity>((context, item) => item.Property != "Ignore");
        return(filters);
    }
Exemplo n.º 9
0
    static IntegrationTests()
    {
        GlobalFilters.Add <FilterParentEntity>((context, item) => item.Property != "Ignore");
        GlobalFilters.Add <FilterChildEntity>((context, item) => item.Property != "Ignore");

        using (var dataContext = BuildDataContext())
        {
            dataContext.Database.EnsureCreated();
        }
    }
Exemplo n.º 10
0
        public Server()
        {
            Console.Title = "FastWebSocketServer";
            GlobalFilters.Add(new ExceptionFilterAttribute());
            this.BindService <CpuCounterService>();
            this.StartListen(8282);
            Console.WriteLine("FastWebSocketServer服务已启动,端口:" + this.LocalEndPoint.Port);

            CpuCounter.CpuTimeChanged += CpuCounter_CpuTimeChanged;
        }
Exemplo n.º 11
0
        static TemplateContext()
        {
            // Global properties
            GlobalScope.SetValue("empty", EmptyValue.Instance);

            // Initialize Global Filters
            GlobalFilters
            .WithArrayFilters()
            .WithStringFilters()
            .WithNumberFilters()
            .WithMiscFilters();
        }
Exemplo n.º 12
0
 public static Task <Connection <TItem> > ApplyConnectionContext <TSource, TItem>(this IQueryable <TItem> list,
                                                                                  int?first,
                                                                                  string afterString,
                                                                                  int?last,
                                                                                  string beforeString,
                                                                                  ResolveFieldContext <TSource> context,
                                                                                  CancellationToken cancellation,
                                                                                  GlobalFilters filters)
 {
     Parse(afterString, beforeString, out var after, out var before);
     return(ApplyConnectionContext(list, first, after, last, before, context, filters, cancellation));
 }
Exemplo n.º 13
0
        /// <summary>
        /// Configuração dos serviços
        /// </summary>
        /// <param name="services">Coleção de serviços</param>
        public void ConfigureServices(IServiceCollection services)
        {
            #region HealthCheck

            services.AddHealthChecks()
            //.AddCheck("Google Ping", new PingHealthCheck("www.google.com", 100))
            //.AddCheck("Bing Ping", new PingHealthCheck("www.bing.com", 100))
            .AddUrlGroup(
                new Uri("https://apps.correios.com.br"),
                name: "Acesso a Apps dos Correios",
                failureStatus: HealthStatus.Degraded)
            .AddMongoDb(
                mongodbConnectionString: Configuration.GetValue <string>("ConnectionStrings:MongoDb"),
                name: "MongoDB",
                failureStatus: HealthStatus.Unhealthy,
                timeout: TimeSpan.FromSeconds(15),
                tags: new string[] { "mongodb" });

            #endregion

            #region Swagger

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1",
                             new OpenApiInfo
                {
                    Title       = "OpenBrasil Endereços",
                    Version     = "v1",
                    Description = "Api de busca de Endereços (CEP & Logradouro)",
                    Contact     = new OpenApiContact
                    {
                        Name = "Rodrigo Rodrigues",
                        Url  = new Uri("https://github.com/rodriguesrm")
                    }
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            #endregion

            // Serviços de injeção da aplicação
            services.AddApplicationService(Configuration);
            services.AddMiddlewareLoggingOption(Configuration);

            services
            .AddControllers(opt => GlobalFilters.Configure(opt))
            .ConfigureApiBehaviorOptions(opt => opt.SuppressModelStateInvalidFilter = true);
        }
Exemplo n.º 14
0
        static TemplateContext()
        {
            // Global properties
            GlobalScope.SetValue("empty", NilValue.Empty);
            GlobalScope.SetValue("blank", new StringValue(""));

            // Initialize Global Filters
            GlobalFilters
            .WithArrayFilters()
            .WithStringFilters()
            .WithNumberFilters()
            .WithMiscFilters();
        }
    public void Add(ServiceCollection services, IModel model)
    {
        #region add-filter

        var filters = new GlobalFilters();
        filters.Add <MyEntity>(
            (userContext, item) =>
        {
            return(item.Property != "Ignore");
        });
        EfGraphQLConventions.RegisterInContainer(services, model, filters);

        #endregion
    }
        /// <summary>
        ///     Creates and return a filter associated with the specified key added for the context.
        /// </summary>
        /// <typeparam name="T">The type of elements of the query.</typeparam>
        /// <param name="key">The filter key associated to the filter.</param>
        /// <param name="queryFilter">The query filter to apply to the the context.</param>
        /// <param name="isEnabled">true if the filter is enabled.</param>
        /// <returns>The filter created and added to the the context.</returns>
        public static BaseQueryFilter Filter <T>(object key, Func <IQueryable <T>, IQueryable <T> > queryFilter, bool isEnabled = true)
        {
            BaseQueryFilter filter;

            if (!GlobalFilters.TryGetValue(key, out filter))
            {
                filter = new QueryFilter <T>(null, queryFilter)
                {
                    IsDefaultEnabled = isEnabled
                };
                GlobalFilters.Add(key, filter);
            }

            return(filter);
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            Console.Title = "LuceneServer";

            GlobalFilters.Add(new ExceptionFilter());
            var server = new LnServer();

            server.BindService <LnService>().BindService <SystemService>();
            server.StartListen(int.Parse(ConfigurationManager.AppSettings["Port"]));

            Console.WriteLine("服务监听中:端口" + server.LocalEndPoint.Port);
            while (true)
            {
                Console.ReadLine();
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">Service collection</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services
            .AddControllersWithViews()
            .AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

            services.AddApplicationSwagger();
            services.AddApplicationService(Configuration);
            services.AddApplicationHealthChecks(Configuration);
            services.AddMiddlewareLoggingOption(Configuration);

            services
            .AddControllers(opt => GlobalFilters.Configure(opt))
            .ConfigureApiBehaviorOptions(opt => opt.SuppressModelStateInvalidFilter = true);
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            GlobalFilters.Add(new ExceptionFilterAttribute());

            var fastServer = new FastServer();

            fastServer.Serializer = new FastJsonSerializer();
            fastServer.BindService(fastServer.GetType().Assembly);
            fastServer.RegisterResolver();
            fastServer.StartListen(1350);

            Console.Title = "FastServer V" + new SystemService().GetVersion();
            Console.WriteLine("服务已启动,端口:" + fastServer.LocalEndPoint.Port);
            while (true)
            {
                Console.ReadLine();
            }
        }
    static async Task <Connection <TReturn> > Range <TSource, TReturn>(
        IQueryable <TReturn> list,
        int skip,
        int take, int count,
        ResolveFieldContext <TSource> context,
        CancellationToken cancellation,
        bool reverse = false)
    {
        var page = list.Skip(skip).Take(take);

        IEnumerable <TReturn> result = await page
                                       .ToListAsync(cancellation)
                                       .ConfigureAwait(false);

        result = result.Where(item => GlobalFilters.ShouldInclude(context.UserContext, item));

        cancellation.ThrowIfCancellationRequested();
        return(Build(skip, take, count, reverse, result));
    }
Exemplo n.º 21
0
    public static async Task <Connection <TItem> > ApplyConnectionContext <TSource, TItem>(
        IQueryable <TItem> list,
        int?first,
        int?after,
        int?last,
        int?before,
        ResolveFieldContext <TSource> context,
        GlobalFilters filters,
        CancellationToken cancellation)
    {
        var count = await list.CountAsync(cancellation);

        cancellation.ThrowIfCancellationRequested();
        if (last == null)
        {
            return(await First(list, first.GetValueOrDefault(0), after, before, count, context, filters, cancellation));
        }

        return(await Last(list, last.Value, after, before, count, context, filters, cancellation));
    }
Exemplo n.º 22
0
    static async Task <Connection <TItem> > Range <TSource, TItem>(
        IQueryable <TItem> list,
        int skip,
        int take, int count,
        ResolveFieldContext <TSource> context,
        GlobalFilters filters,
        CancellationToken cancellation,
        bool reverse = false)
    {
        var page = list.Skip(skip).Take(take);

        if (reverse)
        {
            page = page.Reverse();
        }
        IEnumerable <TItem> result = await page.ToListAsync(cancellation);

        result = await filters.ApplyFilter(result, context.UserContext);

        cancellation.ThrowIfCancellationRequested();
        return(Build(skip, take, count, result));
    }
Exemplo n.º 23
0
        /// <summary>
        ///     Creates and return a filter associated with the specified key added for the context.
        /// </summary>
        /// <typeparam name="T">The type of elements of the query.</typeparam>
        /// <param name="key">The filter key associated to the filter.</param>
        /// <param name="queryFilter">The query filter to apply to the the context.</param>
        /// <param name="isEnabled">true if the filter is enabled.</param>
        /// <returns>The filter created and added to the the context.</returns>
        public static AliasBaseQueryFilter Filter <T>(object key, Func <IQueryable <T>, IQueryable <T> > queryFilter, bool isEnabled = true)
        {
            AliasBaseQueryFilter filter;

            if (!GlobalFilters.TryGetValue(key, out filter))
            {
#if EF6
                filter = new QueryDbSetFilter <T>(null, queryFilter)
                {
                    IsDefaultEnabled = isEnabled
                };
#else
                filter = new QueryFilter <T>(null, queryFilter)
                {
                    IsDefaultEnabled = isEnabled
                };
#endif
                GlobalFilters.Add(key, filter);
            }

            return(filter);
        }
Exemplo n.º 24
0
    static Task <Connection <TItem> > First <TSource, TItem>(
        IQueryable <TItem> list,
        int first,
        int?after,
        int?before,
        int count,
        ResolveFieldContext <TSource> context,
        GlobalFilters filters,
        CancellationToken cancellation)
    {
        int skip;

        if (before == null)
        {
            skip = after + 1 ?? 0;
        }
        else
        {
            skip = Math.Max(before.Value - first, 0);
        }

        return(Range(list, skip, first, count, context, filters, cancellation));
    }
    public async Task Simple()
    {
        var filters = new GlobalFilters();

        filters.Add <Target>((o, target) => target.Property != "Ignore");
        Assert.True(await filters.ShouldInclude(null, new Target()));
        Assert.False(await filters.ShouldInclude <object>(null, null));
        Assert.True(await filters.ShouldInclude(null, new Target {
            Property = "Include"
        }));
        Assert.False(await filters.ShouldInclude(null, new Target {
            Property = "Ignore"
        }));

        filters.Add <BaseTarget>((o, target) => target.Property != "Ignore");
        Assert.True(await filters.ShouldInclude(null, new ChildTarget()));
        Assert.True(await filters.ShouldInclude(null, new ChildTarget {
            Property = "Include"
        }));
        Assert.False(await filters.ShouldInclude(null, new ChildTarget {
            Property = "Ignore"
        }));

        filters.Add <ITarget>((o, target) => target.Property != "Ignore");
        Assert.True(await filters.ShouldInclude(null, new ImplementationTarget()));
        Assert.True(await filters.ShouldInclude(null, new ImplementationTarget {
            Property = "Include"
        }));
        Assert.False(await filters.ShouldInclude(null, new ImplementationTarget {
            Property = "Ignore"
        }));

        Assert.True(await filters.ShouldInclude(null, new NonTarget {
            Property = "Foo"
        }));
    }
Exemplo n.º 26
0
        /// <summary>
        /// Asigna los procesos (relaciones de filtro) involucrados en cada entidad.
        /// Esto permite asignar en la metadata que elementos filtran a otros.
        /// y que elementos son filtrados por otros.
        /// </summary>
        /// <param name="asm">Assembly del modelo</param>
        /// <param name="gfc">filtros globales del modelo</param>
        /// <param name="entity">metadata de la entidad</param>
        /// <param name="docProcess">Documentación de los filtros</param>
        /// <returns></returns>
        private static EntityMetadata GetEntityWithProcess(Assembly asm, GlobalFilters gfc, EntityMetadata entity, DocFilter[] docProcess)
        {
            // obtiene los tipos de tipo modelo (las relaciones de filtro solo se encuentran en el modelo).
            var mdlTypes = Common.GetTypeModel(asm);



            if (!docProcess.Any())
            {
                throw new CustomException("No existe documentación de filtros");
            }


            // desde la documentación encontrada, usa los índices para encontrar los filtros en todo el modelo.
            var filterProcess = docProcess.SelectMany(dp => ToProcess.GetFilterProcess(mdlTypes, dp.Index, false, gfc));

            // si no existen filtros, retorna la metadata sin modificar.
            if (!filterProcess.Any())
            {
                // no existen procesos en el modelo.
                return(entity);
            }


            // obtiene los filtros, que tengan como origen la entidad.
            var filterProcessForEntity = filterProcess.Where(s => s.SourceIndex == entity.Index);

            // si existen filtros que tengan la entidad como origen.
            if (filterProcessForEntity.Any())
            {
                // busca documentación para el filtro.
                var docFiltersAvailableForEntity = docProcess.Where(s => filterProcessForEntity.Any(a => a.SourceIndex == entity.Index));

                // documentación de filtros de la entidad.
                if (docFiltersAvailableForEntity.Any())
                {
                    // asigna a la entidad, la documentación de filtros encontrados.
                    entity.DocFilters = docFiltersAvailableForEntity.ToArray();

                    // obtiene los procesos para la entidad.
                    var targetProcesForEntity = filterProcessForEntity.Where(s => s.SourceIndex == entity.Index);

                    // ToProcessFilter indica que entidades esta entidad puede filtrar.
                    if (targetProcesForEntity.Any())
                    {
                        entity.ToProcessFilter = targetProcesForEntity.ToArray();
                    }
                }
            }


            // se encuentan procesos que apunten a esta entidad.
            var filterAvailableForEntity = filterProcess.Where(s => s.TargetRealIndex == entity.Index).ToList();


            // si existe un filtro global en el modelo.
            if (gfc != null)
            {
                // obtiene la colección de rutas del filtro global (índice 0).
                var globalTarget = ToProcess.GetFilterProcess(mdlTypes, 0, true, null);
                // procesos de índice 0 (filtro global).
                var docFiltersAvailableToEntity = docProcess.Where(s => s.Index == 0);

                // el IndexEntityForGlobalFilters determina una entidad en común por filtro global.
                // por ejemplo, para el modelo agricola, es barrack, debido a que
                // los filtros globales filtran barrack y barrack filtra el resto.
                // esta condición se cumplirá solo si el filtro global apunta a la entidad actual.
                if (gfc.IndexEntityForGlobalFilters == entity.Index)
                {
                    // obtiene el listado de elementos que filtra la entidad
                    var lst = entity.FiltersAvailable?.ToList() ?? new List <RelatedItem>();

                    // todos las entidades que pertenecen al globalFilter, filtran o apuntan
                    // directa o indirectamente a una entidad principal.
                    // se asignan como filtros
                    lst.AddRange(globalTarget.Where(s => s.TargetRealIndex == entity.Index).Select(s => new RelatedItem
                    {
                        PathToEntity = s,
                        ClassName    = s.SourceName,
                        docFilter    = docFiltersAvailableToEntity.First(a => a.Index == s.Index),
                        Index        = s.Index
                    }));

                    entity.FiltersAvailable = lst.ToArray();

                    // se quitan los procesos del filtro global que apunten a la entidad principal
                    filterAvailableForEntity = filterAvailableForEntity.Where(s => !(s.TargetRealIndex == entity.Index && s.Index == 0)).ToList();
                }
            }


            // si existen filtros que apunten a la entidad
            if (filterAvailableForEntity.Any())
            {
                // documentos que tangan los índices de los filtros que apuntan a la entidad.
                var docFiltersAvailableToEntity = docProcess.Where(s => filterAvailableForEntity.Any(a => s.Index == a.Index)).ToList();

                if (!docFiltersAvailableToEntity.Any())
                {
                    throw new Exception($"no existe documentación para uno de los siguentes indices {string.Join(",", filterAvailableForEntity.Select(s => s.Index).Distinct().ToArray())}");
                }

                var lst = entity.FiltersAvailable?.ToList() ?? new List <RelatedItem>();

                // asigna todas las entidades que filtran la entidad.
                lst.AddRange(filterAvailableForEntity.Select(s => new RelatedItem
                {
                    PathToEntity = s,
                    ClassName    = s.SourceName,
                    docFilter    = docFiltersAvailableToEntity.First(a => a.Index == s.Index),
                    Index        = s.Index
                }));
                entity.FiltersAvailable = lst.ToArray();
            }

            // entidad con los procesos (filtros).
            return(entity);
        }
Exemplo n.º 27
0
        public static List <WorklistTicket> GetTickets(ApiUser hdUser, Guid OrgId, int DeptId, int UserId, string status, string role, string Class, string account, string location, string project, bool IsTechAdmin, bool IsUseWorkDaysTimer, string sort_order, string sort_by, string search = "", int page = 0, int limit = 25, DateTime?start_date = null, DateTime?end_date = null)
        {
            string tkts = "";

            if (!string.IsNullOrWhiteSpace(search) && Micajah.Common.Configuration.FrameworkConfiguration.Current.WebApplication.Integration.Azure.Search.Enabled)
            {
                tkts = bigWebApps.bigWebDesk.Data.Tickets.SearchTicketsInAzure(hdUser.OrganizationId, hdUser.DepartmentId, false, search);

                /*if (string.IsNullOrEmpty(tkts))
                 * {
                 *  return new List<WorklistTicket>();
                 * //tkts = "0";
                 * }
                 */
            }
            Worklist.QueryFilter _qFilter = new Worklist.QueryFilter();
            if (string.IsNullOrEmpty(role) || role.ToLower() == "all")
            {
                role = "notset";
            }
            if (!string.IsNullOrEmpty(status))
            {
                string originalstatus = status;
                status = status.Replace(",", "").Replace("_", "").ToLowerInvariant();
                Worklist.TicketStatusMode ticketStatusMode;
                if (Enum.TryParse <Worklist.TicketStatusMode>(status, true, out ticketStatusMode))
                {
                    _qFilter.TicketStatus = ticketStatusMode;
                }
                else
                {
                    if (originalstatus.Contains(","))
                    {
                        string statuses     = originalstatus.Replace("_", "").ToLowerInvariant();
                        string status_query = string.Empty;
                        foreach (string _status in statuses.Split(','))
                        {
                            switch (_status.ToLower())
                            {
                            case "closed":
                                status_query += " OR tkt.status='Closed' ";
                                break;

                            case "open":
                                status_query += " OR tkt.status='Open' ";
                                break;

                            case "onhold":
                                status_query += " OR tkt.status='On Hold' ";
                                break;

                            case "partsonorder":
                                status_query += " OR tkt.status='Parts On Order' ";
                                break;

                            case "waiting":
                                status_query += " OR (tkt.status='Open' AND tkt.WaitingDate is not null) ";
                                break;
                            }
                        }

                        if (!string.IsNullOrEmpty(status_query))
                        {
                            _qFilter.SQLWhere = " AND (" + status_query.Substring(3) + ")";
                        }
                    }
                    else
                    {
                        switch (status)
                        {
                        case "waiting": _qFilter.TicketStatus = Worklist.TicketStatusMode.OpenWaitingOnResponse;
                            break;

                        case "newmessages":
                            switch (role)
                            {
                            case "tech": _qFilter.ShowNewMessages = Worklist.NewMessagesMode.User; break;

                            case "user": _qFilter.ShowNewMessages = Worklist.NewMessagesMode.Technician; break;

                            default: _qFilter.ShowNewMessages = Worklist.NewMessagesMode.UserAndTech; break;
                            }
                            ;
                            break;

                        case "closed": _qFilter.TicketStatus = Worklist.TicketStatusMode.Close;
                            break;
                        }
                    }
                }
            }

            Worklist.SortMode ticketSortMode;
            if (Enum.TryParse <Worklist.SortMode>(role, true, out ticketSortMode))
            {
                _qFilter.Sort = ticketSortMode;
            }
            else
            {
                switch (role)
                {
                case "tech": _qFilter.Sort = Worklist.SortMode.MyTickets; break;

                case "user": _qFilter.Sort = Worklist.SortMode.MyTicketsAsUser; break;

                case "alt_tech": _qFilter.Sort = Worklist.SortMode.MyTicketsAsAlternateTech; break;
                }
            }
            int queueId;

            if (int.TryParse(Class, out queueId))
            {
                _qFilter.TechnicianId = queueId;
                Class = "";
            }
            if (!string.IsNullOrEmpty(Class))
            {
                int class_id = 0;
                if (int.TryParse(Class, out class_id))
                {
                    if (class_id > 0)
                    {
                        _qFilter.SQLWhere += " AND tkt.class_id = " + class_id;
                    }
                }
                else
                {
                    _qFilter.SQLWhere += " AND dbo.fxGetFullClassName(" + DeptId.ToString() + ", tkt.class_id) like '%" + Class + "%'";
                }
            }
            if (!string.IsNullOrEmpty(account))
            {
                int account_id = 0;
                if (int.TryParse(account, out account_id))
                {
                    if (account_id != 0)
                    {
                        _qFilter.AccountId = account_id;
                    }
                }
                else
                {
                    _qFilter.SQLWhere += " AND (ISNULL(acct.vchName, CASE WHEN ISNULL(tkt.btNoAccount, 0) = 0 THEN co.company_name ELSE '' END) like '%" + account + "%')";
                }
            }
            if (!string.IsNullOrEmpty(project))
            {
                int project_id = 0;
                if (int.TryParse(project, out project_id))
                {
                    if (project_id != 0)
                    {
                        _qFilter.ProjectID = project_id;
                    }
                }
                else
                {
                    _qFilter.SQLWhere += " AND dbo.fxGetFullProjectName(" + DeptId.ToString() + ", tkt.ProjectID) like '%" + project + "%'";
                }
            }
            if (!string.IsNullOrEmpty(location))
            {
                int location_id = 0;
                if (int.TryParse(location, out location_id))
                {
                    if (location_id != 0)
                    {
                        _qFilter.AccountLocationId = location_id;
                    }
                }
                else
                {
                    _qFilter.SQLWhere += " AND dbo.fxGetUserLocationName(" + DeptId.ToString() + ", tkt.LocationId) like '%" + location + "%'";
                }
            }

            if (start_date.HasValue)
            {
                if (start_date.Value.TimeOfDay.TotalSeconds > 0)
                {
                    start_date = start_date.Value.Date;
                }
                _qFilter.SQLWhere += string.Format(" AND tkt.CreateTime >= '{0}'", start_date.Value.ToString("yyyy-MM-dd hh:mm:ss"));
            }
            if (end_date.HasValue)
            {
                if (end_date.Value.TimeOfDay.TotalSeconds == 0)
                {
                    end_date = end_date.Value.Date.AddDays(1).AddSeconds(-1);
                }
                _qFilter.SQLWhere += string.Format(" AND tkt.CreateTime <= '{0}'", end_date.Value.ToString("yyyy-MM-dd hh:mm:ss"));
            }

            Instance_Config config = new Instance_Config(hdUser);

            if (!string.IsNullOrWhiteSpace(search))
            {
                string _query = "";
                if (!string.IsNullOrEmpty(tkts))
                {
                    _query += " AND (tkt.Id IN (" + tkts + ")";
                }
                else
                {
                    _query           += " AND (tkt.subject LIKE '%" + search + "%' OR ISNULL(tlip2.CountFoundInitPost, 0) > 0 OR tkt.note LIKE '%" + search + "%' OR ISNULL(tlcn2.CountFoundClosureNotes, 0) > 0";
                    _qFilter.SQLJoin += " LEFT OUTER JOIN (SELECT TId, COUNT(*) AS CountFoundInitPost FROM TicketLogs WHERE DId=" + hdUser.DepartmentId + " AND vchType = 'Initial Post' AND vchNote LIKE '%" + search + "%' GROUP BY TId) tlip2 ON tlip2.TId = tkt.Id "
                                        + "LEFT OUTER JOIN (SELECT TId, COUNT(*) AS CountFoundClosureNotes FROM TicketLogs WHERE DId=" + hdUser.DepartmentId + " AND vchType = 'Closed' AND vchNote LIKE '%" + search + "%' GROUP BY TId) tlcn2 ON tlcn2.TId = tkt.Id ";
                }

                if (config.SerialNumber)
                {
                    _query += " OR tkt.SerialNumber LIKE '%" + search + "%'";
                }
                _query            += ")";
                _qFilter.SQLWhere += _query;
            }

            limit = limit <= 0 ? 25 : limit;
            page  = page < 0 ? 0 : page;
            string pager = string.Format(" OFFSET ({0} * {1}) ROWS FETCH NEXT {1} ROWS ONLY ", page, limit);

            _qFilter.PageIndex = page;

            if (sort_by != "days_old")
            {
                _qFilter.SortColumnIndex    = 0;
                _qFilter.IsSortColumnDesc   = "desc" == sort_order;
                _qFilter.SortColumnSQLAlias = sort_by ?? "CreateTime";
            }


            bigWebApps.bigWebDesk.UserAuth userAuth = new bigWebApps.bigWebDesk.UserAuth
            {
                Role            = hdUser.Role,
                OrgID           = hdUser.OrganizationId,
                lngDId          = hdUser.DepartmentId,
                tintTicketTimer = hdUser.tintTicketTimer,
                lngUId          = hdUser.UserId,
                InstanceID      = hdUser.InstanceId
                                  //ee.strGSUserRootLocationId
                                  //ee.sintGSUserType
            };
            //Use global filters
            bool useGlobalFilters       = hdUser.Role != bigWebApps.bigWebDesk.UserAuth.UserRole.Administrator && (role == "notset" || role == "tech");
            bool limitToAssignedTickets = (useGlobalFilters) ? GlobalFilters.IsFilterEnabled(hdUser.OrganizationId, hdUser.DepartmentId, UserId, GlobalFilters.FilterState.LimitToAssignedTickets) : false;

            if (limitToAssignedTickets)
            {
                _qFilter.SQLWhere += " AND tkt.technician_id=" + UserId.ToString();
                _qFilter.SQLJoin  += " LEFT OUTER JOIN TicketAssignment AS TA2 ON TA2.DepartmentId=" + hdUser.DepartmentId + " AND TA2.TicketId = tkt.Id AND TA2.UserId = " + UserId + " AND TA2.AssignmentType = " + ((int)Ticket.TicketAssignmentType.Technician).ToString() + " AND TA2.IsPrimary = 0 AND TA2.StopDate IS NULL";
            }

            //Use global filters
            if (useGlobalFilters)
            {
                _qFilter.SQLWhere += GlobalFilters.GlobalFiltersSqlWhere(userAuth, config, "tkt.", "tlj2.", "SupGroupID", null);
            }
            //(limitToAssignedTickets ? "TA2." : null

            //bigWebApps.bigWebDesk.Data.Worklist.Filter m_Filter = new bigWebApps.bigWebDesk.Data.Worklist.Filter(tt.DepartmentId, tt.UserId, true, tt.OrganizationId);
            //bool shortMode = true;
            //Worklist.ColumnsSetting m_ColSet = shortMode ? new Worklist.ColumnsSetting("0,2", tt.DepartmentId, tt.UserId, config.AccountManager && config.LocationTracking, tt.OrganizationId) :
            //    new Worklist.ColumnsSetting(tt.DepartmentId, tt.UserId, config.AccountManager && config.LocationTracking, tt.OrganizationId);
            //if sherpadesk
            //DataTable dt = Worklist.SelectTicketsByFilter(ee, config, m_ColSet, m_Filter, _qFilter, false, FilesSources.AzureFileService, limit);

            DataTable dt = Worklist.SelectTicketsByFilter(OrgId, DeptId, UserId, _qFilter, IsTechAdmin, pager);

            if (dt != null)
            {
                //var config = new Instance_Config()
                dt.Columns.Add(new DataColumn("DaysOldSort", typeof(long)));
                dt.Columns.Add(new DataColumn("DaysOlds", typeof(string)));
                foreach (DataRow dr in dt.Rows)
                {
                    int min = Utils.GetDaysOldInMinutes(OrgId, DeptId, IsUseWorkDaysTimer, dr.GetString("Status"), dr.Get <DateTime>("CreateTime"), dr.Get <DateTime?>("ClosedTime") ?? DateTime.UtcNow);
                    dr["DaysOldSort"] = min;
                    dr["DaysOlds"]    = bigWebApps.bigWebDesk.Functions.DisplayDateDuration(min, config.BusinessDayLength, true);
                }
            }
            IEnumerable <WorklistTicket> wrklisttickets = new WorklistTickets(dt);

            return(wrklisttickets.ToList());
        }
    static async Task <object> RunQuery(string query, Inputs inputs, bool throwForClientEval, GlobalFilters filters, params object[] entities)
    {
        Purge();

        using (var dbContext = BuildDbContext(throwForClientEval))
        {
            dbContext.AddRange(entities);
            dbContext.SaveChanges();
        }

        using (var dbContext = BuildDbContext(throwForClientEval))
        {
            var services = new ServiceCollection();

            services.AddSingleton <Query>();
            foreach (var type in GetGraphQlTypes())
            {
                services.AddSingleton(type);
            }

            return(await QueryExecutor.ExecuteQuery(query, services, dbContext, inputs, filters));
        }
    }
    public static async Task <object> ExecuteQuery(string query, ServiceCollection services, DbContext dbContext, Inputs inputs, GlobalFilters filters)
    {
        query = query.Replace("'", "\"");
        EfGraphQLConventions.RegisterInContainer(services, dbContext.Model, filters);
        using (var provider = services.BuildServiceProvider())
            using (var schema = new Schema(new FuncDependencyResolver(provider.GetRequiredService)))
            {
                var documentExecuter = new EfDocumentExecuter();

                var executionOptions = new ExecutionOptions
                {
                    Schema      = schema,
                    Query       = query,
                    UserContext = dbContext,
                    Inputs      = inputs
                };

                var executionResult = await documentExecuter.ExecuteWithErrorCheck(executionOptions);

                return(executionResult.Data);
            }
    }
Exemplo n.º 30
0
 /// <summary>
 /// Adds the global async filters.
 /// </summary>
 /// <param name="filters">The filters.</param>
 /// <returns>Instance of this options</returns>
 public LiteApiOptions AddGlobalFilters(IEnumerable <IApiFilterAsync> filters)
 {
     GlobalFilters.AddRange(filters.Select(x => new ApiFilterWrapper(x)));
     return(this);
 }