示例#1
0
        public async Task <bool> DeleteFileAsync(MethodOptions methodOptions, StorageOptions storageOptions, string filePath)
        {
            EndpointOptions endpoint = FindWriteEndpoint(methodOptions, storageOptions);

            if (!endpoint.Provider.IsFullPath)
            {
                filePath = Path.Combine(endpoint.Path ?? "", filePath);
                string fileName = Path.GetFileName(filePath);
                Log.Information("Command: Remove file {file}", filePath);
                IBlobStorage storage   = _storageProvider.GetStorage(endpoint.Provider, filePath.Replace(fileName, ""));
                bool         fileExist = await storage.ExistsAsync(fileName);

                if (!fileExist)
                {
                    return(false);
                }
                await storage.DeleteAsync(fileName);
            }
            else
            {
                IBlobStorage storage = _storageProvider.GetStorage(endpoint.Provider);
                Log.Information("Command: Remove file {file}", filePath);
                bool fileExist = await storage.ExistsAsync(filePath);

                if (!fileExist)
                {
                    return(false);
                }
                await storage.DeleteAsync(filePath);
            }

            return(true);
        }
示例#2
0
        public ClassComposer AddMethod(MethodOptions options)
        {
            if (!IsAtRoot())
            {
                throw new Exception("A class must be selected (which is also a root to the composer) to add a method to it.");
            }

            TypeSyntax returnType = SyntaxFactory.ParseTypeName(options.ReturnType);
            var        method     = SyntaxFactory.MethodDeclaration(returnType, options.MethodName).WithModifiers(options.ModifiersToTokenList());

            var @params = SyntaxFactory.ParameterList();

            foreach (var param in options.Parameters)
            {
                var type        = SyntaxFactory.IdentifierName(param.Type);
                var name        = SyntaxFactory.Identifier(param.Name);
                var paramSyntax = SyntaxFactory
                                  .Parameter(new SyntaxList <AttributeListSyntax>(), SyntaxFactory.TokenList(), type, name, null);
                @params = @params.AddParameters(paramSyntax);
            }
            @params = @params.NormalizeWhitespace();
            method  = method.WithParameterList(@params);

            method = method.WithBody(SyntaxFactory.Block());

            var newNode = (CurrentNode as ClassDeclarationSyntax).AddMembers(method);

            Replace(CurrentNode, newNode, null);

            return(this);
        }
示例#3
0
        public async Task <Stream> DownloadFileAsync(MethodOptions methodOptions, StorageOptions storageOptions, string filePath)
        {
            EndpointOptions endpoint = FindReadEndpoint(methodOptions, storageOptions);

            if (!endpoint.Provider.IsFullPath)
            {
                filePath = Path.Combine(endpoint.Path ?? "", filePath);
                Log.Information("Query: Download file {file}", filePath);
                string       fileName  = Path.GetFileName(filePath);
                IBlobStorage storage   = _storageProvider.GetStorage(endpoint.Provider, filePath.Replace(fileName, ""));
                bool         fileExist = await storage.ExistsAsync(fileName);

                if (!fileExist)
                {
                    return(null);
                }
                return(await storage.OpenReadAsync(fileName));
            }
            else
            {
                Log.Information("Query: Download file {file}", filePath);
                IBlobStorage storage   = _storageProvider.GetStorage(endpoint.Provider);
                bool         fileExist = await storage.ExistsAsync(filePath);

                if (!fileExist)
                {
                    return(null);
                }
                return(await storage.OpenReadAsync(filePath));
            }
        }
