string.EndsWith(string, System.StringComparison)

Here are the examples of the csharp api string.EndsWith(string, System.StringComparison) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1637 Examples 7

19 View Source File : XmlCommandsProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public void Load(System.Reflection.replacedembly replacedembly)
        {
            var filenames = replacedembly.GetManifestResourceNames();
            foreach (var item in filenames)
            {
                if (!item.EndsWith(".xml", System.StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                Load(replacedembly.GetManifestResourceStream(item));
            }

        }

19 View Source File : StringExtensions.cs
License : MIT License
Project Creator : 17MKH

public static bool EndsWithIgnoreCase(this string s, string value)
    {
        return s.EndsWith(value, StringComparison.OrdinalIgnoreCase);
    }

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

private static string htmlSyntax(string tplcode, int num) {

			while (num-- > 0) {
				string[] arr = _reg_syntax.Split(tplcode);

				if (arr.Length == 1) break;
				for (int a = 1; a < arr.Length; a += 4) {
					string tag = string.Concat('<', arr[a]);
					string end = string.Concat("</", arr[a], '>');
					int fc = 1;
					for (int b = a; fc > 0 && b < arr.Length; b += 4) {
						if (b > a && arr[a].ToLower() == arr[b].ToLower()) fc++;
						int bpos = 0;
						while (true) {
							int fa = arr[b + 3].IndexOf(tag, bpos);
							int fb = arr[b + 3].IndexOf(end, bpos);
							if (b == a) {
								var z = arr[b + 3].IndexOf("/>");
								if ((fb == -1 || z < fb) && z != -1) {
									var y = arr[b + 3].Substring(0, z + 2);
									if (_reg_htmltag.IsMatch(y) == false)
										fb = z - end.Length + 2;
								}
							}
							if (fa == -1 && fb == -1) break;
							if (fa != -1 && (fa < fb || fb == -1)) {
								fc++;
								bpos = fa + tag.Length;
								continue;
							}
							if (fb != -1) fc--;
							if (fc <= 0) {
								var a1 = arr[a + 1];
								var end3 = string.Concat("{/", a1, "}");
								if (a1.ToLower() == "else") {
									if (_reg_blank.Replace(arr[a - 4 + 3], "").EndsWith("{/if}", StringComparison.CurrentCultureIgnoreCase) == true) {
										var idx = arr[a - 4 + 3].IndexOf("{/if}");
										arr[a - 4 + 3] = string.Concat(arr[a - 4 + 3].Substring(0, idx), arr[a - 4 + 3].Substring(idx + 5));
										//如果 @else="有条件内容",则变换成 elseif 条件内容
										if (_reg_blank.Replace(arr[a + 2], "").Length > 0) a1 = "elseif";
										end3 = "{/if}";
									} else {
										arr[a] = string.Concat("指令 @", arr[a + 1], "='", arr[a + 2], "' 没紧接着 if/else 指令之后,无效. <", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								if (arr[a + 1].Length > 0) {
									if (_reg_blank.Replace(arr[a + 2], "").Length > 0 || a1.ToLower() == "else") {
										arr[b + 3] = string.Concat(arr[b + 3].Substring(0, fb + end.Length), end3, arr[b + 3].Substring(fb + end.Length));
										arr[a] = string.Concat("{", a1, " ", arr[a + 2], "}<", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									} else {
										arr[a] = string.Concat('<', arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								break;
							}
							bpos = fb + end.Length;
						}
					}
					if (fc > 0) {
						arr[a] = string.Concat("不严谨的html格式,请检查 ", arr[a], " 的结束标签, @", arr[a + 1], "='", arr[a + 2], "' 指令无效. <", arr[a]);
						arr[a + 1] = arr[a + 2] = string.Empty;
					}
				}
				if (arr.Length > 0) tplcode = string.Join(string.Empty, arr);
			}
			return tplcode;
		}

19 View Source File : DynamicProxy.cs
License : MIT License
Project Creator : 2881099

static replacedembly CompileCode(string cscode)
    {

        var files = Directory.GetFiles(Directory.GetParent(Type.GetType("FreeSql.DynamicProxy, FreeSql.DynamicProxy").replacedembly.Location).FullName);
        using (var compiler = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("cs"))
        {
            var objCompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
            objCompilerParameters.Referencedreplacedemblies.Add("System.dll");
            objCompilerParameters.Referencedreplacedemblies.Add("System.Core.dll");
            objCompilerParameters.Referencedreplacedemblies.Add("FreeSql.DynamicProxy.dll");
            foreach (var dll in files)
            {
                if (!dll.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
                    !dll.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) continue;

                Console.WriteLine(dll);
                var dllName = string.Empty;
                var idx = dll.LastIndexOf('/');
                if (idx != -1) dllName = dll.Substring(idx + 1);
                else
                {
                    idx = dll.LastIndexOf('\\');
                    if (idx != -1) dllName = dll.Substring(idx + 1);
                }
                if (string.IsNullOrEmpty(dllName)) continue;
                try
                {
                    var replaced = replacedembly.LoadFile(dll);
                    objCompilerParameters.Referencedreplacedemblies.Add(dllName);
                }
                catch
                {

                }
            }
            objCompilerParameters.GenerateExecutable = false;
            objCompilerParameters.GenerateInMemory = true;

            var cr = compiler.CompilereplacedemblyFromSource(objCompilerParameters, cscode);

            if (cr.Errors.Count > 0)
                throw new DynamicProxyException($"FreeSql.DynamicProxy 失败提示:{cr.Errors[0].ErrorText} {cscode}", null);

            return cr.Compiledreplacedembly;
        }
    }

19 View Source File : DateAndSizeRollingFileAppender.cs
License : MIT License
Project Creator : Abc-Arbitrage

private int FindLastRollingFileNumber(string directory)
        {
            var fileNumber = 0;
            var root = FilenameRoot + ".";
            var extension = FilenameExtension.Length == 0 ? "" : "." + FilenameExtension;
            foreach (var filename in Directory.EnumerateFiles(directory).Select(f => f.ToUpper()))
            {
                if (filename.StartsWith(root, StringComparison.OrdinalIgnoreCase) && filename.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
                {
                    var rootLength = root.Length;
                    var extensionLength = extension.Length;
                    if (filename.Length - rootLength - extensionLength > 0 && int.TryParse(filename.Substring(rootLength, filename.Length - rootLength - extensionLength), out var tempNumber))
                        fileNumber = Math.Max(fileNumber, tempNumber);
                }
            }

            return fileNumber;
        }

19 View Source File : IndentationReformatter.cs
License : MIT License
Project Creator : Abdesol

static bool TrimEnd(IDoreplacedentAccessor doc)
		{
			string line = doc.Text;
			if (!Char.IsWhiteSpace(line[line.Length - 1])) return false;

			// one space after an empty comment is allowed
			if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
				return false;

			doc.Text = line.TrimEnd();
			return true;
		}

19 View Source File : GltfUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static async Task<GltfObject> ImportGltfObjectFromPathAsync(string uri)
        {
            if (!SyncContextUtility.IsMainThread)
            {
                Debug.LogError("ImportGltfObjectFromPathAsync must be called from the main thread!");
                return null;
            }

            if (string.IsNullOrWhiteSpace(uri))
            {
                Debug.LogError("Uri is not valid.");
                return null;
            }

            GltfObject gltfObject;
            bool useBackgroundThread = Application.isPlaying;

            if (useBackgroundThread) { await BackgroundThread; }

            if (uri.EndsWith(".gltf", StringComparison.OrdinalIgnoreCase))
            {
                string gltfJson = File.ReadAllText(uri);

                gltfObject = GetGltfObjectFromJson(gltfJson);

                if (gltfObject == null)
                {
                    Debug.LogError("Failed load Gltf Object from json schema.");
                    return null;
                }
            }
            else if (uri.EndsWith(".glb", StringComparison.OrdinalIgnoreCase))
            {
                byte[] glbData;

#if WINDOWS_UWP

                if (useBackgroundThread)
                {
                    try
                    {
                        var storageFile = await StorageFile.GetFileFromPathAsync(uri);

                        if (storageFile == null)
                        {
                            Debug.LogError($"Failed to locate .glb file at {uri}");
                            return null;
                        }

                        var buffer = await FileIO.ReadBufferAsync(storageFile);

                        using (DataReader dataReader = DataReader.FromBuffer(buffer))
                        {
                            glbData = new byte[buffer.Length];
                            dataReader.ReadBytes(glbData);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError(e.Message);
                        return null;
                    }
                }
                else
                {
                    glbData = UnityEngine.Windows.File.ReadAllBytes(uri);
                }
#else
                using (FileStream stream = File.Open(uri, FileMode.Open))
                {
                    glbData = new byte[stream.Length];

                    if (useBackgroundThread)
                    {
                        await stream.ReadAsync(glbData, 0, (int)stream.Length);
                    }
                    else
                    {
                        stream.Read(glbData, 0, (int)stream.Length);
                    }
                }
#endif

                gltfObject = GetGltfObjectFromGlb(glbData);

                if (gltfObject == null)
                {
                    Debug.LogError("Failed to load GlTF Object from .glb!");
                    return null;
                }
            }
            else
            {
                Debug.LogError("Unsupported file name extension.");
                return null;
            }

            gltfObject.Uri = uri;

            try
            {
                gltfObject.Name = Path.GetFileNameWithoutExtension(uri);
            }
            catch (ArgumentException)
            {
                Debug.LogWarning("Uri contained invalid character");
                gltfObject.Name = DefaultObjectName;
            }

            gltfObject.UseBackgroundThread = useBackgroundThread;
            await gltfObject.ConstructAsync();

            if (gltfObject.GameObjectReference == null)
            {
                Debug.LogError("Failed to construct Gltf Object.");
            }

            if (useBackgroundThread) { await Update; }

            return gltfObject;
        }

19 View Source File : NumberParse.cs
License : MIT License
Project Creator : abock

static (string str, int @base, bool negate) Configure(string str)
        {
            str = str.Trim();

            var negate = false;
            if (str.Length > 0 && str[0] == '-')
            {
                negate = true;
                str = str.Substring(1);
            }

            str = strip.Replace(str, string.Empty);

            int @base = 10;

            if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                @base = 16;
                str = str.Substring(2);
            }
            else if (str.EndsWith("h", StringComparison.OrdinalIgnoreCase))
            {
                @base = 16;
                str = str.Substring(0, str.Length - 1);
            }
            else if (str.StartsWith("0b", StringComparison.OrdinalIgnoreCase))
            {
                @base = 2;
                str = str.Substring(2);
            }

            return (str, @base, negate);
        }

19 View Source File : StringExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static string TrimEnd(this string result, string trimEnd)
        {
            if (result.EndsWith(trimEnd, StringComparison.OrdinalIgnoreCase))
                result = result.Substring(0, result.Length - trimEnd.Length);

            return result;
        }

19 View Source File : AtmHtmlReportConfig.cs
License : Microsoft Public License
Project Creator : achimismaili

public override bool RunsOn(Story story)
        {
            return story.Namespace.EndsWith("Atm", StringComparison.OrdinalIgnoreCase);
        }

19 View Source File : SelfUpdater.cs
License : MIT License
Project Creator : actions

private async Task DownloadLatestRunner(CancellationToken token)
        {
            string latestRunnerDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Path.UpdateDirectory);
            IOUtil.DeleteDirectory(latestRunnerDirectory, token);
            Directory.CreateDirectory(latestRunnerDirectory);

            int runnerSuffix = 1;
            string archiveFile = null;
            bool downloadSucceeded = false;

            try
            {
                // Download the runner, using multiple attempts in order to be resilient against any networking/CDN issues
                for (int attempt = 1; attempt <= Constants.RunnerDownloadRetryMaxAttempts; attempt++)
                {
                    // Generate an available package name, and do our best effort to clean up stale local zip files
                    while (true)
                    {
                        if (_targetPackage.Platform.StartsWith("win"))
                        {
                            archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.zip");
                        }
                        else
                        {
                            archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.tar.gz");
                        }

                        try
                        {
                            // delete .zip file
                            if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
                            {
                                Trace.Verbose("Deleting latest runner package zip '{0}'", archiveFile);
                                IOUtil.DeleteFile(archiveFile);
                            }

                            break;
                        }
                        catch (Exception ex)
                        {
                            // couldn't delete the file for whatever reason, so generate another name
                            Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
                            runnerSuffix++;
                        }
                    }

                    // Allow a 15-minute package download timeout, which is good enough to update the runner from a 1 Mbit/s ADSL connection.
                    if (!int.TryParse(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_DOWNLOAD_TIMEOUT") ?? string.Empty, out int timeoutSeconds))
                    {
                        timeoutSeconds = 15 * 60;
                    }

                    Trace.Info($"Attempt {attempt}: save latest runner into {archiveFile}.");

                    using (var downloadTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)))
                    using (var downloadCts = CancellationTokenSource.CreateLinkedTokenSource(downloadTimeout.Token, token))
                    {
                        try
                        {
                            Trace.Info($"Download runner: begin download");

                            //open zip stream in async mode
                            using (HttpClient httpClient = new HttpClient(HostContext.CreateHttpClientHandler()))
                            {
                                if (!string.IsNullOrEmpty(_targetPackage.Token))
                                {
                                    Trace.Info($"Adding authorization token ({_targetPackage.Token.Length} chars)");
                                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _targetPackage.Token);
                                }

                                Trace.Info($"Downloading {_targetPackage.DownloadUrl}");

                                using (FileStream fs = new FileStream(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
                                using (Stream result = await httpClient.GetStreamAsync(_targetPackage.DownloadUrl))
                                {
                                    //81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k).
                                    await result.CopyToAsync(fs, 81920, downloadCts.Token);
                                    await fs.FlushAsync(downloadCts.Token);
                                }
                            }

                            Trace.Info($"Download runner: finished download");
                            downloadSucceeded = true;
                            break;
                        }
                        catch (OperationCanceledException) when (token.IsCancellationRequested)
                        {
                            Trace.Info($"Runner download has been canceled.");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            if (downloadCts.Token.IsCancellationRequested)
                            {
                                Trace.Warning($"Runner download has timed out after {timeoutSeconds} seconds");
                            }

                            Trace.Warning($"Failed to get package '{archiveFile}' from '{_targetPackage.DownloadUrl}'. Exception {ex}");
                        }
                    }
                }

                if (!downloadSucceeded)
                {
                    throw new TaskCanceledException($"Runner package '{archiveFile}' failed after {Constants.RunnerDownloadRetryMaxAttempts} download attempts");
                }

                // If we got this far, we know that we've successfully downloaded the runner package
                // Validate Hash Matches if it is provided
                using (FileStream stream = File.OpenRead(archiveFile))
                {
                    if (!String.IsNullOrEmpty(_targetPackage.HashValue))
                    {
                        using (SHA256 sha256 = SHA256.Create())
                        {
                            byte[] srcHashBytes = await sha256.ComputeHashAsync(stream);
                            var hash = PrimitiveExtensions.ConvertToHexString(srcHashBytes);
                            if (hash != _targetPackage.HashValue)
                            {
                                // Hash did not match, we can't recover from this, just throw
                                throw new Exception($"Computed runner hash {hash} did not match expected Runner Hash {_targetPackage.HashValue} for {_targetPackage.Filename}");
                            }
                            Trace.Info($"Validated Runner Hash matches {_targetPackage.Filename} : {_targetPackage.HashValue}");
                        }
                    }
                }
                if (archiveFile.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                {
                    ZipFile.ExtractToDirectory(archiveFile, latestRunnerDirectory);
                }
                else if (archiveFile.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase))
                {
                    string tar = WhichUtil.Which("tar", trace: Trace);

                    if (string.IsNullOrEmpty(tar))
                    {
                        throw new NotSupportedException($"tar -xzf");
                    }

                    // tar -xzf
                    using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
                    {
                        processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                        {
                            if (!string.IsNullOrEmpty(args.Data))
                            {
                                Trace.Info(args.Data);
                            }
                        });

                        processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                        {
                            if (!string.IsNullOrEmpty(args.Data))
                            {
                                Trace.Error(args.Data);
                            }
                        });

                        int exitCode = await processInvoker.ExecuteAsync(latestRunnerDirectory, tar, $"-xzf \"{archiveFile}\"", null, token);
                        if (exitCode != 0)
                        {
                            throw new NotSupportedException($"Can't use 'tar -xzf' extract archive file: {archiveFile}. return code: {exitCode}.");
                        }
                    }
                }
                else
                {
                    throw new NotSupportedException($"{archiveFile}");
                }

                Trace.Info($"Finished getting latest runner package at: {latestRunnerDirectory}.");
            }
            finally
            {
                try
                {
                    // delete .zip file
                    if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
                    {
                        Trace.Verbose("Deleting latest runner package zip: {0}", archiveFile);
                        IOUtil.DeleteFile(archiveFile);
                    }
                }
                catch (Exception ex)
                {
                    //it is not critical if we fail to delete the .zip file
                    Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
                }
            }

            // copy latest runner into runner root folder
            // copy bin from _work/_update -> bin.version under root
            string binVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.BinDirectory}.{_targetPackage.Version}");
            Directory.CreateDirectory(binVersionDir);
            Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory)} to {binVersionDir}.");
            IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory), binVersionDir, token);

            // copy externals from _work/_update -> externals.version under root
            string externalsVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.ExternalsDirectory}.{_targetPackage.Version}");
            Directory.CreateDirectory(externalsVersionDir);
            Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory)} to {externalsVersionDir}.");
            IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory), externalsVersionDir, token);

            // copy and replace all .sh/.cmd files
            Trace.Info($"Copy any remaining .sh/.cmd files into runner root.");
            foreach (FileInfo file in new DirectoryInfo(latestRunnerDirectory).GetFiles() ?? new FileInfo[0])
            {
                string destination = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), file.Name);

                // Removing the file instead of just trying to overwrite it works around permissions issues on linux.
                // https://github.com/actions/runner/issues/981
                Trace.Info($"Copy {file.FullName} to {destination}");
                IOUtil.DeleteFile(destination);
                file.CopyTo(destination, true);
            }
        }

