Пример #1
0
        /// <summary>
        /// Localizar os nomes de arquivos que conferem com o filtro indicado.
        /// </summary>
        /// <param name="pathFilter">
        /// Filtro para pesquisa de arquivos.
        ///
        /// São suportados os caracteres curinga:
        /// *, para indicar um trecho de nome, **, para indicar qualquer quantidade
        /// de pastas no caminho, e ?, para indicar um único caracter na posição.
        ///
        /// Por exemplo: O filtro "\Path\*.txt" retorna todos os arquivos TXT dentro da
        /// pasta "Path". O filtro "\Path\**\*.txt" retorna todos os arquivos TXT dentro
        /// da pasta "Path" ou em qualquer outra pasta na hierarquia de "Path".
        /// </param>
        /// <returns>
        /// O status da pesquisa mais os arquivos lidos.
        /// Em geral 200-OK com a lista dos arquivos lidos ou 404-NotFound com uma
        /// lista vazia caso nada seja encontrado.
        /// </returns>
        public Ret <string[]> FindResources(string pathFilter)
        {
            try
            {
                pathFilter = pathFilter.Replace(@"/", @"\");

                if (!pathFilter.StartsWith(@"\"))
                {
                    pathFilter = $@"\**\{pathFilter}";
                }

                var pattern = pathFilter
                              .Replace(@".", @"[.]")
                              .Replace(@"**", @"§")
                              .Replace(@"*", @"[^\]*")
                              .Replace(@"\§", @"(|\.*)")
                              .Replace(@"?", @".")
                              .Replace(@"\", @"\\")
                ;

                var regex = new Regex($"^{pattern}$", RegexOptions.IgnoreCase);

                var files = (
                    from path in ResourcePaths
                    where regex.IsMatch(path)
                    select path
                    ).ToArray();

                return(files.Length > 0 ? Ret.OK(files) : Ret.NotFound(files));
            }
            catch (Exception ex)
            {
                return(Ret.FailWithValue(ex, new string[0]));
            }
        }
Пример #2
0
        /// <summary>
        /// Copia o arquivo embarcado para o fluxo de saída.
        /// </summary>
        /// <param name="resourcePath">
        /// O caminho do recurso procurado, com pastas separadas por contra-barra (\).
        /// Exemplo: "\My\Folder\MyFile.txt"
        /// </param>
        /// <param name="writer">Fluxo para escrita do arquivo embarcado.</param>
        /// <returns>
        /// O status de leitura do arquivo.
        /// Em geral 200-OK caso o arquivo seja lido com sucesso
        /// ou 404-NotFound caso o arquivo não exista embarcado.
        /// </returns>
        public Ret LoadResource(string resourcePath, TextWriter writer)
        {
            try
            {
                string realPath;

                realPath = resourcePath.Replace(@"/", @"\");
                realPath = ResourcePaths.FirstOrDefault(x => x.EqualsIgnoreCase(realPath));

                if (realPath == null)
                {
                    return(Ret.NotFound());
                }

                var assembly = typeof(ResourceLoader).Assembly;
                using (var input = assembly.GetManifestResourceStream(realPath))
                {
                    var reader = new StreamReader(input);
                    reader.CopyTo(writer);
                }

                return(Ret.OK());
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Пример #3
0
 public Ret Delete(Bulk <Group> groups)
 {
     foreach (var group in groups)
     {
         Db.Groups.RemoveAll(x => x.Id == group.Id);
     }
     return(Ret.OK());
 }
Пример #4
0
 public Ret Delete(Bulk <User> users)
 {
     foreach (var user in users)
     {
         Db.Users.RemoveAll(x => x.Id == user.Id);
     }
     return(Ret.OK());
 }
Пример #5
0
 public static Ret <Entity> CreateFromRet(UriString route, Ret ret)
 {
     if (ret.Value is Entity entity)
     {
         return(Ret.OK(entity));
     }
     else
     {
         return(Create(route, ret.Status.Code, ret.Fault.Message, ret.Fault.Exception));
     }
 }
Пример #6
0
        /// <summary>
        /// Retorna o conteúdo do arquivo binário embarcado.
        /// </summary>
        /// <param name="resourcePath">
        /// O caminho do recurso procurado, com pastas separadas por contra-barra (\).
        /// Exemplo: "\My\Folder\MyFile.txt"
        /// </param>
        /// <returns>
        /// O status de leitura do arquivo mais o seu conteúdo.
        /// Em geral 200-OK mais o conteúdo caso o arquivo seja lido com sucesso
        /// ou 404-NotFound caso o arquivo não exista embarcado.
        /// </returns>
        public Ret <byte[]> LoadResourceAsBinary(string resourcePath)
        {
            try
            {
                using (var memory = new MemoryStream())
                {
                    var ret = LoadResource(resourcePath, memory);
                    if (!ret.Ok)
                    {
                        return(ret);
                    }

                    var bytes = memory.ToArray();
                    return(Ret.OK(bytes));
                }
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Пример #7
0
        /// <summary>
        /// Retorna o conteúdo do arquivo texto embarcado.
        /// </summary>
        /// <param name="resourcePath">
        /// O caminho do recurso procurado, com pastas separadas por contra-barra (\).
        /// Exemplo: "\My\Folder\MyFile.txt"
        /// </param>
        /// <returns>
        /// O status de leitura do arquivo mais o seu conteúdo.
        /// Em geral 200-OK mais o conteúdo caso o arquivo seja lido com sucesso
        /// ou 404-NotFound caso o arquivo não exista embarcado.
        /// </returns>
        public Ret <string> LoadResourceAsText(string resourcePath)
        {
            try
            {
                using (var writer = new StringWriter())
                {
                    var ret = LoadResource(resourcePath, writer);
                    if (!ret.Ok)
                    {
                        return(ret);
                    }

                    var content = writer.ToString();
                    return(Ret.OK(content));
                }
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Пример #8
0
 public Ret VouMostrarIssoPraCininha(TaskForm taskForm, Task[] tasks)
 {
     return(Ret.OK());
 }
Пример #9
0
        private Ret <Result> CallPaperMethod(PaperContext context, IPaper paper, MethodInfo method, Args args, Entity form)
        {
            object result = null;

            try
            {
                var methodArgs = CreateParameters(context, paper, method, args, form);

                context.RenderContext.Sort   = methodArgs.OfType <Sort>().FirstOrDefault();
                context.RenderContext.Page   = methodArgs.OfType <Page>().FirstOrDefault();
                context.RenderContext.Filter = methodArgs.OfType <IFilter>().FirstOrDefault();

                context.RenderContext.Page?.IncreaseLimit();

                result = objectFactory.Invoke(paper, method, methodArgs);
            }
            catch (Exception ex)
            {
                result = Ret.Fail(ex);
            }

            var resultType = method.ReturnType;

            if (Is.Ret(resultType))
            {
                resultType = TypeOf.Ret(resultType);
            }

            Ret <Result> ret;

            if (result == null)
            {
                // Um método que resulta "void" é considerado OK quando não emite exceção.
                // Um método que resulta nulo é considerado NotFound (Não encontrado).
                var isVoid = method.ReturnType == typeof(void);
                if (isVoid)
                {
                    ret = Ret.OK(new Result
                    {
                        Value     = result,
                        ValueType = resultType
                    });
                }
                else
                {
                    ret = Ret.NotFound(new Result
                    {
                        Value     = result,
                        ValueType = resultType
                    });
                }
            }
            else if (Is.Ret(result))
            {
                ret        = new Ret <Result>();
                ret.Status = (RetStatus)result._Get(nameof(ret.Status));
                ret.Fault  = (RetFault)result._Get(nameof(ret.Fault));
                ret.Value  = new Result
                {
                    Value     = result._Get(nameof(ret.Value)),
                    ValueType = resultType
                };
            }
            else
            {
                ret = Ret.OK(new Result
                {
                    Value     = result,
                    ValueType = resultType
                });
            }

            return(ret);
        }