示例#4
0
        public async Task AddFileAsync(MethodOptions methodOptions, StorageOptions storageOptions, IFormFileCollection files, string subPath)
        {
            ICollection <EndpointOptions> endpoints = GetWriteEndpoints(methodOptions, storageOptions).ToList();

            foreach (var file in files)
            {
                if (string.IsNullOrEmpty(file.FileName))
                {
                    Log.Warning("Attempt to upload a file with a null or empty name");
                    continue;
                }
                try
                {
                    foreach (EndpointOptions endpoint in endpoints)
                    {
                        IBlobStorage storage = _storageProvider.GetStorage(endpoint.Provider);
                        using (var fs = file.OpenReadStream())
                        {
                            await storage.WriteAsync(file.FileName, fs);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, ex.Message);
                }
            }
        }
示例#5
0
 internal HttpContextServerCallContext(HttpContext httpContext, MethodOptions options, Type requestType, Type responseType, ILogger logger)
 {
     HttpContext  = httpContext;
     Options      = options;
     RequestType  = requestType;
     ResponseType = responseType;
     Logger       = logger;
 }
 public JsonTranscodingServerCallContext(HttpContext httpContext, MethodOptions options, IMethod method, CallHandlerDescriptorInfo descriptorInfo, ILogger logger)
 {
     HttpContext    = httpContext;
     Options        = options;
     _method        = method;
     DescriptorInfo = descriptorInfo;
     Logger         = logger;
 }
示例#7
0
 /// <summary>
 /// Creates a new instance of <see cref="ServerMethodInvokerBase{TService, TRequest, TResponse}"/>.
 /// </summary>
 /// <param name="method">The description of the gRPC method.</param>
 /// <param name="options">The options used to execute the method.</param>
 /// <param name="serviceActivator">The service activator used to create service instances.</param>
 private protected ServerMethodInvokerBase(
     Method <TRequest, TResponse> method,
     MethodOptions options,
     IGrpcServiceActivator <TService> serviceActivator)
 {
     Method           = method;
     Options          = options;
     ServiceActivator = serviceActivator;
 }
示例#8
0
文件: Data.cs 项目: STXUIFRI/Chat
 public Data(int health, string name, int age, MethodOptions method = MethodOptions.POST, ErrorOptions error = ErrorOptions.ERROR_NONE, ResponseOptions response = ResponseOptions.OK)
 {
     this.Health   = health;
     this.Name     = name;
     this.Method   = method;
     this.Age      = age;
     this.Error    = error;
     this.Response = response;
     this.List     = new[] { "", "" };
 }
示例#9
0
        public async Task <ICollection <FileMetadatas> > ListFilesAsync(MethodOptions methodOptions, StorageOptions storageOptions, ListOptions listOptions = null)
        {
            ICollection <EndpointOptions> endpoints = GetReadEndpoints(methodOptions, storageOptions).ToList();

            _logger.LogInformation("List files in directories {@directory}", endpoints.Select(e => e.Path));
            IEnumerable <IBlobStorage> storages = endpoints.Select(e => _storageProvider.GetStorage(e.Provider));
            IEnumerable <Task <IReadOnlyCollection <BlobId> > > readTasks = storages.Select(x => x.ListAsync(listOptions));
            IEnumerable <BlobId> blobs = (await Task.WhenAll(readTasks)).SelectMany(x => x.Select(t => t));

            _logger.LogDebug("Listed files {@blobs}", blobs);
            return(blobs.Select(x => x.ToFileMetadata()).ToList());
        }
示例#10
0
        public HttpApiServerCallContext(HttpContext httpContext, MethodOptions options, IMethod method, CallHandlerDescriptorInfo descriptorInfo, ILogger logger)
        {
            HttpContext          = httpContext;
            Options              = options;
            _method              = method;
            DescriptorInfo       = descriptorInfo;
            Logger               = logger;
            IsJsonRequestContent = JsonRequestHelpers.HasJsonContentType(httpContext.Request, out var charset);
            RequestEncoding      = JsonRequestHelpers.GetEncodingFromCharset(charset) ?? Encoding.UTF8;

            // Add the HttpContext to UserState so GetHttpContext() continues to work
            HttpContext.Items["__HttpContext"] = httpContext;
        }
    /// <summary>
    /// Creates a new instance of <see cref="DuplexStreamingServerMethodInvoker{TService, TRequest, TResponse}"/>.
    /// </summary>
    /// <param name="invoker">The duplex streaming method to invoke.</param>
    /// <param name="method">The description of the gRPC method.</param>
    /// <param name="options">The options used to execute the method.</param>
    /// <param name="serviceActivator">The service activator used to create service instances.</param>
    public DuplexStreamingServerMethodInvoker(
        DuplexStreamingServerMethod <TService, TRequest, TResponse> invoker,
        Method <TRequest, TResponse> method,
        MethodOptions options,
        IGrpcServiceActivator <TService> serviceActivator)
        : base(method, options, serviceActivator)
    {
        _invoker = invoker;

        if (Options.HasInterceptors)
        {
            var interceptorPipeline = new InterceptorPipelineBuilder <TRequest, TResponse>(Options.Interceptors);
            _pipelineInvoker = interceptorPipeline.DuplexStreamingPipeline(ResolvedInterceptorInvoker);
        }
    }
示例#12
0
        private IEnumerable <EndpointOptions> GetWriteEndpoints(MethodOptions methodOptions, StorageOptions storageOptions)
        {
            IEnumerable <EndpointOptions> endpoints;

            if (methodOptions?.WriteEndpoints != null && storageOptions?.WriteEndpoints != null)
            {
                endpoints = methodOptions?.WriteEndpoints ?? storageOptions?.WriteEndpoints;
            }
            else
            {
                endpoints = new List <EndpointOptions> {
                    methodOptions?.WriteEndpoint ?? methodOptions?.Endpoint ?? storageOptions?.WriteEndpoint ?? storageOptions?.Endpoint
                };
            }
            return(endpoints);
        }
示例#13
0
        public async Task <ICollection <FileMetadatas> > SearchFilesAsync(MethodOptions methodOptions, StorageOptions storageOptions, string fileName)
        {
            string pattern = string.IsNullOrEmpty(methodOptions.Pattern) ? fileName : methodOptions.Pattern.Replace("{fileName}", fileName);
            ICollection <EndpointOptions> endpoints = GetReadEndpoints(methodOptions, storageOptions).ToList();

            _logger.LogInformation("Query: Search files in directory {@directory} with pattern {pattern}", endpoints.Select(e => e.Path), pattern);
            IDictionary <EndpointOptions, IBlobStorage> storages = endpoints.ToDictionary(e => e, e => _storageProvider.GetStorage(e.Provider));
            List <FileMetadatas> filesMetadatas = new List <FileMetadatas>();
            List <Task <IReadOnlyCollection <BlobId> > > storageTasks = new List <Task <IReadOnlyCollection <BlobId> > >();

            foreach (KeyValuePair <EndpointOptions, IBlobStorage> storage in storages)
            {
                if (storage.Key.Provider.StorageType == StorageType.Directory && storage.Key.IsRegex)
                {
                    IEnumerable <string> searchFiles = Directory.EnumerateFiles(storage.Key.Provider.Directory, pattern, SearchOption.AllDirectories);

                    foreach (string file in searchFiles)
                    {
                        string name           = Path.GetFileName(file);
                        string nameWithoutExt = name.Remove(name.LastIndexOf(".", StringComparison.InvariantCultureIgnoreCase));
                        string parent         = Path.GetFileName(Path.GetDirectoryName(file));
                        filesMetadatas.Add(new FileMetadatas
                        {
                            FullPath       = file,
                            Name           = name,
                            Parent         = parent,
                            NameWithoutExt = nameWithoutExt
                        });
                    }
                }
                else
                {
                    storageTasks.Add(storage.Value.ListAsync(new ListOptions {
                        Recurse = true
                    }));
                }
            }

            var taskResults = await Task.WhenAll(storageTasks);

            foreach (var taskResult in taskResults)
            {
                filesMetadatas.AddRange(taskResult.Select(x => x.ToFileMetadata()));
            }

            return(filesMetadatas);
        }
示例#14
0
        Dictionary <string, string> DumpOptions(FileDescriptorProto source, MethodOptions options)
        {
            var optionsKv = new Dictionary <string, string>();

            if (options == null)
            {
                return(optionsKv);
            }

            if (options.deprecatedSpecified)
            {
                optionsKv.Add("deprecated", options.deprecated ? "true" : "false");
            }

            DumpOptionsMatching(source, ".google.protobuf.MethodOptions", options, optionsKv);

            return(optionsKv);
        }
        public static MethodOptions CreateMethodOptions(
            List <ICompressionProvider>?compressionProviders = null,
            string?responseCompressionAlgorithm       = null,
            CompressionLevel?responseCompressionLevel = null,
            int?maxSendMessageSize             = null,
            int?maxReceiveMessageSize          = null,
            InterceptorCollection?interceptors = null)
        {
            var serviceOptions = new GrpcServiceOptions();

            serviceOptions.CompressionProviders = compressionProviders ?? new List <ICompressionProvider>();
            serviceOptions.Interceptors.AddRange(interceptors ?? new InterceptorCollection());
            serviceOptions.MaxSendMessageSize           = maxSendMessageSize;
            serviceOptions.MaxReceiveMessageSize        = maxReceiveMessageSize;
            serviceOptions.ResponseCompressionAlgorithm = responseCompressionAlgorithm;
            serviceOptions.ResponseCompressionLevel     = responseCompressionLevel;

            return(MethodOptions.Create(new[] { serviceOptions }));
        }
示例#16
0
        /// <summary>
        /// Get all of the fields of an object
        /// </summary>
        /// <param name="type"></param>
        /// <param name="options">True to include the compiler generated backing fields for auto-property getters/setters</param>
        /// <returns></returns>
        public static ICollection <ExtendedMethod> GetMethods(this Type type, MethodOptions options)
        {
            if (type == null)
            {
                return(new List <ExtendedMethod>());
            }
            var flags      = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static;
            var allMethods = type.GetMethods(flags)
                             .Select(x => new ExtendedMethod(x, type))
                             .Concat(GetMethods(type.BaseType, options));
            IEnumerable <ExtendedMethod> returnMethods = allMethods;

            if (options.HasFlag(MethodOptions.Public))
            {
                returnMethods = returnMethods.Where(x => x.IsPublic);
            }
            if (options.HasFlag(MethodOptions.Private))
            {
                returnMethods = returnMethods.Where(x => x.IsPrivate);
            }
            if (options.HasFlag(MethodOptions.Static))
            {
                returnMethods = returnMethods.Where(x => x.IsStatic);
            }
            if (options.HasFlag(MethodOptions.Overridden))
            {
                returnMethods = allMethods.Where(x => x.IsOverride);
            }
            if (options.HasFlag(MethodOptions.Virtual))
            {
                returnMethods = returnMethods.Where(x => x.IsVirtual);
            }
            if (options.HasFlag(MethodOptions.Constructor))
            {
                returnMethods = returnMethods.Where(x => x.IsConstructor);
            }
            return(returnMethods.Select(x => (ExtendedMethod)x).ToList());
        }
示例#17
0
        /// <summary>Serialize the instance into the stream</summary>
        public static void Serialize(Stream stream, MethodOptions instance)
        {
            if (instance.UninterpretedOption != null)
            {
                foreach (var i999 in instance.UninterpretedOption)
                {
                    // Key for field: 999, LengthDelimited
                    stream.Write(new byte[]{186, 62}, 0, 2);
                    using (var ms999 = new MemoryStream())
                    {
                        Google.protobuf.UninterpretedOption.Serialize(ms999, i999);
                        // Length delimited byte array
                        uint ms999Length = (uint)ms999.Length;
                        global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms999Length);
                        stream.Write(ms999.GetBuffer(), 0, (int)ms999Length);
                    }

                }
            }
        }
