Esempio n. 1
0
 public static Type ParseType(string assemblyQualifiedName)
 {
     return(AssemblyUtils.FindType(assemblyQualifiedName.FromCsvField()));
 }
Esempio n. 2
0
        /// <summary>
        /// Returns Type from type name syntax of .NET's typeof()
        /// </summary>
        public Type @typeof(string typeName)
        {
            if (string.IsNullOrEmpty(typeName))
            {
                return(null);
            }

            var key = "type:" + typeName;

            Type cookGenericType(Type type, List <string> genericArgs)
            {
                if (type.IsGenericType)
                {
                    var isGenericDefinition = genericArgs != null && genericArgs.All(x => x == "");
                    if (!isGenericDefinition)
                    {
                        var genericTypes = typeGenericTypes(genericArgs);
                        var cookedType   = type.MakeGenericType(genericTypes);
                        return(cookedType);
                    }
                }

                return(type);
            }

            var resolvedType = (Type)Context.Cache.GetOrAdd(key, k => {
                var isGeneric             = typeName.IndexOf('<') >= 0;
                List <string> genericArgs = null;

                if (isGeneric)
                {
                    genericArgs = typeGenericArgs(typeName);
                    typeName    = typeName.LeftPart('<') + '`' + Math.Max(genericArgs.Count, 1);
                }

                if (typeName.IndexOf('.') >= 0)
                {
                    if (Context.ScriptTypeQualifiedNameMap.TryGetValue(typeName, out var type))
                    {
                        return(cookGenericType(type, genericArgs));
                    }

                    if (Context.AllowScriptingOfAllTypes)
                    {
                        type = AssemblyUtils.FindType(typeName);
                        if (type != null)
                        {
                            return(cookGenericType(type, genericArgs));
                        }
                    }
                }
                else
                {
                    switch (typeName)
                    {
                    case "bool":
                        return(typeof(bool));

                    case "byte":
                        return(typeof(byte));

                    case "sbyte":
                        return(typeof(sbyte));

                    case "char":
                        return(typeof(char));

                    case "decimal":
                        return(typeof(decimal));

                    case "double":
                        return(typeof(double));

                    case "float":
                        return(typeof(float));

                    case "int":
                        return(typeof(int));

                    case "uint":
                        return(typeof(uint));

                    case "long":
                        return(typeof(long));

                    case "ulong":
                        return(typeof(ulong));

                    case "object":
                        return(typeof(object));

                    case "short":
                        return(typeof(short));

                    case "ushort":
                        return(typeof(ushort));

                    case "string":
                        return(typeof(string));
                    }

                    if (Context.ScriptTypeNameMap.TryGetValue(typeName, out var type))
                    {
                        return(cookGenericType(type, genericArgs));
                    }
                }

                foreach (var ns in Context.ScriptNamespaces)
                {
                    var lookupType = ns + "." + typeName;
                    if (Context.ScriptTypeQualifiedNameMap.TryGetValue(lookupType, out var type))
                    {
                        return(cookGenericType(type, genericArgs));
                    }

                    if (Context.AllowScriptingOfAllTypes)
                    {
                        type = AssemblyUtils.FindType(lookupType);
                        if (type != null)
                        {
                            return(cookGenericType(type, genericArgs));
                        }
                    }
                }

                var parts       = typeName.Split('.');
                var nameBuilder = "";
                for (var i = 0; i < parts.Length; i++)
                {
                    try
                    {
                        if (i > 0)
                        {
                            nameBuilder += '.';
                        }

                        nameBuilder   += parts[i];
                        var parentType = @typeof(nameBuilder);
                        if (parentType != null)
                        {
                            var nestedTypeName = parts[++i];
                            var nestedType     = parentType.GetNestedType(nestedTypeName);
                            i++;
                            while (i < parts.Length)
                            {
                                nestedTypeName = parts[i++];
                                nestedType     = nestedType.GetNestedType(nestedTypeName);
                            }
                            return(nestedType);
                        }
                    }
                    catch { }
                }

                return(null);
            });

            return(resolvedType);
        }
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
#if NETSTANDARD2_0
                var addresses = Dns.GetHostAddressesAsync(Host).Result;
                socket.Connect(addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork), Port);
#else
                if (ConnectTimeout <= 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }
