コード例 #1
0
        internal void renewSession()
        {
            RenewSessionRequest postBody = new RenewSessionRequest()
            {
                oldSessionToken = this.sessionToken,
                requestType     = "RENEW"
            };

            SFRestRequest renewSessionRequest = new SFRestRequest
            {
                jsonBody = postBody,
                uri      = BuildUri(SF_TOKEN_REQUEST_PATH,
                                    new Dictionary <string, string> {
                    { SF_QUERY_REQUEST_ID, Guid.NewGuid().ToString() }
                }),
                authorizationToken   = string.Format(SF_AUTHORIZATION_SNOWFLAKE_FMT, masterToken),
                sfRestRequestTimeout = Timeout.InfiniteTimeSpan
            };

            var response = restRequest.Post <RenewSessionResponse>(renewSessionRequest);

            if (!response.success)
            {
                SnowflakeDbException e = new SnowflakeDbException("",
                                                                  response.code, response.message, "");
                logger.Error("Renew session failed", e);
                throw e;
            }
            else
            {
                sessionToken = response.data.sessionToken;
            }
        }
コード例 #2
0
        internal void close()
        {
            // Nothing to do if the session is not open
            if (null == sessionToken)
            {
                return;
            }

            // Send a close session request
            var queryParams = new Dictionary <string, string>();

            queryParams[RestParams.SF_QUERY_SESSION_DELETE] = "true";
            queryParams[RestParams.SF_QUERY_REQUEST_ID]     = Guid.NewGuid().ToString();
            queryParams[RestParams.SF_QUERY_REQUEST_GUID]   = Guid.NewGuid().ToString();

            SFRestRequest closeSessionRequest = new SFRestRequest(InsecureMode)
            {
                Url = BuildUri(RestPath.SF_SESSION_PATH, queryParams),
                authorizationToken = string.Format(SF_AUTHORIZATION_SNOWFLAKE_FMT, sessionToken)
            };

            var response = restRequester.Post <CloseResponse>(closeSessionRequest);

            if (!response.success)
            {
                logger.Debug($"Failed to delete session, error ignored. Code: {response.code} Message: {response.message}");
            }
        }
コード例 #3
0
        internal void open()
        {
            logger.Debug("Open Session");

            // build uri
            UriBuilder uriBuilder = new UriBuilder();

            uriBuilder.Scheme = properties[SFSessionProperty.SCHEME];
            uriBuilder.Host   = properties[SFSessionProperty.HOST];
            uriBuilder.Port   = Int32.Parse(properties[SFSessionProperty.PORT]);
            uriBuilder.Path   = SF_LOGIN_PATH;
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            string value;

            queryString[SF_QUERY_WAREHOUSE]  = properties.TryGetValue(SFSessionProperty.WAREHOUSE, out value) ? value : "";
            queryString[SF_QUERY_DB]         = properties.TryGetValue(SFSessionProperty.DB, out value) ? value : "";
            queryString[SF_QUERY_SCHEMA]     = properties.TryGetValue(SFSessionProperty.SCHEMA, out value) ? value : "";
            queryString[SF_QUERY_REQUEST_ID] = Guid.NewGuid().ToString();
            uriBuilder.Query = queryString.ToString();

            // build post body
            AuthnRequestClientEnv clientEnv = new AuthnRequestClientEnv()
            {
                application = System.Diagnostics.Process.GetCurrentProcess().ProcessName,
                osVersion   = System.Environment.OSVersion.VersionString
            };

            AuthnRequestData data = new AuthnRequestData()
            {
                loginName        = properties[SFSessionProperty.USER],
                password         = properties[SFSessionProperty.PASSWORD],
                clientAppId      = ".NET",
                clientAppVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                accountName      = properties[SFSessionProperty.ACCOUNT],
                clientEnv        = clientEnv
            };

            // build request
            int           connectionTimeoutSec = Int32.Parse(properties[SFSessionProperty.CONNECTION_TIMEOUT]);
            SFRestRequest loginRequest         = new SFRestRequest();

            loginRequest.jsonBody = new AuthnRequest()
            {
                data = data
            };
            loginRequest.uri = uriBuilder.Uri;
            loginRequest.authorizationToken = SF_AUTHORIZATION_BASIC;
            // total login timeout
            loginRequest.sfRestRequestTimeout = connectionTimeoutSec <= 0 ? -1 : connectionTimeoutSec * 1000;

            if (logger.IsTraceEnabled)
            {
                logger.TraceFormat("Login Request Data: {0}", loginRequest.ToString());
            }

            JObject response = restRequest.post(loginRequest);

            parseLoginResponse(response);
        }
