public override bool Equals(object obj)
 {
     if (obj == null)
     {
         return(false);
     }
     try
     {
         SFSessionProperties prop = (SFSessionProperties)obj;
         foreach (SFSessionProperty sessionProperty in Enum.GetValues(typeof(SFSessionProperty)))
         {
             if (this.ContainsKey(sessionProperty) ^ prop.ContainsKey(sessionProperty))
             {
                 return(false);
             }
             if (!this.ContainsKey(sessionProperty))
             {
                 continue;
             }
             if (!this[sessionProperty].Equals(prop[sessionProperty]))
             {
                 return(false);
             }
         }
         return(true);
     }
     catch (InvalidCastException)
     {
         logger.Warn("Invalid casting to SFSessionProperties");
         return(false);
     }
 }
        internal SFSession(String connectionString, SecureString password, IRestRequest restRequest)
        {
            this.restRequest = restRequest;
            properties       = SFSessionProperties.parseConnectionString(connectionString, password);

            ParameterMap = new Dictionary <SFSessionParameter, string>();
        }
        private static bool IsRequired(SFSessionProperty sessionProperty, SFSessionProperties properties)
        {
            if (sessionProperty.Equals(SFSessionProperty.PASSWORD))
            {
                var authenticatorDefined =
                    properties.TryGetValue(SFSessionProperty.AUTHENTICATOR, out var authenticator);

                // External browser, jwt and oauth don't require a password for authenticating
                return(!(authenticatorDefined &&
                         (authenticator.Equals(ExternalBrowserAuthenticator.AUTH_NAME,
                                               StringComparison.OrdinalIgnoreCase) ||
                          authenticator.Equals(KeyPairAuthenticator.AUTH_NAME,
                                               StringComparison.OrdinalIgnoreCase) ||
                          authenticator.Equals(OAuthAuthenticator.AUTH_NAME,
                                               StringComparison.OrdinalIgnoreCase))));
            }
            else if (sessionProperty.Equals(SFSessionProperty.USER))
            {
                var authenticatorDefined =
                    properties.TryGetValue(SFSessionProperty.AUTHENTICATOR, out var authenticator);

                // Oauth don't require a username for authenticating
                return(!(authenticatorDefined && (
                             authenticator.Equals(OAuthAuthenticator.AUTH_NAME, StringComparison.OrdinalIgnoreCase))));
            }
            else
            {
                return(sessionProperty.GetAttribute <SFSessionPropertyAttr>().required);
            }
        }
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="connectionString">A string in the form of "key1=value1;key2=value2"</param>
        internal SFSession(String connectionString, SecureString password)
        {
            restRequest = RestRequestImpl.Instance;
            properties  = SFSessionProperties.parseConnectionString(connectionString, password);

            parameterMap = new Dictionary <string, string>();
        }
Пример #5
0
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="connectionString">A string in the form of "key1=value1;key2=value2"</param>
        internal SFSession(String connectionString, SecureString password)
        {
            restRequest = RestRequestImpl.Instance;
            properties  = SFSessionProperties.parseConnectionString(connectionString);
            if (password != null)
            {
                properties[SFSessionProperty.PASSWORD] = new NetworkCredential(string.Empty, password).Password;
            }

            parameterMap = new Dictionary <string, string>();
        }
Пример #6
0
        internal SFSession(String connectionString, SecureString password, IRestRequester restRequester)
        {
            this.restRequester = restRequester;
            properties         = SFSessionProperties.parseConnectionString(connectionString, password);

            ParameterMap = new Dictionary <SFSessionParameter, string>();

            int timeoutInSec = int.Parse(properties[SFSessionProperty.CONNECTION_TIMEOUT]);

            connectionTimeout = timeoutInSec > 0 ? TimeSpan.FromSeconds(timeoutInSec) : Timeout.InfiniteTimeSpan;
        }
