Esempio n. 1
0
        /// <summary>
        /// 获取公共的键值对配置
        /// </summary>
        public async static Task <string> GetRedisConfig()
        {
            foreach (var url in oauthUrls)
            {
                using (var client = HttpClientProvider.CreateHttpClient(url))
                {
                    try
                    {
                        if (!await PrepareAccessToken(client))
                        {
                            continue;
                        }
                        var resp = await client.GetAsync("/api/Config/GetRedisConfig");

                        if (resp.IsSuccessStatusCode)
                        {
                            var result = await resp.Content.ReadAsStringAsync();

                            if (!string.IsNullOrWhiteSpace(result))
                            {
                                return(result);
                            }
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            return(null);
        }
Esempio n. 2
0
        async System.Threading.Tasks.Task <Document> DownloadAndOpenFileAsync(StackFrame frame, int line, SourceLink sourceLink)
        {
            var pm = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor(
                GettextCatalog.GetString("Downloading {0}", sourceLink.Uri),
                Stock.StatusDownload,
                true
                );

            Document doc = null;

            try {
                var downloadLocation = sourceLink.GetDownloadLocation(symbolCachePath);
                Directory.CreateDirectory(Path.GetDirectoryName(downloadLocation));
                DocumentRegistry.SkipNextChange(downloadLocation);
                var client = HttpClientProvider.CreateHttpClient(sourceLink.Uri);
                using (var stream = await client.GetStreamAsync(sourceLink.Uri).ConfigureAwait(false))
                    using (var fs = new FileStream(downloadLocation, FileMode.Create)) {
                        await stream.CopyToAsync(fs).ConfigureAwait(false);
                    }
                frame.UpdateSourceFile(downloadLocation);
                doc = await Runtime.RunInMainThread(() => IdeApp.Workbench.OpenDocument(downloadLocation, null, line, 1, OpenDocumentOptions.Debugger));
            } catch (Exception ex) {
                LoggingService.LogInternalError("Error downloading SourceLink file", ex);
            } finally {
                pm.Dispose();
            }
            return(doc);
        }
Esempio n. 3
0
        protected override SmartSubtransportStream Action(string url, GitSmartSubtransportAction action)
        {
            string postContentType = null;
            string serviceUri;

            switch (action)
            {
            case GitSmartSubtransportAction.UploadPackList:
                serviceUri = url + "/info/refs?service=git-upload-pack";
                break;

            case GitSmartSubtransportAction.UploadPack:
                serviceUri      = url + "/git-upload-pack";
                postContentType = "application/x-git-upload-pack-request";
                break;

            case GitSmartSubtransportAction.ReceivePackList:
                serviceUri = url + "/info/refs?service=git-receive-pack";
                break;

            case GitSmartSubtransportAction.ReceivePack:
                serviceUri      = url + "/git-receive-pack";
                postContentType = "application/x-git-receive-pack-request";
                break;

            default:
                throw new InvalidOperationException();
            }

            // Grab the credentials from the user.
            var httpClient = HttpClientProvider.CreateHttpClient(serviceUri);

            httpClient.Timeout = TimeSpan.FromMinutes(1.0);

            var res = httpClient.GetAsync(serviceUri).Result;

            if (res.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                var cred = (UsernamePasswordCredentials)GitCredentials.TryGet(url, "", SupportedCredentialTypes.UsernamePassword, GitCredentialsType.Tfs);

                httpClient = new HttpClient(new HttpClientHandler {
                    Credentials = new System.Net.NetworkCredential(cred.Username, cred.Password)
                })
                {
                    Timeout = TimeSpan.FromMinutes(1.0),
                };
                res = httpClient.GetAsync(serviceUri).Result;
                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    GitCredentials.StoreCredentials(GitCredentialsType.Tfs);
                }
            }

            return(new TfsSmartSubtransportStream(this)
            {
                HttpClient = httpClient,
                ServiceUri = new Uri(serviceUri),
                PostContentType = postContentType,
            });
        }
Esempio n. 4
0
        /// <summary>
        /// 获取公共的键值对配置
        /// </summary>
        public async static Task <Dictionary <string, string> > GetKeyValues()
        {
            foreach (var url in oauthUrls)
            {
                using (var client = HttpClientProvider.CreateHttpClient(url))
                {
                    try
                    {
                        if (!await PrepareAccessToken(client))
                        {
                            continue;
                        }
                        var resp = await client.GetAsync("/api/Config/GetKeyValues");

                        if (resp.IsSuccessStatusCode)
                        {
                            var result = await resp.Content.ReadAsAsync <Dictionary <string, string> >();

                            if (result != null && result.Count > 0)
                            {
                                return(result);
                            }
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            return(new Dictionary <string, string>());
        }
        public static async Task LaunchBrowserAsync(string appUrl, string launchUrl, ExecutionTarget target, Task processTask)
        {
            launchUrl = launchUrl ?? "";
            //Check if launchUrl is valid absolute url and use it if it is...
            if (!Uri.TryCreate(launchUrl, UriKind.Absolute, out var launchUri) || launchUri.IsFile)
            {
                //Otherwise check if appUrl is valid absolute and launchUrl is relative then concat them...
                if (!Uri.TryCreate(appUrl, UriKind.Absolute, out var appUri) || appUri.IsFile)
                {
                    LoggingService.LogWarning("Failed to launch browser because invalid launch and app urls.");
                    return;
                }
                if (!Uri.TryCreate(launchUrl, UriKind.Relative, out launchUri))
                {
                    LoggingService.LogWarning("Failed to launch browser because invalid launch url.");
                    return;
                }
                launchUri = new Uri(appUri, launchUri);
            }

            //Try to connect every 50ms while process is running
            while (!processTask.IsCompleted)
            {
                await Task.Delay(50).ConfigureAwait(false);

                using (var httpClient = HttpClientProvider.CreateHttpClient(launchUri.AbsoluteUri)) {
                    try {
                        using (var response = await httpClient.GetAsync(launchUri.AbsoluteUri, System.Net.Http.HttpCompletionOption.ResponseHeadersRead)) {
                            await Task.Delay(1000).ConfigureAwait(false);

                            break;
                        }
                    } catch {
                    }
                }
            }

            if (processTask.IsCompleted)
            {
                LoggingService.LogDebug("Failed to launch browser because process exited before server started listening.");
                return;
            }

            // Process is still alive hence we succesfully connected inside loop to web server, launch browser
            var aspNetCoreTarget = target as AspNetCoreExecutionTarget;

            if (aspNetCoreTarget != null && !aspNetCoreTarget.DesktopApplication.IsDefault)
            {
                aspNetCoreTarget.DesktopApplication.Launch(launchUri.AbsoluteUri);
            }
            else
            {
                IdeServices.DesktopService.ShowUrl(launchUri.AbsoluteUri);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Calls the REST api with GET method.
        /// </summary>
        /// <param name="url">The url for the REST api.</param>
        /// <param name="acceptType">The accept type string.</param>
        /// <param name="requestHeaders">The request headers for the REST api.</param>
        /// <returns>The http response having status code and content.</returns>
        private static RESTFulResponseInternal GetInternal(string url, string acceptType, Dictionary <string, string> requestHeaders)
        {
            // Create http client with auto disposition
            using (var httpClient = HttpClientProvider.CreateHttpClient(requestHeaders))
            {
                // Add 'Accept' header in the request
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(acceptType));

                // Call the REST api with GET method
                var result = httpClient.GetAsync(url).Result;

                // Get the response content
                var responseContent = result.Content.ReadAsStringAsync().Result;

                // Return the RESTFul response
                return(new RESTFulResponseInternal(result.StatusCode, result.IsSuccessStatusCode, responseContent));
            }
        }
Esempio n. 7
0
        /// <summary>
        /// 内部方法
        /// </summary>
        private async static Task <string> GetConnectionStrInner(string oauthUrl, string project, string deKey)
        {
            try
            {
                var client = HttpClientProvider.CreateHttpClient(oauthUrl);
                var resp   = await client.GetAsync(string.Format("/api/Config/GetConStr/?project={0}", project));

                if (resp.IsSuccessStatusCode)
                {
                    var resultData = resp.Content.ReadAsByteArrayAsync().Result;
                    if (resultData != null && resultData.Length > 0)
                    {
                        var data = RSAHelper.DecryptData(deKey, resultData);
                        return(Encoding.UTF8.GetString(data));
                    }
                }
            }
            catch { }
            return(null);
        }
Esempio n. 8
0
        /// <summary>
        /// 短信发送
        /// </summary>
        public static bool Send(string msg, params string[] phoneList)
        {
            if (string.IsNullOrWhiteSpace(msg) || phoneList == null || phoneList.Length == 0)
            {
                return(false);
            }

            var sendUrl  = ConfigurationManager.AppSettings["SmsSendUrl"] ?? "";
            var userName = ConfigurationManager.AppSettings["UserName"] ?? "";

            if (string.IsNullOrWhiteSpace(sendUrl) || string.IsNullOrWhiteSpace(userName))
            {
                return(false);
            }

            var client = HttpClientProvider.CreateHttpClient(sendUrl);
            var resp   = client.GetAsync(string.Format("?username={0}&mobile={1}&content={2}&sendtime=", userName, string.Join(",", phoneList), msg)).Result;

            return(resp.IsSuccessStatusCode && resp.Content.ReadAsStringAsync().Result.Contains("ok"));
        }
Esempio n. 9
0
        public static async Task <ScaffoldingConfig> LoadFromJsonAsync()
        {
            if (fetchedConfig == null)
            {
                Stream stream;
                using var httpClient = HttpClientProvider.CreateHttpClient(packageVersionsUrl);
                httpClient.Timeout   = TimeSpan.FromSeconds(2);

                try {
                    stream = await httpClient.GetStreamAsync(packageVersionsUrl);
                } catch {
                    // fallback to embedded resource
                    stream = typeof(ScaffoldingConfig).Assembly.GetManifestResourceStream("ScaffoldingPackageVersions.json");
                }

                var serializer = new JsonSerializer();

                using var sr             = new StreamReader(stream);
                using var jsonTextReader = new JsonTextReader(sr);
                return(serializer.Deserialize <ScaffoldingConfig> (jsonTextReader));
            }
            return(fetchedConfig);
        }
Esempio n. 10
0
        /// <summary>
        /// Calls the REST api with PUT method.
        /// </summary>
        /// <param name="url">The url for the REST api.</param>
        /// <param name="acceptType">The accept type string.</param>
        /// <param name="requestHeaders">The request headers for the REST api.</param>
        /// <returns>The http response having status code and content.</returns>
        private static RESTFulResponseInternal PutInternal(string url, object content, string contentType, Dictionary <string, string> requestHeaders)
        {
            // Create http client with auto disposition
            using (var httpClient = HttpClientProvider.CreateHttpClient(requestHeaders))
            {
                // Add 'Accept' header in the request
                if (requestHeaders != null && requestHeaders.All(rh => rh.Key != HttpRequestHeader.Accept.ToString()))
                {
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(contentType));
                }

                // Build the http content
                HttpContent httpContent = null;

                if (contentType.ToLower().Contains("form"))
                {
                    httpContent = new FormUrlEncodedContent(content as Dictionary <string, string>);
                }
                else if (contentType.ToLower().Contains("json"))
                {
                    var jsonContent = content is string?content.ToString() : ContentProvider.GetJsonContent(content);

                    httpContent = new StringContent(jsonContent, Encoding.UTF8, contentType);
                }

                // Call the REST api with POST method
                var result = httpClient.PutAsync(url, httpContent).Result;

                // Get the response content
                var responseContent = result.Content.ReadAsStringAsync().Result;

                // Return the RESTFul response
                return(new RESTFulResponseInternal(result.StatusCode, result.IsSuccessStatusCode, responseContent));
            }
        }
Esempio n. 11
0
        public static async Task <bool> UpdateDownloadedCacheFile(string url, string cacheFile,
                                                                  Func <Stream, bool> validateDownload = null, CancellationToken ct = default(CancellationToken))
        {
            bool       deleteTempFile = true;
            var        tempFile       = cacheFile + ".temp";
            HttpClient client         = null;

            try {
                client = HttpClientProvider.CreateHttpClient(url);
                //check to see if the online file has been modified since it was last downloaded
                var localNewsXml = new FileInfo(cacheFile);
                if (localNewsXml.Exists)
                {
                    client.DefaultRequestHeaders.IfModifiedSince = localNewsXml.LastWriteTime;
                }
                using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false)) {
                    ct.ThrowIfCancellationRequested();

                    //TODO: limit this size in case open wifi hotspots provide junk data
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (var fs = File.Create(tempFile))
                            await response.Content.CopyToAsync(fs);
                    }
                    else if (response.StatusCode == HttpStatusCode.NotModified)
                    {
                        return(false);
                    }
                    else
                    {
                        LoggingService.LogWarning("FileService.UpdateDownloadedCacheFile. Unexpected status code {0}", response.StatusCode);
                        return(false);
                    }
                }

                //check the document is valid, might get bad ones from wifi hotspots etc
                if (validateDownload != null)
                {
                    ct.ThrowIfCancellationRequested();

                    using (var f = File.OpenRead(tempFile)) {
                        bool validated;
                        try {
                            validated = validateDownload(f);
                        } catch (Exception ex) {
                            throw new Exception("Failed to validate downloaded file", ex);
                        }
                        if (!validated)
                        {
                            throw new Exception("Failed to validate downloaded file");
                        }
                    }
                }

                ct.ThrowIfCancellationRequested();

                SystemRename(tempFile, cacheFile);
                deleteTempFile = false;
                return(true);
            } finally {
                client?.Dispose();
                if (deleteTempFile)
                {
                    try {
                        File.Delete(tempFile);
                    } catch (Exception ex) {
                        LoggingService.LogError("Failed to delete temp download file", ex);
                    }
                }
            }
        }
Esempio n. 12
0
        void Load()
        {
            string tempPath = cachePath + ".tmp";

            LoadFromDisk(cachePath, false);

            var finfo = new FileInfo(cachePath);

            var client = HttpClientProvider.CreateHttpClient(url);

            if (finfo.Exists)
            {
                client.DefaultRequestHeaders.IfModifiedSince = finfo.LastWriteTime;
            }
            client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ContinueWith(async t => {
                try {
                    using (var response = t.Result) {
                        // If the errorcode is NotModified the file we cached on disk is still the latest one.
                        if (t.Result.StatusCode == HttpStatusCode.NotModified)
                        {
                            Cleanup();
                            return;
                        }
                        //if 404, there is no gravatar for the user
                        if (t.Result.StatusCode == HttpStatusCode.NotFound)
                        {
                            image = null;
                            Cleanup();
                            return;
                        }

                        finfo.Directory.Create();

                        // Copy out the new file and reload it
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            using (var tempFile = File.Create(tempPath)) {
                                await response.Content.CopyToAsync(tempFile);
                            }
                            FileService.SystemRename(tempPath, cachePath);
                        }
                        LoadFromDisk(cachePath, true);
                    }
                } catch (Exception ex) {
                    var aex = ex as AggregateException;
                    if (aex != null)
                    {
                        ex = aex.Flatten().InnerException;
                    }
                    var wex = ex?.InnerException as WebException;
                    if (wex != null && wex.Status.IsCannotReachInternetError())
                    {
                        LoggingService.LogWarning("Gravatar service could not be reached.");
                    }
                    else
                    {
                        LoggingService.LogError("Error in Gravatar downloader.", ex);
                    }
                    Cleanup();
                } finally {
                    try {
                        client.Dispose();
                        if (File.Exists(tempPath))
                        {
                            File.Delete(tempPath);
                        }
                    } catch (Exception ex) {
                        LoggingService.LogError("Error deleting Gravatar temp file.", ex);
                    }
                }
            });
        }