#endif

                if (!socket.Connected)
                {
                    socket.Close();
                    socket        = null;
                    DeactivatedAt = DateTime.UtcNow;
                    return;
                }

                Stream networkStream = new NetworkStream(socket);

                if (Ssl)
                {
                    if (Env.IsMono)
                    {
                        //Mono doesn't support EncryptionPolicy
                        sslStream = new SslStream(networkStream,
                                                  leaveInnerStreamOpen: false,
                                                  userCertificateValidationCallback: RedisConfig.CertificateValidationCallback,
                                                  userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback);
                    }
                    else
                    {
#if NETSTANDARD2_0
                        sslStream = new SslStream(networkStream,
                                                  leaveInnerStreamOpen: false,
                                                  userCertificateValidationCallback: RedisConfig.CertificateValidationCallback,
                                                  userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback,
                                                  encryptionPolicy: EncryptionPolicy.RequireEncryption);
#else
                        var ctor = typeof(SslStream).GetConstructors()
                                   .First(x => x.GetParameters().Length == 5);

                        var policyType  = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy");
                        var policyValue = Enum.Parse(policyType, "RequireEncryption");

                        sslStream = (SslStream)ctor.Invoke(new[] {
                            networkStream,
                            false,
                            RedisConfig.CertificateValidationCallback,
                            RedisConfig.CertificateSelectionCallback,
                            policyValue,
                        });
#endif
                    }

#if NETSTANDARD2_0
                    sslStream.AuthenticateAsClientAsync(Host).Wait();
#else
                    sslStream.AuthenticateAsClient(Host);
#endif

                    if (!sslStream.IsEncrypted)
                    {
                        throw new Exception("Could not establish an encrypted connection to " + Host);
                    }

                    networkStream = sslStream;
                }

                Bstream = new BufferedStream(networkStream, 16 * 1024);

                if (!string.IsNullOrEmpty(Password))
                {
                    SendUnmanagedExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendUnmanagedExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                if (Client != null)
                {
                    SendUnmanagedExpectSuccess(Commands.Client, Commands.SetName, Client.ToUtf8Bytes());
                }

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        ServerVersionNumber = RedisConfig.AssumeServerVersion.GetValueOrDefault(0);
                        if (ServerVersionNumber <= 0)
                        {
                            var parts   = ServerVersion.Split('.');
                            var version = int.Parse(parts[0]) * 1000;
                            if (parts.Length > 1)
                            {
                                version += int.Parse(parts[1]) * 100;
                            }
                            if (parts.Length > 2)
                            {
                                version += int.Parse(parts[2]);
                            }

                            ServerVersionNumber = version;
                        }
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }

                clientPort               = socket.LocalEndPoint is IPEndPoint ipEndpoint ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException)
            {
                log.Error(ErrorConnect.Fmt(Host, Port));
                throw;
            }
        }