Пример #7
0
        internal static SFSessionProperties parseConnectionString(String connectionString, SecureString password)
        {
            logger.Info("Start parsing connection string.");
            SFSessionProperties properties = new SFSessionProperties();

            string[] propertyEntry = connectionString.Split(';');

            foreach (string keyVal in propertyEntry)
            {
                if (keyVal.Length > 0)
                {
                    string[] token = keyVal.Split(new string[] { "=" }, StringSplitOptions.None);
                    if (token.Length == 2)
                    {
                        try
                        {
                            SFSessionProperty p = (SFSessionProperty)Enum.Parse(
                                typeof(SFSessionProperty), token[0].ToUpper());
                            properties.Add(p, token[1]);
                            logger.Info($"Connection property: {p}, value: {(p == SFSessionProperty.PASSWORD ? "XXXXXXXX" : token[1])}");
                        }
                        catch (ArgumentException e)
                        {
                            logger.Warn($"Property {token[0]} not found ignored.");
                        }
                    }
                    else
                    {
                        string invalidStringDetail = String.Format("Invalid kay value pair {0}", keyVal);
                        SnowflakeDbException e     = new SnowflakeDbException(SFError.INVALID_CONNECTION_STRING,
                                                                              new object[] { invalidStringDetail });
                        logger.Error("Invalid string.", e);
                        throw e;
                    }
                }
            }

            if (password != null)
            {
                properties[SFSessionProperty.PASSWORD] = new NetworkCredential(string.Empty, password).Password;
            }
            checkSessionProperties(properties);

            // compose host value if not specified
            if (!properties.ContainsKey(SFSessionProperty.HOST))
            {
                string hostName = String.Format("%s.snowflakecomputing.com", properties[SFSessionProperty.ACCOUNT]);
                properties.Add(SFSessionProperty.HOST, hostName);
                logger.Info($"Compose host name: {hostName}");
            }

            return(properties);
        }
Пример #8
0
 private static bool IsRequired(SFSessionProperty sessionProperty, SFSessionProperties properties)
 {
     if (sessionProperty.Equals(SFSessionProperty.PASSWORD))
     {
         return(!(properties.ContainsKey(SFSessionProperty.AUTHENTICATOR) &&
                  properties[SFSessionProperty.AUTHENTICATOR] == "externalbrowser"));
     }
     else
     {
         return(sessionProperty.GetAttribute <SFSessionPropertyAttr>().required);
     }
 }
        internal SFSession(String connectionString, SecureString password, IRestRequester restRequester)
        {
            this.restRequester = restRequester;
            properties         = SFSessionProperties.parseConnectionString(connectionString, password);

            ParameterMap = new Dictionary <SFSessionParameter, object>();
            ParameterMap[SFSessionParameter.CLIENT_VALIDATE_DEFAULT_PARAMETERS] =
                Boolean.Parse(properties[SFSessionProperty.VALIDATE_DEFAULT_PARAMETERS]);

            int timeoutInSec = int.Parse(properties[SFSessionProperty.CONNECTION_TIMEOUT]);

            connectionTimeout = timeoutInSec > 0 ? TimeSpan.FromSeconds(timeoutInSec) : Timeout.InfiniteTimeSpan;
        }