示例#18
0
 /// <summary>Helper: Serialize with a varint length prefix</summary>
 public static void SerializeLengthDelimited(Stream stream, MethodOptions instance)
 {
     var data = SerializeToBytes(instance);
     global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, (uint)data.Length);
     stream.Write(data, 0, data.Length);
 }
示例#19
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static MethodOptions DeserializeLength(Stream stream, int length)
 {
     MethodOptions instance = new MethodOptions();
     DeserializeLength(stream, length, instance);
     return instance;
 }
示例#20
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static MethodOptions DeserializeLengthDelimited(Stream stream)
 {
     MethodOptions instance = new MethodOptions();
     DeserializeLengthDelimited(stream, instance);
     return instance;
 }
示例#21
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static MethodOptions Deserialize(Stream stream)
 {
     MethodOptions instance = new MethodOptions();
     Deserialize(stream, instance);
     return instance;
 }
示例#22
0
 /// <summary>Helper: put the buffer into a MemoryStream and create a new instance to deserializing into</summary>
 public static MethodOptions Deserialize(byte[] buffer)
 {
     MethodOptions instance = new MethodOptions();
     using (var ms = new MemoryStream(buffer))
         Deserialize(ms, instance);
     return instance;
 }
        /// <summary>Serialize the instance into the stream</summary>
        public static void Serialize(Stream stream, MethodOptions instance)
        {
            var msField = global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Pop();
            if (instance.UninterpretedOption != null)
            {
                foreach (var i999 in instance.UninterpretedOption)
                {
                    // Key for field: 999, LengthDelimited
                    stream.WriteByte(186);
                    stream.WriteByte(62);
                    msField.SetLength(0);
                    Google.Protobuf.UninterpretedOption.Serialize(msField, i999);
                    // Length delimited byte array
                    uint length999 = (uint)msField.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length999);
                    msField.WriteTo(stream);

                }
            }
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Push(msField);
        }
 private MethodOptions CreateMethodOptions()
 {
     return(MethodOptions.Create(new[] { _globalOptions, _serviceOptions }));
 }