Esempio n. 4
0
        public void Can_connect_to_Buffered_SslStream()
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = -1,
                ReceiveTimeout = -1,
            };

            socket.Connect(Host, Port);

            if (!socket.Connected)
            {
                socket.Close();
                throw new Exception("Could not connect");
            }

            Stream networkStream = new NetworkStream(socket);

            SslStream sslStream;

            if (Env.IsMono)
            {
                //Mono doesn't support EncryptionPolicy
                sslStream = new SslStream(networkStream,
                                          leaveInnerStreamOpen: false,
                                          userCertificateValidationCallback: RedisConfig.CertificateValidationCallback,
                                          userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback);
            }
            else
            {
                var ctor = typeof(SslStream).GetConstructors()
                           .First(x => x.GetParameters().Length == 5);

                var policyType  = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy");
                var policyValue = Enum.Parse(policyType, "RequireEncryption");

                sslStream = (SslStream)ctor.Invoke(new [] {
                    networkStream,
                    false,
                    RedisConfig.CertificateValidationCallback,
                    RedisConfig.CertificateSelectionCallback,
                    policyValue,
                });

                //sslStream = new SslStream(networkStream,
                //    leaveInnerStreamOpen: false,
                //    userCertificateValidationCallback: null,
                //    userCertificateSelectionCallback: null,
                //    encryptionPolicy: EncryptionPolicy.RequireEncryption);
            }

            sslStream.AuthenticateAsClient(Host);

            if (!sslStream.IsEncrypted)
            {
                throw new Exception("Could not establish an encrypted connection to " + Host);
            }

            var bstream = new BufferedStream(sslStream, 16 * 1024);

            SendAuth(bstream);
        }
        internal static object StringToType(
            Type type,
            string strType,
            EmptyCtorDelegate ctorFn,
            Dictionary <string, TypeAccessor> typeAccessorMap)
        {
            var index = 0;

            if (strType == null)
            {
                return(null);
            }

            //if (!Serializer.EatMapStartChar(strType, ref index))
            if (strType[index++] != JsWriter.MapStartChar)
            {
                throw DeserializeTypeRef.CreateSerializationError(type, strType);
            }

            if (JsonTypeSerializer.IsEmptyMap(strType))
            {
                return(ctorFn());
            }

            object instance = null;

            var propertyResolver = JsConfig.PropertyConvention == PropertyConvention.Lenient
                ? ParseUtils.LenientPropertyNameResolver
                : ParseUtils.DefaultPropertyNameResolver;

            var strTypeLength = strType.Length;

            while (index < strTypeLength)
            {
                var propertyName = Serializer.EatMapKey(strType, ref index);

                //Serializer.EatMapKeySeperator(strType, ref index);
                index++;

                var propertyValueStr = Serializer.EatValue(strType, ref index);
                var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1;

                if (possibleTypeInfo && propertyName == JsWriter.TypeAttr)
                {
                    var explicitTypeName = Serializer.ParseString(propertyValueStr);
                    var explicitType     = AssemblyUtils.FindType(explicitTypeName);

                    if (explicitType != null && !explicitType.IsInterface() && !explicitType.IsAbstract())
                    {
                        instance = explicitType.CreateInstance();
                    }

                    if (instance == null)
                    {
                        Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr);
                    }
                    else
                    {
                        //If __type info doesn't match, ignore it.
                        if (!type.InstanceOfType(instance))
                        {
                            instance = null;
                        }
                        else
                        {
                            var derivedType = instance.GetType();
                            if (derivedType != type)
                            {
                                var derivedTypeConfig = new TypeConfig(derivedType);
                                var map = DeserializeTypeRef.GetTypeAccessorMap(derivedTypeConfig, Serializer);
                                if (map != null)
                                {
                                    typeAccessorMap = map;
                                }
                            }
                        }
                    }

                    //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                    if (index != strType.Length)
                    {
                        index++;
                    }

                    continue;
                }

                if (instance == null)
                {
                    instance = ctorFn();
                }

                var typeAccessor = propertyResolver.GetTypeAccessorForProperty(propertyName, typeAccessorMap);

                var propType = possibleTypeInfo && propertyValueStr[0] == '_' ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null;
                if (propType != null)
                {
                    try
                    {
                        if (typeAccessor != null)
                        {
                            var parseFn       = Serializer.GetParseFn(propType);
                            var propertyValue = parseFn(propertyValueStr);
                            typeAccessor.SetProperty(instance, propertyValue);
                        }

                        //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                        if (index != strType.Length)
                        {
                            index++;
                        }

                        continue;
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.ThrowOnDeserializationError)
                        {
                            throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e);
                        }
                        else
                        {
                            Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName, propertyValueStr);
                        }
                    }
                }

                if (typeAccessor != null && typeAccessor.GetProperty != null && typeAccessor.SetProperty != null)
                {
                    try
                    {
                        var propertyValue = typeAccessor.GetProperty(propertyValueStr);
                        typeAccessor.SetProperty(instance, propertyValue);
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.ThrowOnDeserializationError)
                        {
                            throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e);
                        }
                        else
                        {
                            Tracer.Instance.WriteWarning("WARN: failed to set property {0} with: {1}", propertyName, propertyValueStr);
                        }
                    }
                }

                //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                if (index != strType.Length)
                {
                    index++;
                }
            }

            return(instance);
        }
        internal static object StringToType(
            Type type,
            string strType,
            EmptyCtorDelegate ctorFn,
            Dictionary <string, TypeAccessor> typeAccessorMap)
        {
            var index = 0;

            if (strType == null)
            {
                return(null);
            }

            //if (!Serializer.EatMapStartChar(strType, ref index))
            for (; index < strType.Length; index++)
            {
                var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c])
                {
                    break;
                }
            }                                                                                                                                                                        //Whitespace inline
            if (strType[index++] != JsWriter.MapStartChar)
            {
                throw DeserializeTypeRef.CreateSerializationError(type, strType);
            }

            if (JsonTypeSerializer.IsEmptyMap(strType, index))
            {
                return(ctorFn());
            }

            object instance = null;

            var strTypeLength = strType.Length;

            while (index < strTypeLength)
            {
                var propertyName = JsonTypeSerializer.ParseJsonString(strType, ref index);

                //Serializer.EatMapKeySeperator(strType, ref index);
                for (; index < strType.Length; index++)
                {
                    var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c])
                    {
                        break;
                    }
                }                                                                                                                                                                        //Whitespace inline
                if (strType.Length != index)
                {
                    index++;
                }

                var propertyValueStr = Serializer.EatValue(strType, ref index);
                var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1;

                //if we already have an instance don't check type info, because then we will have a half deserialized object
                //we could throw here or just use the existing instance.
                if (instance == null && possibleTypeInfo && propertyName == JsWriter.TypeAttr)
                {
                    var explicitTypeName = Serializer.ParseString(propertyValueStr);
                    var explicitType     = AssemblyUtils.FindType(explicitTypeName);

                    if (explicitType != null && !explicitType.IsInterface() && !explicitType.IsAbstract())
                    {
                        instance = explicitType.CreateInstance();
                    }

                    if (instance == null)
                    {
                        Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr);
                    }
                    else
                    {
                        //If __type info doesn't match, ignore it.
                        if (!type.InstanceOfType(instance))
                        {
                            instance = null;
                        }
                        else
                        {
                            var derivedType = instance.GetType();
                            if (derivedType != type)
                            {
                                var derivedTypeConfig = new TypeConfig(derivedType);
                                var map = DeserializeTypeRef.GetTypeAccessorMap(derivedTypeConfig, Serializer);
                                if (map != null)
                                {
                                    typeAccessorMap = map;
                                }
                            }
                        }
                    }

                    Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                    continue;
                }

                if (instance == null)
                {
                    instance = ctorFn();
                }

                var typeAccessor = PropertyNameResolver.GetTypeAccessorForProperty(propertyName, typeAccessorMap);

                var propType = possibleTypeInfo && propertyValueStr[0] == '_' ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null;
                if (propType != null)
                {
                    try
                    {
                        if (typeAccessor != null)
                        {
                            //var parseFn = Serializer.GetParseFn(propType);
                            var parseFn = JsonReader.GetParseFn(propType);

                            var propertyValue = parseFn(propertyValueStr);
                            typeAccessor.SetProperty(instance, propertyValue);
                        }

                        //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                        for (; index < strType.Length; index++)
                        {
                            var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c])
                            {
                                break;
                            }
                        }                                                                                                                                                                        //Whitespace inline
                        if (index != strType.Length)
                        {
                            var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar;
                            index++;
                            if (success)
                            {
                                for (; index < strType.Length; index++)
                                {
                                    var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c])
                                    {
                                        break;
                                    }
                                }                                                                                                                                                                        //Whitespace inline
                            }
                        }

                        continue;
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.ThrowOnDeserializationError)
                        {
                            throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, propType, e);
                        }
                        else
                        {
                            Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName, propertyValueStr);
                        }
                    }
                }

                if (typeAccessor != null && typeAccessor.GetProperty != null && typeAccessor.SetProperty != null)
                {
                    try
                    {
                        var propertyValue = typeAccessor.GetProperty(propertyValueStr);
                        typeAccessor.SetProperty(instance, propertyValue);
                    }
                    catch (Exception e)
                    {
                        if (JsConfig.ThrowOnDeserializationError)
                        {
                            throw DeserializeTypeRef.GetSerializationException(propertyName, propertyValueStr, typeAccessor.PropertyType, e);
                        }
                        else
                        {
                            Tracer.Instance.WriteWarning("WARN: failed to set property {0} with: {1}", propertyName, propertyValueStr);
                        }
                    }
                }

                //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                for (; index < strType.Length; index++)
                {
                    var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c])
                    {
                        break;
                    }
                }                                                                                                                                                                        //Whitespace inline
                if (index != strType.Length)
                {
                    var success = strType[index] == JsWriter.ItemSeperator || strType[index] == JsWriter.MapEndChar;
                    index++;
                    if (success)
                    {
                        for (; index < strType.Length; index++)
                        {
                            var c = strType[index]; if (c >= JsonTypeSerializer.WhiteSpaceFlags.Length || !JsonTypeSerializer.WhiteSpaceFlags[c])
                            {
                                break;
                            }
                        }                                                                                                                                                                        //Whitespace inline
                    }
                }
            }

            return(instance);
        }