19 View Source File : RunnerWebProxy.cs
License : MIT License
Project Creator : actions

private bool IsUriInBypreplacedList(Uri input)
        {
            foreach (var noProxy in _noProxyList)
            {
                var matchHost = false;
                var matchPort = false;

                if (string.IsNullOrEmpty(noProxy.Port))
                {
                    matchPort = true;
                }
                else
                {
                    matchPort = string.Equals(noProxy.Port, input.Port.ToString());
                }

                if (noProxy.Host.StartsWith('.'))
                {
                    matchHost = input.Host.EndsWith(noProxy.Host, StringComparison.OrdinalIgnoreCase);
                }
                else
                {
                    matchHost = string.Equals(input.Host, noProxy.Host, StringComparison.OrdinalIgnoreCase) || input.Host.EndsWith($".{noProxy.Host}", StringComparison.OrdinalIgnoreCase);
                }

                if (matchHost && matchPort)
                {
                    return true;
                }
            }

            return false;
        }

19 View Source File : VssStringComparer.cs
License : MIT License
Project Creator : actions

public bool EndsWith(string main, string pattern)
        {
            ArgumentUtility.CheckForNull(main, "main");
            ArgumentUtility.CheckForNull(pattern, "pattern");

            return main.EndsWith(pattern, m_stringComparison);
        }