示例#25
0
 /// <summary>Helper: Serialize into a MemoryStream and return its byte array</summary>
 public static byte[] SerializeToBytes(MethodOptions instance)
 {
     using (var ms = new MemoryStream())
     {
         Serialize(ms, instance);
         return ms.ToArray();
     }
 }
示例#26
0
        /// <summary>
        /// 缓存代理
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="key">关键字</param>
        /// <param name="suffix">关键字后接字符串(可为空)</param>
        /// <param name="expiry">过期时间(绝对)</param>
        /// <param name="acquire">方法变量</param>
        /// <param name="methodOptions">操作类型</param>
        /// <returns>缓存数据</returns>
        /// <remarks>2013-08-01 黄波 创建</remarks>
        private static T BaseGet <T>(string key, string suffix, DateTime expiry, Func <T> acquire, MethodOptions methodOptions)
        {
            var returnValue = default(T);

            //如果缓存关闭则不执行缓存策略
            if (CacheState != _CacheState.Open.ToString())
            {
                if (acquire == null)
                {
                    return(returnValue);
                }
                return(acquire());
            }

            //缓存关键字
            var cacheKey = key.ToString();

            if (!string.IsNullOrEmpty(suffix))
            {
                cacheKey += suffix;
            }

            //缓存键是否存在
            var cacheExists = CacheManager.Instance.IsExists(cacheKey);

            //强制重新缓存
            //或者缓存不存在时重新缓存
            if (methodOptions == MethodOptions.ForcedUpdating || !cacheExists)
            {
                //存在则更新 否则设置
                if (acquire != null)
                {
                    returnValue = acquire();
                    if (cacheExists)
                    {
                        CacheManager.Instance.Update(cacheKey, returnValue, expiry);
                    }
                    else
                    {
                        CacheManager.Instance.Set(cacheKey, returnValue, expiry);
                    }
                    return(returnValue);
                }
            }
            object o = CacheManager.Instance.Get <object>(cacheKey);

            return(CacheManager.Instance.Get <T>(cacheKey));
        }