コード例 #4
0
        internal void close()
        {
            UriBuilder uriBuilder = new UriBuilder();

            uriBuilder.Scheme = properties[SFSessionProperty.SCHEME];
            uriBuilder.Host   = properties[SFSessionProperty.HOST];
            uriBuilder.Port   = Int32.Parse(properties[SFSessionProperty.PORT]);
            uriBuilder.Path   = SF_SESSION_PATH;

            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString[SF_QUERY_SESSION_DELETE] = "true";
            queryString[SF_QUERY_REQUEST_ID]     = Guid.NewGuid().ToString();
            uriBuilder.Query = queryString.ToString();

            SFRestRequest closeSessionRequest = new SFRestRequest();

            closeSessionRequest.jsonBody           = null;
            closeSessionRequest.uri                = uriBuilder.Uri;
            closeSessionRequest.authorizationToken = String.Format(SF_AUTHORIZATION_SNOWFLAKE_FMT, sessionToken);

            JObject          response = restRequest.post(closeSessionRequest);
            NullDataResponse deleteSessionResponse = response.ToObject <NullDataResponse>();

            if (!deleteSessionResponse.success)
            {
                logger.WarnFormat("Failed to delete session, error ignored. Code: {0} Message: {0}",
                                  deleteSessionResponse.code, deleteSessionResponse.message);
            }
        }
コード例 #5
0
        public async Task <T> GetAsync <T>(SFRestRequest request, CancellationToken cancellationToken)
        {
            var req = ToRequestMessage(HttpMethod.Get, request);

            var response = await SendAsync(req, request.sfRestRequestTimeout, cancellationToken);

            var json = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <T>(json));
        }
コード例 #6
0
        internal void cancel()
        {
            if (this.requestId == null)
            {
                logger.Info("No query to be cancelled.");
                return;
            }

            UriBuilder uriBuilder = new UriBuilder();

            uriBuilder.Scheme = sfSession.properties[SFSessionProperty.SCHEME];
            uriBuilder.Host   = sfSession.properties[SFSessionProperty.HOST];
            uriBuilder.Port   = Int32.Parse(sfSession.properties[SFSessionProperty.PORT]);
            uriBuilder.Path   = SF_QUERY_CANCEL_PATH;

            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString[SF_QUERY_REQUEST_ID] = Guid.NewGuid().ToString();
            uriBuilder.Query = queryString.ToString();

            QueryCancelRequest postBody = new QueryCancelRequest()
            {
                requestId = this.requestId
            };

            SFRestRequest cancelRequest = new SFRestRequest();

            cancelRequest.uri = uriBuilder.Uri;
            cancelRequest.authorizationToken = String.Format(SF_AUTHORIZATION_SNOWFLAKE_FMT, sfSession.sessionToken);
            cancelRequest.jsonBody           = postBody;

            NullDataResponse cancelResponse = restRequest.post(cancelRequest).ToObject <NullDataResponse>();

            if (cancelResponse.success)
            {
                logger.Info("Query cancellation succeed");
            }
            else
            {
                SnowflakeDbException e = new SnowflakeDbException(
                    "", cancelResponse.code, cancelResponse.message, "");
                logger.Error("Query cancellation failed.", e);
                throw e;
            }
        }
コード例 #7
0
        private HttpRequestMessage ToRequestMessage(HttpMethod method, SFRestRequest request)
        {
            var msg = new HttpRequestMessage(method, request.uri);

            if (method != HttpMethod.Get && request.jsonBody != null)
            {
                var json = JsonConvert.SerializeObject(request.jsonBody);
                //TODO: Check if we should use other encodings...
                msg.Content = new StringContent(json, Encoding.UTF8, "application/json");
            }

            msg.Headers.Add(SF_AUTHORIZATION_HEADER, request.authorizationToken);
            msg.Headers.Accept.Add(applicationSnowflake);

            msg.Properties["TIMEOUT_PER_HTTP_REQUEST"] = request.httpRequestTimeout;

            return(msg);
        }