19 View Source File : ExpressionValue.cs
License : MIT License
Project Creator : actions

public static Boolean IsExpression(String value)
        {
            return !String.IsNullOrEmpty(value) &&
                   value.Length > 3 &&
                   value.StartsWith("$[", StringComparison.Ordinal) &&
                   value.EndsWith("]", StringComparison.Ordinal);
        }

19 View Source File : SimpleStructureMatcher.cs
License : MIT License
Project Creator : Actipro

public override IStructureMatchResultSet Match(TextSnapshotOffset snapshotOffset, IStructureMatchOptions options) {
			if (snapshotOffset.IsDeleted)
				throw new ArgumentNullException("snapshotOffset");

			// Get a snapshot reader and configure it for quick initial lookup
			ITextSnapshotReader reader = snapshotOffset.Snapshot.GetReader(snapshotOffset.Offset);
			reader.Options.DefaultTokenLoadBufferLength = 250;
			reader.Options.InitialTokenLoadBufferLength = 4;
			
			IToken token = reader.Token;
			if (token != null) {
				// If the token is not a multi-line comment but is at the start of a token, check the previous token
				if ((token.Id != SimpleTokenId.MultiLineCommentText) && (reader.IsAtTokenStart))
					token = reader.ReadTokenReverse();

				// If the token is a multi-line comment...
				if (token.Id == SimpleTokenId.MultiLineCommentText) {
					// The Simple language programmatic lexer variant only has a single token for the entire comment so
					//   ensure the target offset is at a delimiter (and not within the body of the comment)...
					//   For most other languages, you'd want to scan tokens to find a matching delimiter token instead
					bool isAtStart = (snapshotOffset.Offset <= token.StartOffset + 2);
					bool isAtEnd = (snapshotOffset.Offset >= token.EndOffset - 2);
					if (isAtStart || isAtEnd) {
						// Get the token's text and ensure it ends with a proper delimiter
						string tokenText = reader.TokenText;
						if ((token.Length >= 4) && (tokenText.EndsWith("*/", StringComparison.Ordinal))) {
							// Found a valid match
							StructureMatchResultCollection results = new StructureMatchResultCollection();
							results.Add(new StructureMatchResult(new TextSnapshotRange(reader.Snapshot, token.StartOffset, token.StartOffset + 2)) {
								IsSource = isAtStart,
								NavigationSnapshotOffset = new TextSnapshotOffset(reader.Snapshot, token.StartOffset)
							});
							results.Add(new StructureMatchResult(new TextSnapshotRange(reader.Snapshot, token.EndOffset - 2, token.EndOffset)) {
								IsSource = !isAtStart,
								NavigationSnapshotOffset = new TextSnapshotOffset(reader.Snapshot, token.EndOffset)
							});
							return new StructureMatchResultSet(results);
						}
					}
				}
			}

			// Call the base method
			return base.Match(snapshotOffset, options);
		}

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void BindProducts() {
			// Manually reference these type to ensure the related replacedemblies are loaded since they may not yet have been loaded by default
			var srTypes = new Type[] {
				// None: typeof(ActiproSoftware.Products.SyntaxEditor.Addons.JavaScript.SR),
				typeof(ActiproSoftware.Products.SyntaxEditor.Addons.Python.SR),
				typeof(ActiproSoftware.Products.SyntaxEditor.Addons.Xml.SR),
				typeof(ActiproSoftware.Products.Text.Addons.JavaScript.SR),
				typeof(ActiproSoftware.Products.Text.Addons.Python.SR),
				typeof(ActiproSoftware.Products.Text.Addons.Xml.SR),
			};

			var productResources = new List<ProductResource>();

			foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
				var name = replacedembly.GetName().Name;
				if ((name.StartsWith("ActiproSoftware.", StringComparison.OrdinalIgnoreCase)) && (name.EndsWith(".Wpf", StringComparison.OrdinalIgnoreCase))) {
					var productResource = new ProductResource(replacedembly);
					if (productResource.IsValid)
						productResources.Add(productResource);
				}
			}

			productResources.Sort((x, y) => x.Name.CompareTo(y.Name));

			productComboBox.ItemsSource = productResources;

			if (productComboBox.Items.Count > 0)
				productComboBox.SelectedIndex = 0;
		}

19 View Source File : CodeResolvingUtils.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static EventInfo GetEventHandlerInfo(this IMethodSymbol symbol, PXContext pxContext)
		{
			if (symbol.ReturnsVoid && symbol.TypeParameters.IsEmpty && !symbol.Parameters.IsEmpty)
			{
				// Loosely check method signature because sometimes business logic 
				// is extracted from event handler calls to a separate method

				// Old non-generic syntax
				if (symbol.Parameters[0].Type.OriginalDefinition.InheritsFromOrEquals(pxContext.PXCache.Type))
				{
					if (symbol.Name.EndsWith("CacheAttached", StringComparison.Ordinal))
						return new EventInfo(EventType.CacheAttached, EventHandlerSignatureType.Default);

					if (symbol.Parameters.Length >= 2 && pxContext.Events.EventTypeMap.TryGetValue(
						    symbol.Parameters[1].Type.OriginalDefinition, out EventType eventType))
					{
						return new EventInfo(eventType, EventHandlerSignatureType.Default);
					}
				}
				else if (pxContext.Events.EventTypeMap.TryGetValue(
					symbol.Parameters[0].Type.OriginalDefinition, out EventType eventType)) // New generic event handler syntax
				{
					return new EventInfo(eventType, EventHandlerSignatureType.Generic);
				}
			}

			return EventInfo.None();
		}

