示例#1
0
        /// <summary>
        /// Opens this instance.
        /// </summary>
        /// <exception cref="ArgumentNullException"> if a required parameter extracted from connection string is missing.
        /// </exception>
        /// <exception cref="AceQLException"> if any other Exception occurs.
        /// </exception>
        internal async Task OpenAsync()
        {
            string sessionId;

            try
            {
                ConnectionStringDecoder connectionStringDecoder = new ConnectionStringDecoder();
                connectionStringDecoder.Decode(connectionString);
                this.server             = connectionStringDecoder.Server;
                this.database           = connectionStringDecoder.Database;
                this.username           = connectionStringDecoder.Username;
                this.password           = connectionStringDecoder.Password;
                sessionId               = connectionStringDecoder.SessionId;
                this.proxyUri           = connectionStringDecoder.ProxyUri;
                this.proxyCredentials   = connectionStringDecoder.ProxyCredentials;
                this.useCredentialCache = connectionStringDecoder.UseCredentialCache;
                this.timeout            = connectionStringDecoder.Timeout;
                this.enableDefaultSystemAuthentication = connectionStringDecoder.EnableDefaultSystemAuthentication;

                if (connectionStringDecoder.EnableTrace)
                {
                    simpleTracer.SetTraceOn(true);
                }

                await simpleTracer.TraceAsync("connectionString: " + connectionString).ConfigureAwait(false);

                await simpleTracer.TraceAsync("DecodeConnectionString() done!").ConfigureAwait(false);

                if (credential != null)
                {
                    username = credential.Username;

                    if (credential.Password != null)
                    {
                        password = credential.Password;
                    }

                    if (credential.SessionId != null)
                    {
                        sessionId = credential.SessionId;
                    }
                }

                if (server == null)
                {
                    throw new ArgumentNullException("Server keyword not found in connection string.");
                }

                if (password == null && sessionId == null)
                {
                    throw new ArgumentNullException("Password keyword or SessionId keyword not found in connection string or AceQLCredential not set");
                }

                if (database == null)
                {
                    throw new ArgumentNullException("Database keyword not found in connection string.");
                }

                this.username = username ?? throw new ArgumentNullException("Username keyword not found in connection string or AceQLCredential not set.");

                // Create the HttpManager instance
                this.httpManager = new HttpManager(proxyUri, proxyCredentials, timeout, enableDefaultSystemAuthentication);
                this.httpManager.SetSimpleTracer(simpleTracer);

                Debug("httpManager.Proxy: " + httpManager.Proxy);

                UserLoginStore userLoginStore = new UserLoginStore(server, username,
                                                                   database);

                if (sessionId != null)
                {
                    userLoginStore.SetSessionId(sessionId);
                }

                if (userLoginStore.IsAlreadyLogged())
                {
                    await simpleTracer.TraceAsync("Get a new connection with get_connection").ConfigureAwait(false);

                    sessionId = userLoginStore.GetSessionId();

                    String theUrl = server + "/session/" + sessionId + "/get_connection";
                    String result = await httpManager.CallWithGetAsync(theUrl).ConfigureAwait(false);

                    await simpleTracer.TraceAsync("result: " + result).ConfigureAwait(false);

                    ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result,
                                                                       HttpStatusCode);

                    if (!resultAnalyzer.IsStatusOk())
                    {
                        throw new AceQLException(resultAnalyzer.GetErrorMessage(),
                                                 resultAnalyzer.GetErrorId(),
                                                 resultAnalyzer.GetStackTrace(),
                                                 HttpStatusCode);
                    }

                    String connectionId = resultAnalyzer.GetValue("connection_id");
                    await simpleTracer.TraceAsync("Ok. New Connection created: " + connectionId).ConfigureAwait(false);

                    this.url = server + "/session/" + sessionId + "/connection/"
                               + connectionId + "/";
                }
                else
                {
                    await DummyGetCallForProxyAuthentication().ConfigureAwait(false);

                    String theUrl = server + "/database/" + database + "/username/" + username + "/login";
                    ConsoleEmul.WriteLine("theUrl: " + theUrl);

                    Dictionary <string, string> parametersMap = new Dictionary <string, string>
                    {
                        { "password", new String(password) },
                        { "client_version", VersionValues.VERSION }
                    };

                    await simpleTracer.TraceAsync("Before CallWithPostAsyncReturnString: " + theUrl);

                    String result = await httpManager.CallWithPostAsyncReturnString(new Uri(theUrl), parametersMap).ConfigureAwait(false);

                    ConsoleEmul.WriteLine("result: " + result);
                    await simpleTracer.TraceAsync("result: " + result).ConfigureAwait(false);

                    ResultAnalyzer resultAnalyzer = new ResultAnalyzer(result, HttpStatusCode);
                    if (!resultAnalyzer.IsStatusOk())
                    {
                        throw new AceQLException(resultAnalyzer.GetErrorMessage(),
                                                 resultAnalyzer.GetErrorId(),
                                                 resultAnalyzer.GetStackTrace(),
                                                 HttpStatusCode);
                    }

                    String theSessionId    = resultAnalyzer.GetValue("session_id");
                    String theConnectionId = resultAnalyzer.GetValue("connection_id");

                    this.url = server + "/session/" + theSessionId + "/connection/" + theConnectionId + "/";
                    userLoginStore.SetSessionId(theSessionId);
                    await simpleTracer.TraceAsync("OpenAsync url: " + this.url).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                await simpleTracer.TraceAsync(exception.ToString()).ConfigureAwait(false);

                if (exception.GetType() == typeof(AceQLException))
                {
                    throw;
                }
                else
                {
                    throw new AceQLException(exception.Message, 0, exception, HttpStatusCode);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Uploads a filePath using a blob reference.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="proxyUri"></param>
        /// <param name="credentials"></param>
        /// <param name="timeout"></param>
        /// <param name="enableDefaultSystemAuthentication"></param>
        /// <param name="blobId"></param>
        /// <param name="stream"></param>
        /// <param name="totalLength"></param>
        /// <param name="progressIndicator"></param>
        /// <param name="cancellationToken"></param>
        /// <param name="useCancellationToken"></param>
        /// <param name="requestHeaders">The request headers to add to all requests.</param>
        /// <returns></returns>
        internal async Task <HttpResponseMessage> UploadAsync(String url, String proxyUri, ICredentials credentials,
                                                              int timeout, bool enableDefaultSystemAuthentication, String blobId, Stream stream, long totalLength,
                                                              AceQLProgressIndicator progressIndicator, CancellationToken cancellationToken, bool useCancellationToken, Dictionary <string, string> requestHeaders)
        {
            HttpClientHandler      handler = HttpClientHandlerBuilderNew.Build(proxyUri, credentials, enableDefaultSystemAuthentication);
            ProgressMessageHandler processMessageHander = new ProgressMessageHandler(handler);
            HttpClient             httpClient           = new HttpClient(processMessageHander);

            HttpManager.AddRequestHeaders(httpClient, requestHeaders);

            if (timeout != 0)
            {
                long nanoseconds = 1000000 * timeout;
                httpClient.Timeout = new TimeSpan(nanoseconds / 100);
            }

            processMessageHander.HttpSendProgress += (sender, e) =>
            {
                int num = e.ProgressPercentage;
                this.tempLen += e.BytesTransferred;

                if (progressIndicator != null)
                {
                    if (totalLength > 0 && tempLen > totalLength / 100)
                    {
                        tempLen = 0;
                    }
                    int cpt = progressIndicator.Percent;
                    cpt++;
                    progressIndicator.SetValue(Math.Min(99, cpt));

                    if (DEBUG)
                    {
                        ConsoleEmul.WriteLine(DateTime.Now + " progressHolder.Progress: " + progressIndicator.Percent);
                    }
                }
                else
                {
                    if (DEBUG)
                    {
                        ConsoleEmul.WriteLine(DateTime.Now + " num: " + num);
                    }
                }
            };

            StringContent stringContentBlobId = new StringContent(blobId);

            try
            {
                var multipart = new MultipartFormDataContent();
                multipart.Add(stringContentBlobId, '"' + "blob_id" + '"');
                multipart.Add(new StreamContent(stream), '"' + "filePath" + '"', '"' + blobId + '"');

                if (DEBUG)
                {
                    ConsoleEmul.WriteLine();
                    ConsoleEmul.WriteLine("url     : " + url);
                    ConsoleEmul.WriteLine("blob_id : " + blobId);
                }

                HttpResponseMessage response = null;

                if (!useCancellationToken)
                {
                    response = await httpClient.PostAsync(url, multipart).ConfigureAwait(false);
                }
                else
                {
                    response = await httpClient.PostAsync(url, multipart, cancellationToken).ConfigureAwait(false);
                }

                // Allows a retry for 407, because can happen time to time with Web proxies
                if (response.StatusCode.Equals(HttpStatusCode.ProxyAuthenticationRequired))
                {
                    while (proxyAuthenticationCallCount < HttpRetryManager.ProxyAuthenticationCallLimit)
                    {
                        proxyAuthenticationCallCount++;
                        if (!useCancellationToken)
                        {
                            response = await httpClient.PostAsync(url, multipart).ConfigureAwait(false);
                        }
                        else
                        {
                            response = await httpClient.PostAsync(url, multipart, cancellationToken).ConfigureAwait(false);
                        }

                        if (!response.StatusCode.Equals(HttpStatusCode.ProxyAuthenticationRequired))
                        {
                            proxyAuthenticationCallCount = 0;
                            break;
                        }
                    }
                }

                if (progressIndicator != null)
                {
                    progressIndicator.SetValue(100);
                }

                return(response);
            }
            finally
            {
                stream.Dispose();
                httpClient.Dispose();
            }
        }