コード例 #8
0
        public JObject get(SFRestRequest getRequest)
        {
            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, getRequest.uri);

            message.Headers.Add(SF_AUTHORIZATION_HEADER, getRequest.authorizationToken);
            message.Headers.Accept.Add(applicationSnowflake);
            message.Properties["TIMEOUT_PER_HTTP_REQUEST"] = getRequest.httpRequestTimeout;

            CancellationTokenSource cancellationTokenSource =
                new CancellationTokenSource(getRequest.sfRestRequestTimeout);

            var responseContent = sendRequest(message, cancellationTokenSource.Token).Content;

            var jsonString = responseContent.ReadAsStringAsync();

            jsonString.Wait();

            return(JObject.Parse(jsonString.Result));
        }
コード例 #9
0
        internal void close()
        {
            var queryParams = new Dictionary <string, string>();

            queryParams[SF_QUERY_SESSION_DELETE] = "true";
            queryParams[SF_QUERY_REQUEST_ID]     = Guid.NewGuid().ToString();

            SFRestRequest closeSessionRequest = new SFRestRequest
            {
                uri = BuildUri(SF_SESSION_PATH, queryParams),
                authorizationToken = string.Format(SF_AUTHORIZATION_SNOWFLAKE_FMT, sessionToken)
            };

            var response = restRequest.Post <NullDataResponse>(closeSessionRequest);

            if (!response.success)
            {
                logger.Warn($"Failed to delete session, error ignored. Code: {response.code} Message: {response.message}");
            }
        }
コード例 #10
0
        internal void Cancel()
        {
            SFRestRequest request = BuildCancelQueryRequest();

            if (request == null)
            {
                return;
            }

            var response = _restRequester.Post <NullDataResponse>(request);

            if (response.success)
            {
                logger.Info("Query cancellation succeed");
            }
            else
            {
                logger.Warn("Query cancellation failed.");
            }
        }
コード例 #11
0
        internal void renewSession()
        {
            UriBuilder uriBuilder = new UriBuilder();

            uriBuilder.Scheme = properties[SFSessionProperty.SCHEME];
            uriBuilder.Host   = properties[SFSessionProperty.HOST];
            uriBuilder.Port   = Int32.Parse(properties[SFSessionProperty.PORT]);
            uriBuilder.Path   = SF_TOKEN_REQUEST_PATH;

            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString[SF_QUERY_REQUEST_ID] = Guid.NewGuid().ToString();
            uriBuilder.Query = queryString.ToString();

            RenewSessionRequest postBody = new RenewSessionRequest()
            {
                oldSessionToken = this.sessionToken,
                requestType     = "RENEW"
            };

            SFRestRequest renewSessionRequest = new SFRestRequest();

            renewSessionRequest.jsonBody             = postBody;
            renewSessionRequest.uri                  = uriBuilder.Uri;
            renewSessionRequest.authorizationToken   = String.Format(SF_AUTHORIZATION_SNOWFLAKE_FMT, masterToken);
            renewSessionRequest.sfRestRequestTimeout = -1;

            JObject          response             = restRequest.post(renewSessionRequest);
            NullDataResponse sessionRenewResponse = response.ToObject <NullDataResponse>();

            if (!sessionRenewResponse.success)
            {
                SnowflakeDbException e = new SnowflakeDbException("",
                                                                  sessionRenewResponse.code, sessionRenewResponse.message, "");
                logger.Error("Renew session failed", e);
                throw e;
            }
        }
コード例 #12
0
        internal void Cancel()
        {
            SFRestRequest request = BuildCancelQueryRequest();

            if (request == null)
            {
                return;
            }

            var response = _restRequest.Post <NullDataResponse>(request);

            if (response.success)
            {
                logger.Info("Query cancellation succeed");
            }
            else
            {
                SnowflakeDbException e = new SnowflakeDbException(
                    "", response.code, response.message, "");
                logger.Error("Query cancellation failed.", e);
                throw e;
            }
        }
コード例 #13
0
        public JObject post(SFRestRequest postRequest)
        {
            var                     json                    = JsonConvert.SerializeObject(postRequest.jsonBody);
            HttpContent             httpContent             = new StringContent(json);
            CancellationTokenSource cancellationTokenSource =
                new CancellationTokenSource(postRequest.sfRestRequestTimeout);

            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, postRequest.uri);

            message.Properties["TIMEOUT_PER_HTTP_REQUEST"] = postRequest.httpRequestTimeout;

            message.Content = httpContent;
            message.Content.Headers.ContentType = applicationJson;
            message.Headers.Add(SF_AUTHORIZATION_HEADER, postRequest.authorizationToken);
            message.Headers.Accept.Add(applicationSnowflake);

            var responseContent = sendRequest(message, cancellationTokenSource.Token).Content;

            var jsonString = responseContent.ReadAsStringAsync();

            jsonString.Wait();

            return(JObject.Parse(jsonString.Result));
        }