19 View Source File : ChildrenCodeTemplate.cs
License : MIT License
Project Creator : adamant

public void Write(string textToAppend)
        {
            if (string.IsNullOrEmpty(textToAppend))
            {
                return;
            }
            // If we're starting off, or if the previous text ended with a newline,
            // we have to append the current indent first.
            if (((this.GenerationEnvironment.Length == 0) 
                        || this.endsWithNewline))
            {
                this.GenerationEnvironment.Append(this.currentIndentField);
                this.endsWithNewline = false;
            }
            // Check if the current text ends with a newline
            if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
            {
                this.endsWithNewline = true;
            }
            // This is an optimization. If the current indent is "", then we don't have to do any
            // of the more complex stuff further down.
            if ((this.currentIndentField.Length == 0))
            {
                this.GenerationEnvironment.Append(textToAppend);
                return;
            }
            // Everywhere there is a newline in the text, add an indent after it
            textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
            // If the text ends with a newline, then we should strip off the indent added at the very end
            // because the appropriate indent will be added when the next time Write() is called
            if (this.endsWithNewline)
            {
                this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
            }
            else
            {
                this.GenerationEnvironment.Append(textToAppend);
            }
        }

19 View Source File : LexerTests.cs
License : MIT License
Project Creator : adamant

[Theory]
        [InlineData(@"""\", "")]
        [InlineData(@"""\a""", "a")]
        [InlineData(@"""\m""", "m")]
        [InlineData(@"""\x""", "x")]
        // Unicode escapes could be stopped with EOF, End of string or invalid char
        // at each of the different states
        [InlineData(@"""\u""", "u")]
        [InlineData(@"""\u", "u")]
        [InlineData(@"""\u|""", "u|")]
        [InlineData(@"""\u(", "u(")]
        [InlineData(@"""\u(""", "u(")]
        [InlineData(@"""\u(|""", "u(|")]
        [InlineData(@"""\u(1f", "\u001f")]
        [InlineData(@"""\u(1f""", "\u001f")]
        [InlineData(@"""\u(1f|""", "\u001f|")]
        [InlineData(@"""\u()""", "u()")]
        [InlineData(@"""\u(110000)""", "u(110000)")] // 1 too high
        // TODO can't put use a surrogate pair as a unicode escape, they must be unicode scalars
        public void Invalid_escape_sequence(string literal, string expectedValue)
        {
            var result = Lex(literal);
            var token = result.replacedertSingleToken();
            token.replacedertStringLiteral(0, literal.Length, expectedValue);
            var completeString = literal.EndsWith("\"", StringComparison.Ordinal);
            var expectedDiagnosticCount = completeString ? 1 : 2;
            result.replacedertDiagnostics(expectedDiagnosticCount);
            var diagnostics = result.Diagnostics;

            var expectedLength = literal.Length;
            if (literal.Contains('|', StringComparison.Ordinal)) expectedLength -= 1;
            if (completeString)
                diagnostics[0].replacedertError(1003, 1, expectedLength - 2);
            else
            {
                diagnostics[0].replacedertError(1002, 0, literal.Length);
                diagnostics[1].replacedertError(1003, 1, expectedLength - 1);
            }
        }

19 View Source File : AssemblyExtensions.cs
License : MIT License
Project Creator : adamfisher

public static bool ContainsManifestResource(this replacedembly replacedembly, string resourceName)
        {
            return replacedembly != null
                && replacedembly.GetManifestResourceNames()
                .Any(x => x.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase));
        }

19 View Source File : AssemblyExtensions.cs
License : MIT License
Project Creator : adamfisher

public static Stream GetEmbeddedResourceStream(this replacedembly replacedembly, string resourceFileName)
        {
            var resourceNames = replacedembly.GetManifestResourceNames();

            var resourcePaths = resourceNames
                .Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase))
                .ToArray();

            if (!resourcePaths.Any())
            {
                throw new Exception($"Resource ending with {resourceFileName} not found.");
            }

            if (resourcePaths.Count() > 1)
            {
                throw new Exception($"Multiple resources ending with {resourceFileName} found: {Environment.NewLine}{string.Join(Environment.NewLine, resourcePaths)}");
            }

            return replacedembly.GetManifestResourceStream(resourcePaths.Single());
        }

19 View Source File : Git.cs
License : Apache License 2.0
Project Creator : adamralph

private static string RemoveFromEnd(this string text, string value) =>
            text.EndsWith(value, StringComparison.OrdinalIgnoreCase) ? text[..^value.Length] : text;

19 View Source File : Utilities.cs
License : MIT License
Project Creator : ADeltaX

public static string MakeRelativePath(string path, string basePath)
        {
            List<string> pathElements =
                new List<string>(path.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries));
            List<string> basePathElements =
                new List<string>(basePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries));

            if (!basePath.EndsWith("\\", StringComparison.Ordinal) && basePathElements.Count > 0)
            {
                basePathElements.RemoveAt(basePathElements.Count - 1);
            }

            // Find first part of paths that don't match
            int i = 0;
            while (i < Math.Min(pathElements.Count - 1, basePathElements.Count))
            {
                if (pathElements[i].ToUpperInvariant() != basePathElements[i].ToUpperInvariant())
                {
                    break;
                }

                ++i;
            }

            // For each remaining part of the base path, insert '..'
            StringBuilder result = new StringBuilder();
            if (i == basePathElements.Count)
            {
                result.Append(@".\");
            }
            else if (i < basePathElements.Count)
            {
                for (int j = 0; j < basePathElements.Count - i; ++j)
                {
                    result.Append(@"..\");
                }
            }

            // For each remaining part of the path, add the path element
            for (int j = i; j < pathElements.Count - 1; ++j)
            {
                result.Append(pathElements[j]);
                result.Append(@"\");
            }

            result.Append(pathElements[pathElements.Count - 1]);

            // If the target was a directory, put the terminator back
            if (path.EndsWith(@"\", StringComparison.Ordinal))
            {
                result.Append(@"\");
            }

            return result.ToString();
        }

19 View Source File : SharePointDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private static string ConvertSortExpressionToCaml(string sortExpression)
		{
			if (string.IsNullOrWhiteSpace(sortExpression)) throw new ArgumentNullException("sortExpression");

			var sort = sortExpression.Trim();
			var sortAsc = !sort.EndsWith(" DESC", StringComparison.InvariantCultureIgnoreCase);
			var sortBy = sort.Split(' ').First();

			return @"Name=""{0}"" Ascending=""{1}""".FormatWith(sortBy, sortAsc.ToString().ToUpperInvariant());
		}

19 View Source File : AuthenticationPage.xaml.cs
License : MIT License
Project Creator : Adoxio

protected virtual IServiceConfiguration<IDiscoveryService> CreateServiceConfiguration(Uri uri)
		{
			var fullServiceUri = uri.AbsolutePath.EndsWith(_discoveryUri, StringComparison.OrdinalIgnoreCase)
				? uri
				: new Uri(uri, uri.AbsolutePath.TrimEnd('/') + _discoveryUri);

			var config = ServiceConfigurationFactory.CreateConfiguration<IDiscoveryService>(fullServiceUri);

			return config;
		}

19 View Source File : SetupController.cs
License : MIT License
Project Creator : Adoxio

private static Uri GetOrganizationServiceUrl(Uri url)
		{
			return url.AbsolutePath.EndsWith(_orgSvcPath, StringComparison.OrdinalIgnoreCase)
				? url
				: new Uri(url, url.AbsolutePath.TrimEnd('/') + _orgSvcPath);
		}

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : AdriaandeJongh

static void ClearITMSPPackage()
        {
            // remove any previously copied replacedets

            foreach (string file in Directory.GetFiles(itmspFilePath + "/", "*.png").Where(item => item.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase)))
                File.Delete(file);

            foreach (string file in Directory.GetFiles(itmspFilePath + "/", "*.mp4").Where(item => item.EndsWith(".mp4", StringComparison.CurrentCultureIgnoreCase)))
                File.Delete(file);
        }

19 View Source File : EpubFile.cs
License : MIT License
Project Creator : Aeroblast

public void Save(string path, FileMode fileMode = FileMode.Create)
        {
            string filepath = path;
            if (!path.EndsWith(".epub", StringComparison.OrdinalIgnoreCase))
            {
                filepath = Path.Combine(filepath, filename + ".epub");
            }
            using (FileStream zipToOpen = new FileStream(filepath, fileMode))
            {

                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    foreach (var item in entries) { item.PutInto(archive); }
                }
            }
            Log.log("[Info]Saved " + filepath);
        }

19 View Source File : AG0021PreferAsyncMethods.cs
License : Apache License 2.0
Project Creator : agoda-com

private IEnumerable<IMethodSymbol> GetAlternativeAsyncMethods(SemanticModel semanticModel, int position, MethodDescriptor descriptor)
        {
            // searching methods by name
            var methods = semanticModel.LookupSymbols(
                position,
                container: descriptor.CallingType,
                name: descriptor.UsedMethod.Name,
                includeReducedExtensionMethods: true).OfType<IMethodSymbol>();

            // searching methods by name with the postfix
            if (!descriptor.UsedMethod.Name.EndsWith("Async", StringComparison.Ordinal))
            {
                methods = methods.Concat(semanticModel.LookupSymbols(
                    position,
                    container: descriptor.CallingType,
                    name: descriptor.UsedMethod.Name + "Async",
                    includeReducedExtensionMethods: true).OfType<IMethodSymbol>());
            }

            // should we look at static method
            bool isStatic = descriptor.UsedMethod.IsStatic && !descriptor.UsedMethod.IsExtensionMethod;

            foreach (IMethodSymbol member in methods)
            {
                if (!member.Equals(descriptor.UsedMethod)
                    && (member.IsStatic == isStatic || member.IsExtensionMethod)
                    && member.IsAwaitableNonDynamic(semanticModel, position: 0))
                {
                    yield return member;
                }
            }
        }

19 View Source File : Toolbox.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal static string AddMissingFileExtension(string filePath, string extension)
        {
            if (filePath == null) return null;
            if (!filePath.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
                return $"{filePath}{extension}";

            return filePath;
        }

19 View Source File : DateTimeUtils.cs
License : MIT License
Project Creator : akaskela

internal static bool TryParseDateTimeOffset(string s, string dateFormatString, CultureInfo culture, out DateTimeOffset dt)
        {
            if (s.Length > 0)
            {
                if (s[0] == '/')
                {
                    if (s.Length >= 9 && s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal))
                    {
                        if (TryParseDateTimeOffsetMicrosoft(new StringReference(s.ToCharArray(), 0, s.Length), out dt))
                        {
                            return true;
                        }
                    }
                }
                else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[0]) && s[10] == 'T')
                {
                    if (DateTimeOffset.TryParseExact(s, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dt))
                    {
                        if (TryParseDateTimeOffsetIso(new StringReference(s.ToCharArray(), 0, s.Length), out dt))
                        {
                            return true;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(dateFormatString))
                {
                    if (TryParseDateTimeOffsetExact(s, dateFormatString, culture, out dt))
                    {
                        return true;
                    }
                }
            }

            dt = default(DateTimeOffset);
            return false;
        }

19 View Source File : DateTimeUtils.cs
License : MIT License
Project Creator : akaskela

internal static bool TryParseDateTime(string s, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt)
        {
            if (s.Length > 0)
            {
                if (s[0] == '/')
                {
                    if (s.Length >= 9 && s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal))
                    {
                        if (TryParseDateTimeMicrosoft(new StringReference(s.ToCharArray(), 0, s.Length), dateTimeZoneHandling, out dt))
                        {
                            return true;
                        }
                    }
                }
                else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[0]) && s[10] == 'T')
                {
                    if (DateTime.TryParseExact(s, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dt))
                    {
                        dt = EnsureDateTime(dt, dateTimeZoneHandling);
                        return true;
                    }
                }

                if (!string.IsNullOrEmpty(dateFormatString))
                {
                    if (TryParseDateTimeExact(s, dateTimeZoneHandling, dateFormatString, culture, out dt))
                    {
                        return true;
                    }
                }
            }

            dt = default(DateTime);
            return false;
        }

19 View Source File : JsonPosition.cs
License : MIT License
Project Creator : akaskela

internal static string FormatMessage(IJsonLineInfo lineInfo, string path, string message)
        {
            // don't add a fullstop and space when message ends with a new line
            if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
            {
                message = message.Trim();

                if (!message.EndsWith('.'))
                {
                    message += ".";
                }

                message += " ";
            }

            message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);

            if (lineInfo != null && lineInfo.HasLineInfo())
            {
                message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
            }

            message += ".";

            return message;
        }

19 View Source File : InternalExpressionHelper.cs
License : Apache License 2.0
Project Creator : AKlaus

private static string EnsureControllerName(Type controllerType)
        {
            var controllerName = controllerType.Name;
            if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("Action target must end in controller", "action");
            }
            controllerName = controllerName.Remove(controllerName.Length - 10, 10);
            if (controllerName.Length == 0)
            {
                throw new ArgumentException("Action cannot route to controller", "action");
            }
            return controllerName;
        }

19 View Source File : ScriptAssetOpener.cs
License : MIT License
Project Creator : akof1314

private static void OpenLuaFileInter(string exePath, string file, int line)
        {
            string arg = string.Format("{0}:{1}", QuotePathIfNeeded(file), line);
            if (exePath.EndsWith("idea.exe", StringComparison.Ordinal) ||
                exePath.EndsWith("idea64.exe", StringComparison.Ordinal))
            {
                arg = String.Format("--line {1} {0}", QuotePathIfNeeded(file), line);
            }

            Process.Start(new ProcessStartInfo
            {
                FileName = exePath,
                Arguments = arg,
                UseShellExecute = false,
                CreateNoWindow = true
            });
        }

19 View Source File : InternalExpressionHelper.cs
License : Apache License 2.0
Project Creator : AKlaus

private static Type EnsureController<TController>()
        {
            var controllerType = typeof(TController);

            bool isController = controllerType != null
                   && controllerType.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)
                   && !controllerType.IsAbstract
                   && (
                        typeof(ControllerBase).IsreplacedignableFrom(controllerType)
                        || typeof(ControllerBase).IsreplacedignableFrom(controllerType)
                      );

            if (!isController)
                throw new InvalidOperationException("Action target is an invalid controller.");

            return controllerType!;
        }