示例#27
0
 /// <summary>
 /// 缓存代理
 /// </summary>
 /// <typeparam name="T">返回类型</typeparam>
 /// <param name="key">枚举类型关键字</param>
 /// <param name="acquire">方法变量</param>
 /// <param name="methodOptions">操作类型</param>
 /// <returns>缓存数据</returns>
 /// <remarks>2013-08-01 黄波 创建</remarks>
 public static T Get <T>(CacheKeys.Items key, Func <T> acquire, MethodOptions methodOptions = MethodOptions.Get)
 {
     return(BaseGet <T>(key.ToString(), null, DateTime.Now.AddMinutes(CacheExpiry), acquire, methodOptions));
 }
示例#28
0
 /// <summary>
 /// 缓存代理
 /// </summary>
 /// <typeparam name="T">返回类型</typeparam>
 /// <param name="key">枚举类型关键字</param>
 /// <param name="acquire">方法变量</param>
 /// <param name="expiry">过期时间</param>
 /// <param name="methodOptions">操作类型</param>
 /// <returns>缓存数据</returns>
 /// <remarks>2013-08-01 黄波 创建</remarks>
 public static T Get <T>(CacheKeys.Items key, DateTime expiry, Func <T> acquire, MethodOptions methodOptions = MethodOptions.Get)
 {
     return(BaseGet <T>(key.ToString(), null, expiry, acquire, methodOptions));
 }