コード例 #14
0
 public T Get <T>(SFRestRequest request)
 {
     //Run synchronous in a new thread-pool task.
     return(Task.Run(async() => await GetAsync <T>(request, CancellationToken.None)).Result);
 }
コード例 #15
0
        internal SFBaseResultSet execute(string sql, Dictionary <string, BindingDTO> bindings, bool describeOnly)
        {
            if (requestId != null)
            {
                logger.Info("Another query is running.");
                throw new SnowflakeDbException(SFError.STATEMENT_ALREADY_RUNNING_QUERY);
            }
            this.requestId = Guid.NewGuid().ToString();


            UriBuilder uriBuilder = new UriBuilder();

            uriBuilder.Scheme = sfSession.properties[SFSessionProperty.SCHEME];
            uriBuilder.Host   = sfSession.properties[SFSessionProperty.HOST];
            uriBuilder.Port   = Int32.Parse(sfSession.properties[SFSessionProperty.PORT]);
            uriBuilder.Path   = SF_QUERY_PATH;

            var queryString = HttpUtility.ParseQueryString(string.Empty);

            queryString[SF_QUERY_REQUEST_ID] = requestId;
            uriBuilder.Query = queryString.ToString();

            QueryRequest postBody = new QueryRequest()
            {
                sqlText           = sql,
                parameterBindings = bindings,
                describeOnly      = describeOnly,
            };

            SFRestRequest queryRequest = new SFRestRequest();

            queryRequest.uri = uriBuilder.Uri;
            queryRequest.authorizationToken = String.Format(SF_AUTHORIZATION_SNOWFLAKE_FMT, sfSession.sessionToken);
            queryRequest.jsonBody           = postBody;
            queryRequest.httpRequestTimeout = -1;

            try
            {
                JObject           rawResponse  = restRequest.post(queryRequest);
                QueryExecResponse execResponse = rawResponse.ToObject <QueryExecResponse>();

                if (execResponse.code == SF_SESSION_EXPIRED_CODE)
                {
                    sfSession.renewSession();
                    this.execute(sql, bindings, describeOnly);
                }
                else if (execResponse.code == SF_QUERY_IN_PROGRESS ||
                         execResponse.code == SF_QUERY_IN_PROGRESS_ASYNC)
                {
                    logger.Info("Query execution in progress.");
                    bool   isSessionRenewed = false;
                    string getResultUrl     = null;
                    while (execResponse.code == SF_QUERY_IN_PROGRESS ||
                           execResponse.code == SF_QUERY_IN_PROGRESS_ASYNC)
                    {
                        if (!isSessionRenewed)
                        {
                            getResultUrl = execResponse.data.getResultUrl;
                        }

                        UriBuilder getResultUriBuilder = new UriBuilder();
                        getResultUriBuilder.Scheme = sfSession.properties[SFSessionProperty.SCHEME];
                        getResultUriBuilder.Host   = sfSession.properties[SFSessionProperty.HOST];
                        getResultUriBuilder.Port   = Int32.Parse(sfSession.properties[SFSessionProperty.PORT]);
                        getResultUriBuilder.Path   = getResultUrl;

                        SFRestRequest getResultRequest = new SFRestRequest()
                        {
                            uri = getResultUriBuilder.Uri,
                            authorizationToken = String.Format(SF_AUTHORIZATION_SNOWFLAKE_FMT, sfSession.sessionToken)
                        };
                        getResultRequest.httpRequestTimeout = -1;

                        execResponse = null;
                        execResponse = restRequest.get(getResultRequest).ToObject <QueryExecResponse>();

                        if (execResponse.code == SF_SESSION_EXPIRED_CODE)
                        {
                            logger.Info("Ping pong request failed with session expired, trying to renew the session.");
                            sfSession.renewSession();
                            isSessionRenewed = true;
                        }
                        else
                        {
                            isSessionRenewed = false;
                        }
                    }
                }

                if (execResponse.success)
                {
                    return(new SFResultSet(execResponse.data, this));
                }
                else
                {
                    SnowflakeDbException e = new SnowflakeDbException(
                        execResponse.data.sqlState, execResponse.code, execResponse.message,
                        execResponse.data.queryId);
                    logger.Error("Query execution failed.", e);
                    throw e;
                }
            }
            finally
            {
                this.requestId = null;
            }
        }