19 View Source File : HtmlFromXamlConverter.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev

private static void AddComplexProperty(XmlTextReader xamlReader, StringBuilder inlineStyle)
        {
            Debug.replacedert(xamlReader.NodeType == XmlNodeType.Element);

            if (inlineStyle != null && xamlReader.Name.EndsWith(".TextDecorations", StringComparison.OrdinalIgnoreCase))
            {
                inlineStyle.Append("text-decoration:underline;");
            }

            // Skip the element representing the complex property
            WriteElementContent(xamlReader, /*htmlWriter:*/null, /*inlineStyle:*/null);
        }

19 View Source File : StringExtensions.cs
License : MIT License
Project Creator : AlexanderPro

public static string TrimEnd(this string text, string value, StringComparison comparisonType = StringComparison.CurrentCulture)
        {
            var result = text;
            while (result.EndsWith(value, comparisonType))
            {
                result = result.Substring(0, result.Length - value.Length);
            }
            return result;
        }

19 View Source File : WpfThemeService.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public void Initialize()
        {
            // Add default theme style
            this.ThemeStyles.Add(this.DefaultThemeStyle, (null, null));

            // Load custom theme style
            if (Directory.Exists(App.ThemesPath))
            {
                var files = Directory.GetFiles(App.ThemesPath, "*.xaml");
                var themes = files
                    .Select(f => Path.GetFileNameWithoutExtension(f))
                    .Where(f => f.EndsWith(".Light", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".Dark", StringComparison.OrdinalIgnoreCase))
                    .Select(f => f.Substring(0, f.LastIndexOf(".")))
                    .Distinct();

                foreach (var theme in themes)
                {
                    var lightThemePath = Path.Combine(App.ThemesPath, $"{theme}.Light.xaml");
                    var darkThemePath = Path.Combine(App.ThemesPath, $"{theme}.Dark.xaml");
                    ResourceDictionary lightDictionary = null;
                    ResourceDictionary darkDictionary = null;

                    if (File.Exists(lightThemePath))
                    {
                        lightDictionary = new ResourceDictionary() { Source = new Uri(lightThemePath) };
                    }

                    if (File.Exists(darkThemePath))
                    {
                        darkDictionary = new ResourceDictionary() { Source = new Uri(darkThemePath) };
                    }

                    if (!this.ThemeStyles.ContainsKey(theme))
                    {
                        this.ThemeStyles.Add(theme, (lightDictionary, darkDictionary));
                    }
                }
            }
        }

