/// <summary>
        ///     Download one Cocoapods package and extract it to the target directory.
        /// </summary>
        /// <param name="purl"> Package URL of the package to download. </param>
        /// <returns> n/a </returns>
        public override async Task <IEnumerable <string> > DownloadVersionAsync(PackageURL purl, bool doExtract, bool cached = false)
        {
            Logger.Trace("DownloadVersion {0}", purl?.ToString());

            string?       packageName     = purl?.Name;
            string?       packageVersion  = purl?.Version;
            string?       fileName        = purl?.ToStringFilename();
            List <string> downloadedPaths = new();

            if (string.IsNullOrWhiteSpace(packageName) || string.IsNullOrWhiteSpace(packageVersion) || string.IsNullOrWhiteSpace(fileName))
            {
                Logger.Debug("Error with 'purl' argument. Unable to download [{0} {1}] @ {2}. Both must be defined.", packageName, packageVersion, fileName);
                return(downloadedPaths);
            }

            HttpClient httpClient = CreateHttpClient();
            string     prefix     = GetCocoapodsPrefix(packageName);

            System.Text.Json.JsonDocument podspec = await GetJsonCache(httpClient, $"{ENV_COCOAPODS_SPECS_RAW_ENDPOINT}/Specs/{prefix}/{packageName}/{packageVersion}/{packageName}.podspec.json");

            if (podspec.RootElement.TryGetProperty("source", out System.Text.Json.JsonElement source))
            {
                string?url = null;
                if (source.TryGetProperty("git", out System.Text.Json.JsonElement sourceGit) &&
                    source.TryGetProperty("tag", out System.Text.Json.JsonElement sourceTag))
                {
                    string?sourceGitString = sourceGit.GetString();
                    string?sourceTagString = sourceTag.GetString();

                    if (!string.IsNullOrWhiteSpace(sourceGitString) && sourceGitString.EndsWith(".git"))
                    {
                        sourceGitString = sourceGitString[0..^ 4];
示例#2
0
        /// <summary>
        /// 设置请求正文。
        /// </summary>
        /// <param name="httpRequest"></param>
        /// <param name="jsonDoc"></param>
        /// <returns></returns>
        public static IHttpRequest SetBody(this IHttpRequest httpRequest, System.Text.Json.JsonDocument jsonDoc)
        {
            if (jsonDoc == null)
            {
                return(SetBody(httpRequest, string.Empty));
            }

            return(SetBody(httpRequest, jsonDoc?.RootElement.ToString()));
        }
示例#3
0
        /// <summary>
        /// 设置请求正文。
        /// </summary>
        /// <param name="httpRequest"></param>
        /// <param name="jsonDoc"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static IHttpRequest SetBody(this IHttpRequest httpRequest, System.Text.Json.JsonDocument jsonDoc, System.Text.Json.JsonSerializerOptions settings)
        {
            if (jsonDoc == null)
            {
                return(SetBody(httpRequest, string.Empty));
            }

            return(SetBody(httpRequest, System.Text.Json.JsonSerializer.Serialize(jsonDoc.RootElement, settings ?? JsonHelper.DefaultSystemTextJsonSerializerSettings)));
        }
示例#4
0
        public static Scene DeserializeJson(string json)
        {
            Scene scene = new Scene();

            JsonSerializer serializer = new JsonSerializer(CreateSettings(scene));

            using (System.Text.Json.JsonDocument reader = System.Text.Json.JsonDocument.Parse(json))
            {
                serializer.Deserialize(reader.RootElement, typeof(Scene));
                return(scene);
            }
        }
示例#5
0
        public async Task UpdateClientDataToDB()
        {
            _context.Database.Migrate();

            string clientString  = string.Empty;
            string scope         = string.Empty;
            string secret        = string.Empty;
            var    checkEnvExist = Environment.GetEnvironmentVariable("SECRET");

            if (string.IsNullOrEmpty(checkEnvExist))
            {
                var r = await _client.GetAsync("http://localhost:3500/v1.0/secrets/kubernetes/opendatasecrets");

                System.Text.Json.JsonDocument jd = System.Text.Json.JsonDocument.Parse(await r.Content.ReadAsStringAsync());
                clientString = jd.RootElement.GetProperty("client").ToString();
                scope        = jd.RootElement.GetProperty("scope").ToString();
                secret       = jd.RootElement.GetProperty("secret").ToString();
                _logger.LogError(await r.Content.ReadAsStringAsync());
            }
            else
            {
                clientString = Environment.GetEnvironmentVariable("CLIENT") !;
                scope        = Environment.GetEnvironmentVariable("SCOPE") !;
                secret       = Environment.GetEnvironmentVariable("SECRET") !;
            }
            _logger.LogInformation(System.Text.Json.JsonSerializer.Serialize(_context.Clients.ToList()));
            if (!_context.Clients.Any())
            {
                var NewClients = new Client
                {
                    ClientId             = clientString,
                    RequireRequestObject = true,

                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    ClientSecrets =
                    {
                        new Secret(secret.ToString().Sha256())
                    },
                    AllowedScopes = { scope }
                }.ToEntity();
                _context.Clients.Add(NewClients);
            }

            if (!_context.ApiScopes.Any())
            {
                _context.ApiScopes.Add(new ApiScope("api1", "My API").ToEntity());
            }
            _context.SaveChanges();
        }
        public async System.Threading.Tasks.Task OnComplete(string response)
        {
            System.Text.Json.JsonDocument doc = null;

            if (!string.IsNullOrEmpty(response))
            {
                try
                {
                    doc = System.Text.Json.JsonDocument.Parse(response);
                }
                catch (System.Text.Json.JsonException)
                {
                    //
                }
            }

            await Complete.InvokeAsync(new UploadCompleteEventArgs()
            {
                RawResponse = response, JsonResponse = doc
            });
        }
示例#7
0
        /// <inheritdoc />
        public override async Task <IEnumerable <string> > EnumerateVersionsAsync(PackageURL purl, bool useCache = true, bool includePrerelease = true)
        {
            Logger.Trace("EnumerateVersions {0}", purl?.ToString());
            if (purl == null)
            {
                return(new List <string>());
            }

            List <string> versionList = new();

            if (string.IsNullOrWhiteSpace(purl?.Namespace) || string.IsNullOrWhiteSpace(purl?.Name))
            {
                return(versionList);
            }

            string packageName = $"{purl?.Namespace}/{purl?.Name}";

            try
            {
                HttpClient httpClient = CreateHttpClient();

                System.Text.Json.JsonDocument doc = await GetJsonCache(httpClient, $"{ENV_COMPOSER_ENDPOINT}/p/{packageName}.json");

                foreach (System.Text.Json.JsonProperty topObject in doc.RootElement.GetProperty("packages").EnumerateObject())
                {
                    foreach (System.Text.Json.JsonProperty versionObject in topObject.Value.EnumerateObject())
                    {
                        Logger.Debug("Identified {0} version {1}.", packageName, versionObject.Name);
                        versionList.Add(versionObject.Name);
                    }
                }
                return(SortVersions(versionList.Distinct()));
            }
            catch (Exception ex)
            {
                Logger.Debug("Unable to enumerate versions: {0}", ex.Message);
                throw;
            }
        }
 public static bool TryParseValue(ref System.Text.Json.Utf8JsonReader reader, out System.Text.Json.JsonDocument document)
 {
     throw null;
 }
 public JsonData(System.Text.Json.JsonDocument jsonDocument)
 {
 }
示例#10
0
        private void UpdateBrowserIconPath(Theme newTheme)
        {
            try
            {
                string progId = GetRegistryValue(
                    "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
                    "ProgId");

                // The `?` argument doesn't work on opera, so we get the user's default search engine:
                if (progId.StartsWith("Opera", StringComparison.OrdinalIgnoreCase))
                {
                    // Opera user preferences file:
                    string prefFile;

                    if (progId.Contains("GX", StringComparison.OrdinalIgnoreCase))
                    {
                        _browserName = "Opera GX";
                        prefFile     = System.IO.File.ReadAllText($"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\Opera Software\\Opera GX Stable\\Preferences");
                    }
                    else
                    {
                        _browserName = "Opera";
                        prefFile     = System.IO.File.ReadAllText($"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\Opera Software\\Opera Stable\\Preferences");
                    }

                    // "default_search_provider_data" doesn't exist if the user hasn't searched for the first time,
                    // therefore we set `url` to opera's default search engine:
                    string url = "https://www.google.com/search?client=opera&q={0}&sourceid=opera";

                    using (System.Text.Json.JsonDocument doc = System.Text.Json.JsonDocument.Parse(prefFile))
                    {
                        if (doc.RootElement.TryGetProperty("default_search_provider_data", out var element))
                        {
                            if (element.TryGetProperty("template_url_data", out element))
                            {
                                if (element.TryGetProperty("url", out element))
                                {
                                    url = element.GetString();
                                }
                            }
                        }
                    }

                    url = url
                          .Replace("{searchTerms}", "{0}", StringComparison.Ordinal)
                          .Replace("{inputEncoding}", "UTF-8", StringComparison.Ordinal)
                          .Replace("{outputEncoding}", "UTF-8", StringComparison.Ordinal);

                    int startIndex = url.IndexOf('}', StringComparison.Ordinal) + 1;

                    // In case there are other url parameters (e.g. `&foo={bar}`), remove them:
                    for (int i = url.IndexOf("}", startIndex, StringComparison.Ordinal);
                         i != -1;
                         i = url.IndexOf("}", startIndex, StringComparison.Ordinal))
                    {
                        for (int j = i - 1; j > 0; --j)
                        {
                            if (url[j] == '&')
                            {
                                url = url.Remove(j, i - j + 1);
                                break;
                            }
                        }
                    }

                    _searchEngineUrl = url;
                }
                else
                {
                    string appName = GetRegistryValue($"HKEY_CLASSES_ROOT\\{progId}\\Application", "ApplicationName")
                                     ?? GetRegistryValue($"HKEY_CLASSES_ROOT\\{progId}", "FriendlyTypeName");

                    if (appName is null)
                    {
                        appName = Properties.Resources.plugin_browser;
                    }
                    else
                    {
                        // Handle indirect strings:
                        if (appName.StartsWith("@", StringComparison.Ordinal))
                        {
                            appName = GetIndirectString(appName);
                        }

                        appName = appName
                                  .Replace("URL", null, StringComparison.OrdinalIgnoreCase)
                                  .Replace("HTML", null, StringComparison.OrdinalIgnoreCase)
                                  .Replace("Document", null, StringComparison.OrdinalIgnoreCase)
                                  .TrimEnd();
                    }

                    _browserName = appName;

                    _searchEngineUrl = null;
                }

                var programLocation =

                    // Resolve App Icon (UWP)
                    GetRegistryValue(
                        "HKEY_CLASSES_ROOT\\" + progId + "\\Application",
                        "ApplicationIcon")

                    // Resolves default  file association icon (UWP + Normal)
                    ?? GetRegistryValue("HKEY_CLASSES_ROOT\\" + progId + "\\DefaultIcon", null);

                // "Handles 'Indirect Strings' (UWP programs)"
                // Using Ordinal since this is internal and used with a symbol
                if (programLocation.StartsWith("@", StringComparison.Ordinal))
                {
                    // Check if there's a postfix with contract-white/contrast-black icon is available and use that instead
                    string directProgramLocation = GetIndirectString(programLocation);
                    var    themeIcon             = newTheme == Theme.Light || newTheme == Theme.HighContrastWhite
                        ? "contrast-white"
                        : "contrast-black";
                    var extension          = Path.GetExtension(directProgramLocation);
                    var themedProgLocation =
                        $"{directProgramLocation.Substring(0, directProgramLocation.Length - extension.Length)}_{themeIcon}{extension}";
                    _browserIconPath = File.Exists(themedProgLocation)
                        ? themedProgLocation
                        : directProgramLocation;
                }
                else
                {
                    // Using Ordinal since this is internal and used with a symbol
                    var indexOfComma = programLocation.IndexOf(',', StringComparison.Ordinal);
                    _browserIconPath = indexOfComma > 0
                        ? programLocation.Substring(0, indexOfComma)
                        : programLocation;
                    _browserPath = _browserIconPath;
                }
            }
            catch (Exception e)
            {
                _browserIconPath = _defaultIconPath;
                Log.Exception("Exception when retrieving icon", e, GetType());
            }

            string GetRegistryValue(string registryLocation, string valueName)
            {
                return(Microsoft.Win32.Registry.GetValue(registryLocation, valueName, null) as string);
            }

            string GetIndirectString(string str)
            {
                var stringBuilder = new StringBuilder(128);

                if (NativeMethods.SHLoadIndirectString(
                        str,
                        stringBuilder,
                        (uint)stringBuilder.Capacity,
                        IntPtr.Zero)
                    == NativeMethods.Hresult.Ok)
                {
                    return(stringBuilder.ToString());
                }

                throw new Exception("Could not load indirect string.");
            }
        }
示例#11
0
        public string WithSystemTextJson()
        {
            System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(_jsonText);

            return(jsonDocument.RootElement.GetProperty("Glossary").GetProperty("GlossDiv").GetProperty("Title").GetRawText());
        }
示例#12
0
 public static Microsoft.AspNetCore.Authentication.OAuth.OAuthTokenResponse Success(System.Text.Json.JsonDocument response)
 {
     throw null;
 }
示例#13
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="dataAccess">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess dataAccess)
        {
            GH_ObjectWrapper objectWrapper = null;

            if (!dataAccess.GetData(0, ref objectWrapper) || objectWrapper == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            object value = objectWrapper.Value;

            if (value is IGH_Goo)
            {
                value = (value as dynamic).Value;
            }

            if (value == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            SAMObject result = null;

            string json = null;

            try
            {
                json = Core.LadybugTools.Convert.ToString(value);
            }
            catch
            {
            }

            if (!string.IsNullOrWhiteSpace(json))
            {
                System.Text.Json.JsonDocument jsonDocument = null;

                try
                {
                    jsonDocument = System.Text.Json.JsonDocument.Parse(json);
                }
                catch
                {
                    jsonDocument = null;
                }

                if (jsonDocument != null)
                {
                    try
                    {
                        IDdBaseModel ddBaseModel = Core.LadybugTools.Convert.ToHoneybee(value);

                        if (ddBaseModel != null)
                        {
                            result = Analytical.LadybugTools.Convert.ToSAM(ddBaseModel);
                        }
                    }
                    catch
                    {
                    }
                }
            }

            dataAccess.SetData(0, result);
            dataAccess.SetData(1, json);
        }
示例#14
0
        /// <summary>
        ///     Download one Composer (PHP) package and extract it to the target directory.
        /// </summary>
        /// <param name="purl"> Package URL of the package to download. </param>
        /// <returns> n/a </returns>
        public override async Task <IEnumerable <string> > DownloadVersionAsync(PackageURL purl, bool doExtract, bool cached = false)
        {
            Logger.Trace("DownloadVersion {0}", purl?.ToString());

            string?       packageNamespace = purl?.Namespace;
            string?       packageName      = purl?.Name;
            string?       packageVersion   = purl?.Version;
            List <string> downloadedPaths  = new();

            if (string.IsNullOrWhiteSpace(packageNamespace) || string.IsNullOrWhiteSpace(packageName) ||
                string.IsNullOrWhiteSpace(packageVersion))
            {
                Logger.Debug("Unable to download [{0} {1} {2}]. All three must be defined.", packageNamespace, packageName, packageVersion);
                return(downloadedPaths);
            }

            try
            {
                HttpClient httpClient             = CreateHttpClient();
                System.Text.Json.JsonDocument doc = await GetJsonCache(httpClient, $"{ENV_COMPOSER_ENDPOINT}/p/{packageNamespace}/{packageName}.json");

                foreach (System.Text.Json.JsonProperty topObject in doc.RootElement.GetProperty("packages").EnumerateObject())
                {
                    foreach (System.Text.Json.JsonProperty versionObject in topObject.Value.EnumerateObject())
                    {
                        if (versionObject.Name != packageVersion)
                        {
                            continue;
                        }
                        string?url = versionObject.Value.GetProperty("dist").GetProperty("url").GetString();
                        System.Net.Http.HttpResponseMessage?result = await httpClient.GetAsync(url);

                        result.EnsureSuccessStatusCode();
                        Logger.Debug("Downloading {0}...", purl);

                        string fsNamespace = OssUtilities.NormalizeStringForFileSystem(packageNamespace);
                        string fsName      = OssUtilities.NormalizeStringForFileSystem(packageName);
                        string fsVersion   = OssUtilities.NormalizeStringForFileSystem(packageVersion);

                        string targetName     = $"composer-{fsNamespace}-{fsName}@{fsVersion}";
                        string extractionPath = Path.Combine(TopLevelExtractionDirectory, targetName);
                        if (doExtract && Directory.Exists(extractionPath) && cached == true)
                        {
                            downloadedPaths.Add(extractionPath);
                            return(downloadedPaths);
                        }
                        if (doExtract)
                        {
                            downloadedPaths.Add(await ArchiveHelper.ExtractArchiveAsync(TopLevelExtractionDirectory, targetName, await result.Content.ReadAsStreamAsync(), cached));
                        }
                        else
                        {
                            extractionPath += ".zip";
                            await File.WriteAllBytesAsync(extractionPath, await result.Content.ReadAsByteArrayAsync());

                            downloadedPaths.Add(extractionPath);
                        }
                    }
                }
                if (downloadedPaths.Count == 0)
                {
                    Logger.Debug("Unable to find version {0} to download.", packageVersion);
                }
            }
            catch (Exception ex)
            {
                Logger.Debug(ex, "Error downloading Composer package: {0}", ex.Message);
            }
            return(downloadedPaths);
        }
示例#15
0
 public static bool TryParseValue(ref System.Text.Json.Utf8JsonReader reader, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Text.Json.JsonDocument document)
 {
     throw null;
 }