Пример #10
0
        internal SFSession(String connectionString, SecureString password, IRestRequester restRequester)
        {
            this.restRequester = restRequester;
            properties         = SFSessionProperties.parseConnectionString(connectionString, password);

            ParameterMap = new Dictionary <SFSessionParameter, object>();
            int recommendedMinTimeoutSec = BaseRestRequest.DEFAULT_REST_RETRY_SECONDS_TIMEOUT;
            int timeoutInSec             = recommendedMinTimeoutSec;

            try
            {
                ParameterMap[SFSessionParameter.CLIENT_VALIDATE_DEFAULT_PARAMETERS] =
                    Boolean.Parse(properties[SFSessionProperty.VALIDATE_DEFAULT_PARAMETERS]);

                timeoutInSec = int.Parse(properties[SFSessionProperty.CONNECTION_TIMEOUT]);

                InsecureMode = Boolean.Parse(properties[SFSessionProperty.INSECUREMODE]);
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
                throw new SnowflakeDbException(e.InnerException,
                                               SFError.INVALID_CONNECTION_STRING,
                                               "Unable to connect");
            }

            if (timeoutInSec < recommendedMinTimeoutSec)
            {
                logger.Warn($"Connection timeout provided is less than recommended minimum value of" +
                            $" {recommendedMinTimeoutSec}");
            }
            if (timeoutInSec < 0)
            {
                logger.Warn($"Connection timeout provided is negative. Timeout will be infinite.");
            }

            connectionTimeout = timeoutInSec > 0 ? TimeSpan.FromSeconds(timeoutInSec) : Timeout.InfiniteTimeSpan;
        }
        private static void checkSessionProperties(SFSessionProperties properties)
        {
            foreach (SFSessionProperty sessionProperty in Enum.GetValues(typeof(SFSessionProperty)))
            {
                // if required property, check if exists in the dictionary
                if (IsRequired(sessionProperty, properties) &&
                    !properties.ContainsKey(sessionProperty))
                {
                    SnowflakeDbException e = new SnowflakeDbException(SFError.MISSING_CONNECTION_PROPERTY,
                                                                      sessionProperty);
                    logger.Error("Missing connetion property", e);
                    throw e;
                }

                // add default value to the map
                string defaultVal = sessionProperty.GetAttribute <SFSessionPropertyAttr>().defaultValue;
                if (defaultVal != null && !properties.ContainsKey(sessionProperty))
                {
                    logger.Debug($"Sesssion property {sessionProperty} set to default value: {defaultVal}");
                    properties.Add(sessionProperty, defaultVal);
                }
            }
        }
        internal static SFSessionProperties parseConnectionString(String connectionString, SecureString password)
        {
            logger.Info("Start parsing connection string.");
            SFSessionProperties properties = new SFSessionProperties();

            string[] propertyEntry = connectionString.Split(';');

            foreach (string keyVal in propertyEntry)
            {
                if (keyVal.Length > 0)
                {
                    string[] tokens = keyVal.Split(new string[] { "=" }, StringSplitOptions.None);
                    if (tokens.Length != 2)
                    {
                        // https://docs.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbconnection.connectionstring
                        // To include an equal sign (=) in a keyword or value, it must be preceded
                        // by another equal sign. For example, in the hypothetical connection
                        // string "key==word=value" :
                        // the keyword is "key=word" and the value is "value".
                        int currentIndex     = 0;
                        int singleEqualIndex = -1;
                        while (currentIndex <= keyVal.Length)
                        {
                            currentIndex = keyVal.IndexOf("=", currentIndex);
                            if (-1 == currentIndex)
                            {
                                // No '=' found
                                break;
                            }
                            if ((currentIndex < (keyVal.Length - 1)) &&
                                ('=' != keyVal[currentIndex + 1]))
                            {
                                if (0 > singleEqualIndex)
                                {
                                    // First single '=' encountered
                                    singleEqualIndex = currentIndex;
                                    currentIndex++;
                                }
                                else
                                {
                                    // Found another single '=' which is not allowed
                                    singleEqualIndex = -1;
                                    break;
                                }
                            }
                            else
                            {
                                // skip the doubled one
                                currentIndex += 2;
                            }
                        }

                        if ((singleEqualIndex > 0) && (singleEqualIndex < keyVal.Length - 1))
                        {
                            // Split the key/value at the right index and deduplicate '=='
                            tokens    = new string[2];
                            tokens[0] = keyVal.Substring(0, singleEqualIndex).Replace("==", "=");
                            tokens[1] = keyVal.Substring(
                                singleEqualIndex + 1,
                                keyVal.Length - (singleEqualIndex + 1)).Replace("==", "=");;
                        }
                        else
                        {
                            // An equal sign was not doubled or something else happened
                            // making the connection invalid
                            string invalidStringDetail =
                                String.Format("Invalid key value pair {0}", keyVal);
                            SnowflakeDbException e =
                                new SnowflakeDbException(SFError.INVALID_CONNECTION_STRING,
                                                         new object[] { invalidStringDetail });
                            logger.Error("Invalid string.", e);
                            throw e;
                        }
                    }

                    try
                    {
                        SFSessionProperty p = (SFSessionProperty)Enum.Parse(
                            typeof(SFSessionProperty), tokens[0].ToUpper());
                        properties.Add(p, tokens[1]);
                        logger.Info($"Connection property: {p}, value: {(secretProps.Contains(p) ? "XXXXXXXX" : tokens[1])}");
                    }
                    catch (ArgumentException e)
                    {
                        logger.Warn($"Property {tokens[0]} not found ignored.", e);
                    }
                }
            }

            if (password != null)
            {
                properties[SFSessionProperty.PASSWORD] = new NetworkCredential(string.Empty, password).Password;
            }
            checkSessionProperties(properties);

            // compose host value if not specified
            if (!properties.ContainsKey(SFSessionProperty.HOST) ||
                (0 == properties[SFSessionProperty.HOST].Length))
            {
                string hostName = String.Format("{0}.snowflakecomputing.com", properties[SFSessionProperty.ACCOUNT]);
                // Remove in case it's here but empty
                properties.Remove(SFSessionProperty.HOST);
                properties.Add(SFSessionProperty.HOST, hostName);
                logger.Info($"Compose host name: {hostName}");
            }

            return(properties);
        }