19 View Source File : Utility.cs
License : MIT License
Project Creator : alexrainman

public static bool PathMatches(string path, string cookiePath) //per update 6265 rules
        {
            if (path == cookiePath)
                return true;
            if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(cookiePath))
                return false;
            if (path.StartsWith(cookiePath, StringComparison.InvariantCultureIgnoreCase) && cookiePath.EndsWith("/", StringComparison.InvariantCultureIgnoreCase))
                return true;
            if (path.StartsWith(cookiePath, StringComparison.InvariantCultureIgnoreCase) && path.Substring(cookiePath.Length).StartsWith("/", StringComparison.InvariantCultureIgnoreCase))
                return true;

            return false;
        }

19 View Source File : TestAccount.cs
License : Apache License 2.0
Project Creator : alipay

public static string GetSolutionBasePath()
        {
            string current = Directory.GetCurrentDirectory();
            do
            {
                current = Directory.GetParent(current).ToString();
            }
            while (!current.EndsWith("bin", StringComparison.Ordinal));
            return current + "/../..";
        }

19 View Source File : AopUtils.cs
License : Apache License 2.0
Project Creator : alipay

public static string GetMimeType(string fileName)
        {
            string mimeType;
            fileName = fileName.ToLower();

            if (fileName.EndsWith(".bmp", StringComparison.CurrentCulture))
            {
                mimeType = "image/bmp";
            }
            else if (fileName.EndsWith(".gif", StringComparison.CurrentCulture))
            {
                mimeType = "image/gif";
            }
            else if (fileName.EndsWith(".jpg", StringComparison.CurrentCulture) || fileName.EndsWith(".jpeg", StringComparison.CurrentCulture))
            {
                mimeType = "image/jpeg";
            }
            else if (fileName.EndsWith(".png", StringComparison.CurrentCulture))
            {
                mimeType = "image/png";
            }
            else
            {
                mimeType = "application/octet-stream";
            }

            return mimeType;
        }

19 View Source File : MQSigner.cs
License : MIT License
Project Creator : aliyunmq

protected static string CanonicalizeResourcePath(string resourcePath)
        {
            if (string.IsNullOrEmpty(resourcePath) || resourcePath == "/")
                return "/";

            var pathSegments = resourcePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var canonicalizedPath = new StringBuilder();
            foreach (var segment in pathSegments)
            {
                canonicalizedPath.AppendFormat("/{0}", segment);
            }

            if (resourcePath.EndsWith("/", StringComparison.Ordinal))
                canonicalizedPath.Append("/");

            return canonicalizedPath.ToString();
        }

19 View Source File : DefaultRedisProvider.cs
License : MIT License
Project Creator : AlphaYu

private string HandlePrefix(string prefix)
        {
            // Forbid
            if (prefix.Equals("*"))
                throw new ArgumentException("the prefix should not equal to *");

            // Don't start with *
            prefix = new System.Text.RegularExpressions.Regex("^\\*+").Replace(prefix, "");

            // End with *
            if (!prefix.EndsWith("*", StringComparison.OrdinalIgnoreCase))
                prefix = string.Concat(prefix, "*");

            return prefix;
        }

19 View Source File : DirectoryImageReader.cs
License : MIT License
Project Creator : AlturosDestinations

public IEnumerable<ImageInfo> replacedyze(string path)
        {
            var allowedFileExtensions = new string[] { ".bmp", ".jpg", ".png" };

            var files = Directory.GetFiles(path);
            foreach (var file in files)
            {
                if (!allowedFileExtensions.Any(o => file.EndsWith(o, StringComparison.OrdinalIgnoreCase)))
                {
                    continue;
                }

                var fileInfo = new FileInfo(file);
                var resolution = this.GetImageResolution(file);

                var imageInfo = new ImageInfo();
                imageInfo.Name = fileInfo.Name;
                imageInfo.Path = file;
                imageInfo.Width = resolution.Item1;
                imageInfo.Height = resolution.Item2;

                yield return imageInfo;
            }
        }

19 View Source File : CsCodeGenerator.cs
License : MIT License
Project Creator : amerkoleci