示例#29
0
 private EndpointOptions FindWriteEndpoint(MethodOptions methodOptions, StorageOptions storageOptions)
 {
     return(methodOptions?.WriteEndpoint ?? methodOptions?.Endpoint ?? storageOptions?.WriteEndpoint ?? storageOptions?.Endpoint);
 }
示例#30
0
 /// <summary>
 /// 缓存代理
 /// </summary>
 /// <typeparam name="T">返回类型</typeparam>
 /// <param name="prefixKey">前缀关键字</param>
 /// <param name="suffix">关键字后接字符串</param>
 /// <param name="expiry">过期时间</param>
 /// <param name="acquire">方法变量</param>
 /// <param name="methodOptions">操作类型</param>
 /// <returns>缓存数据</returns>
 /// <remarks>2013-08-01 黄波 创建</remarks>
 public static T Get <T>(CacheKeys.Items prefixKey, string suffix, DateTime expiry, Func <T> acquire, MethodOptions methodOptions = MethodOptions.Get)
 {
     return(BaseGet <T>(prefixKey.ToString(), suffix, expiry, acquire, methodOptions));
 }
示例#31
0
 /// <summary>
 /// 缓存代理
 /// </summary>
 /// <typeparam name="T">返回类型</typeparam>
 /// <param name="prefixKey">前缀关键字</param>
 /// <param name="suffix">关键字后接字符串</param>
 /// <param name="expiry">过期时间</param>
 /// <param name="acquire">方法变量</param>
 /// <param name="methodOptions">操作类型</param>
 /// <returns>缓存数据</returns>
 /// <remarks>2013-08-01 黄波 创建</remarks>
 public static T Get <T>(string prefixKey, string suffix, DateTime expiry, Func <T> acquire, MethodOptions methodOptions = MethodOptions.Get)
 {
     return(BaseGet <T>(prefixKey, suffix, expiry, acquire, methodOptions));
 }
 /// <summary>
 /// Get all of the methods of an object
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static ICollection <ExtendedMethod> GetMethods(this object obj, MethodOptions options)
 {
     return(obj.GetType().GetMethods(options));
 }
示例#33
0
 /// <summary>
 /// 缓存代理
 /// </summary>
 /// <typeparam name="T">返回类型</typeparam>
 /// <param name="prefixKey">前缀关键字</param>
 /// <param name="suffix">关键字后接字符串</param>
 /// <param name="expiry">过期时间</param>
 /// <param name="acquire">方法变量</param>
 /// <param name="methodOptions">操作类型</param>
 /// <returns>缓存数据</returns>
 /// <remarks>2013-08-01 黄波 创建</remarks>
 public static T Get <T>(string prefixKey, Func <T> acquire, MethodOptions methodOptions = MethodOptions.Get)
 {
     return(BaseGet <T>(prefixKey, "", DateTime.Now.AddMinutes(CacheExpiry), acquire, methodOptions));
 }