private static void GenerateConstants(CppCompilation compilation, string outputPath)
        {
            using var writer = new CodeWriter(Path.Combine(outputPath, "Constants.cs"));
            writer.WriteLine("/// <summary>");
            writer.WriteLine("/// Provides Vulkan specific constants for special values, layer names and extension names.");
            writer.WriteLine("/// </summary>");
            using (writer.PushBlock("public static partial clreplaced Vulkan"))
            {
                foreach (CppMacro cppMacro in compilation.Macros)
                {
                    if (string.IsNullOrEmpty(cppMacro.Value)
                        || cppMacro.Name.EndsWith("_H_", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VKAPI_CALL", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VKAPI_PTR", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VULKAN_CORE_H_", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VK_TRUE", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VK_FALSE", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VK_MAKE_VERSION", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VK_MAKE_API_VERSION", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VK_MAKE_VIDEO_STD_VERSION", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.StartsWith("VK_ENABLE_BETA_EXTENSIONS", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.StartsWith("VK_VERSION_", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.StartsWith("VK_API_VERSION_", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VK_NULL_HANDLE", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VK_DEFINE_HANDLE", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.Equals("VK_DEFINE_NON_DISPATCHABLE_HANDLE", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.StartsWith("VK_USE_PLATFORM_", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.StartsWith("VK_KHR_MAINTENANCE1_", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.StartsWith("VK_KHR_MAINTENANCE2_", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.StartsWith("VK_KHR_MAINTENANCE3_", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.StartsWith("VK_NV_VIEWPORT_ARRAY2_", StringComparison.OrdinalIgnoreCase)
                        || cppMacro.Name.StartsWith("VK_GOOGLE_HLSL_FUNCTIONALITY1_", StringComparison.OrdinalIgnoreCase)
                        )
                    {
                        continue;
                    }

                    string csName = GetPrettyEnumName(cppMacro.Name, "VK_");

                    string modifier = "const";
                    string csDataType = "string";
                    string macroValue = NormalizeEnumValue(cppMacro.Value);
                    if (macroValue.EndsWith("F", StringComparison.OrdinalIgnoreCase))
                    {
                        csDataType = "float";
                    }
                    else if (macroValue.EndsWith("UL", StringComparison.OrdinalIgnoreCase))
                    {
                        csDataType = "ulong";
                    }
                    else if (macroValue.EndsWith("U", StringComparison.OrdinalIgnoreCase))
                    {
                        csDataType = "uint";
                    }
                    else if (uint.TryParse(macroValue, out _))
                    {
                        csDataType = "uint";
                    }

                    if (cppMacro.Name == "VK_QUEUE_FAMILY_EXTERNAL"
                        || cppMacro.Name == "VK_QUEUE_FAMILY_FOREIGN_EXT")
                    {
                        csDataType = "uint";
                    }
                    else if (cppMacro.Name == "VK_LUID_SIZE_KHR"
                        || cppMacro.Name == "VK_SHADER_UNUSED_NV"
                        || cppMacro.Name == "VK_QUEUE_FAMILY_EXTERNAL_KHR"
                        || cppMacro.Name == "VK_MAX_DRIVER_NAME_SIZE_KHR"
                        || cppMacro.Name == "VK_MAX_DRIVER_INFO_SIZE_KHR"
                        || cppMacro.Name == "VK_MAX_DEVICE_GROUP_SIZE_KHR"
                        )
                    {
                        csDataType = "uint";
                        macroValue = GetCsCleanName(cppMacro.Value);
                    }

                    AddCsMapping(cppMacro.Name, csName);

                    writer.WriteLine("/// <summary>");
                    if (cppMacro.Name == "VK_HEADER_VERSION_COMPLETE" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H264_API_VERSION_0_9" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H265_SPEC_VERSION" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H265_API_VERSION_0_5" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H264_SPEC_VERSION" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H264_API_VERSION_0_9_5" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H265_API_VERSION_0_9_5")
                    {
                        modifier = "static readonly";
                        csDataType = "VkVersion";
                    }

                    writer.WriteLine($"/// {cppMacro.Name} = {cppMacro.Value}");
                    writer.WriteLine("/// </summary>");
                    if (cppMacro.Name == "VK_HEADER_VERSION_COMPLETE")
                    {
                        writer.WriteLine($"public {modifier} {csDataType} {csName} = new VkVersion({cppMacro.Tokens[2]}, {cppMacro.Tokens[4]}, {cppMacro.Tokens[6]}, HeaderVersion);");
                    }
                    else if (cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H264_API_VERSION_0_9" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H265_API_VERSION_0_5" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H264_API_VERSION_0_9_5" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H265_API_VERSION_0_9_5")
                    {
                        writer.WriteLine($"public {modifier} {csDataType} {csName} = new VkVersion({cppMacro.Tokens[2]}, {cppMacro.Tokens[4]}, {cppMacro.Tokens[6]});");
                    }
                    else if (cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H265_SPEC_VERSION" ||
                        cppMacro.Name == "VK_STD_VULKAN_VIDEO_CODEC_H264_SPEC_VERSION")
                    {
                        writer.WriteLine($"public {modifier} {csDataType} {csName} = {GetPrettyEnumName(cppMacro.Tokens[0].ToString(), "VK_")};");
                    }
                    else if (cppMacro.Name.StartsWith("STD_VIDEO_"))
                    {
                        csName = GetPrettyEnumName(cppMacro.Name, "STD_");

                        writer.WriteLine($"public {modifier} {csDataType} {csName} = {macroValue};");
                    }
                    else
                    {
                        writer.WriteLine($"public {modifier} {csDataType} {csName} = {macroValue};");
                    }
                }
            }
        }

19 View Source File : CsCodeGenerator.Enum.cs
License : MIT License
Project Creator : amerkoleci

public static void GenerateEnums(CppCompilation compilation, string outputPath)
        {
            using var writer = new CodeWriter(Path.Combine(outputPath, "Enumerations.cs"), "System");
            var createdEnums = new Dictionary<string, string>();

            foreach (CppEnum cppEnum in compilation.Enums)
            {
                bool isBitmask = cppEnum.Name.EndsWith("FlagBits") ||
                    cppEnum.Name.EndsWith("FlagBitsEXT") ||
                    cppEnum.Name.EndsWith("FlagBitsKHR") ||
                    cppEnum.Name.EndsWith("FlagBitsNV") ||
                    cppEnum.Name.EndsWith("FlagBitsAMD") ||
                    cppEnum.Name.EndsWith("FlagBitsMVK") ||
                    cppEnum.Name.EndsWith("FlagBitsNN");
                if (isBitmask)
                {
                    writer.WriteLine("[Flags]");
                }

                string csName = GetCsCleanName(cppEnum.Name);
                string enumNamePrefix = GetEnumNamePrefix(cppEnum.Name);

                // Rename FlagBits in Flags.
                if (isBitmask)
                {
                    csName = csName.Replace("FlagBits", "Flags");
                    AddCsMapping(cppEnum.Name, csName);
                }

                // Remove extension suffix from enum item values
                string extensionPrefix = "";

                if (csName.EndsWith("EXT"))
                {
                    extensionPrefix = "EXT";
                }
                else if (csName.EndsWith("NV"))
                {
                    extensionPrefix = "NV";
                }
                else if (csName.EndsWith("KHR"))
                {
                    extensionPrefix = "KHR";
                }

                createdEnums.Add(csName, cppEnum.Name);

                bool noneAdded = false;
                using (writer.PushBlock($"public enum {csName}"))
                {
                    if (isBitmask &&
                        !cppEnum.Items.Any(item => GetPrettyEnumName(item.Name, enumNamePrefix) == "None"))
                    {
                        writer.WriteLine("None = 0,");
                        noneAdded = true;
                    }

                    foreach (CppEnumItem enumItem in cppEnum.Items)
                    {
                        if (enumItem.Name.EndsWith("_BEGIN_RANGE") ||
                            enumItem.Name.EndsWith("_END_RANGE") ||
                            enumItem.Name.EndsWith("_RANGE_SIZE") ||
                            enumItem.Name.EndsWith("_BEGIN_RANGE_EXT") ||
                            enumItem.Name.EndsWith("_BEGIN_RANGE_KHR") ||
                            enumItem.Name.EndsWith("_BEGIN_RANGE_NV") ||
                            enumItem.Name.EndsWith("_BEGIN_RANGE_AMD") ||
                            enumItem.Name.EndsWith("_END_RANGE_EXT") ||
                            enumItem.Name.EndsWith("_END_RANGE_KHR") ||
                            enumItem.Name.EndsWith("_END_RANGE_NV") ||
                            enumItem.Name.EndsWith("_END_RANGE_AMD") ||
                            enumItem.Name.EndsWith("_RANGE_SIZE_EXT") ||
                            enumItem.Name.EndsWith("_RANGE_SIZE_KHR") ||
                            enumItem.Name.EndsWith("_RANGE_SIZE_NV") ||
                            enumItem.Name.EndsWith("_RANGE_SIZE_AMD") ||
                            enumItem.Name.EndsWith("_MAX_ENUM") ||
                            enumItem.Name.EndsWith("_MAX_ENUM_EXT") ||
                            enumItem.Name.EndsWith("_MAX_ENUM_KHR") ||
                            enumItem.Name.EndsWith("_MAX_ENUM_NV") ||
                            enumItem.Name.EndsWith("_MAX_ENUM_AMD") ||
                            enumItem.Name.EndsWith("_MAX_ENUM_INTEL") ||
                            enumItem.Name == "VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_EXT" ||
                            enumItem.Name == "VK_STENCIL_FRONT_AND_BACK" ||
                            enumItem.Name == "VK_PIPELINE_CREATE_DISPATCH_BASE")
                        {
                            continue;
                        }

                        string enumItemName = GetEnumItemName(cppEnum, enumItem.Name, enumNamePrefix);

                        if (!string.IsNullOrEmpty(extensionPrefix) && enumItemName.EndsWith(extensionPrefix))
                        {
                            enumItemName = enumItemName.Remove(enumItemName.Length - extensionPrefix.Length);
                        }

                        if (enumItemName == "None" && noneAdded)
                        {
                            continue;
                        }

                        //writer.WriteLine("/// <summary>");
                        //writer.WriteLine($"/// {enumItem.Name}");
                        //writer.WriteLine("/// </summary>");
                        if (enumItem.ValueExpression is CppRawExpression rawExpression)
                        {
                            string enumValueName = GetEnumItemName(cppEnum, rawExpression.Text, enumNamePrefix);
                            if (enumItemName == "SurfaceCapabilities2EXT")
                            {
                                continue;
                            }

                            if (!string.IsNullOrEmpty(extensionPrefix) && enumValueName.EndsWith(extensionPrefix))
                            {
                                enumValueName = enumValueName.Remove(enumValueName.Length - extensionPrefix.Length);

                                if (enumItemName == enumValueName)
                                    continue;
                            }

                            writer.WriteLine($"{enumItemName} = {enumValueName},");
                        }
                        else
                        {
                            writer.WriteLine($"{enumItemName} = {enumItem.Value},");
                        }
                    }

                    if (csName == "VkColorComponentFlags")
                    {
                        writer.WriteLine("All = R | G | B | A");
                    }
                }

                writer.WriteLine();
            }

            // Map missing flags with typedefs to VkFlags
            foreach (CppTypedef typedef in compilation.Typedefs)
            {
                if (typedef.Name.StartsWith("PFN_")
                    || typedef.Name.Equals("VkBool32", StringComparison.OrdinalIgnoreCase)
                    || typedef.Name.Equals("VkFlags", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (typedef.ElementType is CppPointerType)
                {
                    continue;
                }

                if (createdEnums.ContainsKey(typedef.Name))
                {
                    continue;
                }

                if (typedef.Name.EndsWith("Flags", StringComparison.OrdinalIgnoreCase) ||
                    typedef.Name.EndsWith("FlagsKHR", StringComparison.OrdinalIgnoreCase) ||
                    typedef.Name.EndsWith("FlagsEXT", StringComparison.OrdinalIgnoreCase) ||
                    typedef.Name.EndsWith("FlagsNV", StringComparison.OrdinalIgnoreCase) ||
                    typedef.Name.EndsWith("FlagsAMD", StringComparison.OrdinalIgnoreCase) ||
                    typedef.Name.EndsWith("FlagsMVK", StringComparison.OrdinalIgnoreCase) ||
                    typedef.Name.EndsWith("FlagsNN", StringComparison.OrdinalIgnoreCase))
                {
                    writer.WriteLine("[Flags]");
                    using (writer.PushBlock($"public enum {typedef.Name}"))
                    {
                        writer.WriteLine("None = 0,");
                    }
                    writer.WriteLine();
                }
            }

            // Defined with specs 1.2.170 => VK_KHR_synchronization2
            string lastCreatedEnum = string.Empty;
            foreach (CppField cppField in compilation.Fields)
            {
                string? fieldType = GetCsTypeName(cppField.Type, false);
                string createdEnumName;

                if (!createdEnums.ContainsKey(fieldType))
                {
                    if (!string.IsNullOrEmpty(lastCreatedEnum))
                    {
                        writer.EndBlock();
                        writer.WriteLine();
                    }

                    createdEnums.Add(fieldType, fieldType);
                    lastCreatedEnum = fieldType;

                    string baseType = "uint";
                    if (cppField.Type is CppQualifiedType qualifiedType)
                    {
                        if (qualifiedType.ElementType is CppTypedef typedef)
                        {
                            baseType = GetCsTypeName(typedef.ElementType, false);
                        }
                        else
                        {
                            baseType = GetCsTypeName(qualifiedType.ElementType, false);
                        }
                    }

                    writer.WriteLine("[Flags]");
                    writer.BeginBlock($"public enum {fieldType} : {baseType}");
                    createdEnumName = fieldType;
                }
                else
                {
                    createdEnumName = createdEnums[fieldType];
                }

                string csFieldName = string.Empty;
                if (cppField.Name.StartsWith("VK_PIPELINE_STAGE_2"))
                {
                    csFieldName = GetPrettyEnumName(cppField.Name, "VK_PIPELINE_STAGE_2");
                }
                else if (cppField.Name.StartsWith("VK_ACCESS_2"))
                {
                    csFieldName = GetPrettyEnumName(cppField.Name, "VK_ACCESS_2");
                }
                else if (cppField.Name.StartsWith("VK_FORMAT_FEATURE_2"))
                {
                    csFieldName = GetPrettyEnumName(cppField.Name, "VK_FORMAT_FEATURE_2");
                }
                else
                {
                    csFieldName = NormalizeFieldName(cppField.Name);
                }

                // Remove vendor suffix from enum value if enum already contains it
                if (csFieldName.EndsWith("KHR", StringComparison.Ordinal) &&
                    createdEnumName.EndsWith("KHR", StringComparison.Ordinal))
                {
                    csFieldName = csFieldName.Substring(0, csFieldName.Length - 3);
                }

                writer.WriteLine($"{csFieldName} = {cppField.InitValue},");
            }

            if (!string.IsNullOrEmpty(lastCreatedEnum))
            {
                writer.EndBlock();
            }
        }

19 View Source File : LibraryLoader.cs
License : MIT License
Project Creator : amerkoleci

public static IntPtr LoadLibrary(string libraryName)
        {
            if (!libraryName.EndsWith(Extension, StringComparison.OrdinalIgnoreCase))
                libraryName += Extension;


            var osPlatform = GetOSPlatform();
            var architecture = GetArchitecture();

            var libraryPath = GetNativereplacedemblyPath(osPlatform, architecture, libraryName);

            static string GetOSPlatform()
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    return "win";
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    return "linux";
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    return "osx";

                throw new ArgumentException("Unsupported OS platform.");
            }

            static string GetArchitecture()
            {
                switch (RuntimeInformation.ProcessArchitecture)
                {
                    case Architecture.X86: return "x86";
                    case Architecture.X64: return "x64";
                    case Architecture.Arm: return "arm";
                    case Architecture.Arm64: return "arm64";
                }

                throw new ArgumentException("Unsupported architecture.");
            }

            static string GetNativereplacedemblyPath(string osPlatform, string architecture, string libraryName)
            {
                var replacedemblyLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

                string[] paths = new[]
                {
                    Path.Combine(replacedemblyLocation, libraryName),
                    Path.Combine(replacedemblyLocation, "runtimes", osPlatform, "native", libraryName),
                    Path.Combine(replacedemblyLocation, "runtimes", $"{osPlatform}-{architecture}", "native", libraryName),
                    Path.Combine(replacedemblyLocation, "native", $"{osPlatform}-{architecture}", libraryName),
                };

                foreach (string path in paths)
                {
                    if (File.Exists(path))
                    {
                        return path;
                    }
                }

                return libraryName;
            }

            IntPtr handle;
#if !NET5_0_OR_GREATER
            handle = LoadPlatformLibrary(libraryPath);
#else
            handle = NativeLibrary.Load(libraryPath);
#endif

            if (handle == IntPtr.Zero)
                throw new DllNotFoundException($"Unable to load library '{libraryName}'.");

            return handle;
        }

19 View Source File : LibraryLoader.cs
License : MIT License
Project Creator : amerkoleci

public static IntPtr LoadLocalLibrary(string libraryName)
        {
            if (!libraryName.EndsWith(Extension, StringComparison.OrdinalIgnoreCase))
                libraryName += Extension;


            var osPlatform = GetOSPlatform();
            var architecture = GetArchitecture();

            var libraryPath = GetNativereplacedemblyPath(osPlatform, architecture, libraryName);

            static string GetOSPlatform()
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    return "win";
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    return "linux";
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    return "osx";

                throw new ArgumentException("Unsupported OS platform.");
            }

            static string GetArchitecture()
            {
                switch (RuntimeInformation.ProcessArchitecture)
                {
                    case Architecture.X86: return "x86";
                    case Architecture.X64: return "x64";
                    case Architecture.Arm: return "arm";
                    case Architecture.Arm64: return "arm64";
                }

                throw new ArgumentException("Unsupported architecture.");
            }

            static string GetNativereplacedemblyPath(string osPlatform, string architecture, string libraryName)
            {
                var replacedemblyLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

                string[] paths = new[]
                {
                    Path.Combine(replacedemblyLocation, libraryName),
                    Path.Combine(replacedemblyLocation, "runtimes", osPlatform, "native", libraryName),
                    Path.Combine(replacedemblyLocation, "runtimes", $"{osPlatform}-{architecture}", "native", libraryName),
                    Path.Combine(replacedemblyLocation, "native", $"{osPlatform}-{architecture}", libraryName),
                };

                foreach (string path in paths)
                {
                    if (File.Exists(path))
                    {
                        return path;
                    }
                }

                return libraryName;
            }

            IntPtr handle;
#if !NET5_0_OR_GREATER
            handle = LoadPlatformLibrary(libraryPath);
#else
            handle = NativeLibrary.Load(libraryPath);
#endif

            if (handle == IntPtr.Zero)
                throw new DllNotFoundException($"Unable to load library '{libraryName}'.");

            return handle;
        }

19 View Source File : ProjectTracker.Solution.cs
License : Apache License 2.0
Project Creator : AmpScm

public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution)
        {
            _solutionLoaded = true;
            SccEvents.OnSolutionOpened(true);

            GetService<IAnkhServiceEvents>().OnSolutionOpened(EventArgs.Empty);

            if (!SccProvider.IsActive)
                return VSErr.S_OK;
            try
            {
                VerifySolutionNaming();

                IAnkhSolutionSettings ss = GetService<IAnkhSolutionSettings>();

                if (ss != null && ss.ProjectRoot != null)
                {
                    string rootDir = Path.GetPathRoot(ss.ProjectRoot);
                    if (rootDir.Length == 3 && rootDir.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
                    {
                        DriveInfo di = new DriveInfo(rootDir);
                        bool oldFs = false;

                        switch ((di.DriveFormat ?? "").ToUpperInvariant())
                        {
                            case "FAT32":
                            case "FAT":
                                oldFs = true;
                                break;
                        }

                        if (oldFs)
                        {
                            IAnkhConfigurationService cs = GetService<IAnkhConfigurationService>();

                            if (!cs.GetWarningBool(AnkhWarningBool.FatFsFound))
                            {
                                using (SccFilesystemWarningDialog dlg = new SccFilesystemWarningDialog())
                                {
                                    dlg.Text = Path.GetFileName(ss.SolutionFilename);
                                    if (DialogResult.OK == dlg.ShowDialog(Context))
                                    {
                                        cs.SetWarningBool(AnkhWarningBool.FatFsFound, true);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                IAnkhErrorHandler handler = GetService<IAnkhErrorHandler>();

                if (handler.IsEnabled(ex))
                    handler.OnError(ex);
                else
                    throw;
            }

            return VSErr.S_OK;
        }

See More Examples