Here are the examples of the csharp api string.EndsWith(string, bool, System.Globalization.CultureInfo) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
597 Examples
19
View Source File : SixCloudUser.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
public override IReadOnlyList<IDownloadingFile> GetDownloadingFiles()
{
var downloadingFiles = ArddFilePaths
.Where(item => item.EndsWith(Constants.DownloadInfoFileExtension))
.Where(File.Exists)
.Where(item => !_downloadingFiles.Any(file => item.StartsWith(file.DownloadInfo.Context.LocalPath)))
.Select(File.ReadAllText)
.Select(item => item.ToDownloadingFile(builder => builder
.UseSixCloudConfigure()
.Configure<RemotePathProvider>(provider =>
{
provider.Owner = this;
return provider;
}), this))
.ToArray();
ArddFilePaths.Clear();
downloadingFiles.ForEach(SaveDownloadingFile);
return _downloadingFiles;
}
19
View Source File : ValueEncoders.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static String TrimDoubleQuotes(String value)
{
var trimmed = string.Empty;
if (!string.IsNullOrEmpty(value) &&
value.Length > 8 &&
value.StartsWith('"') &&
value.EndsWith('"'))
{
trimmed = value.Substring(1, value.Length - 2);
}
return trimmed;
}
19
View Source File : EmbeddedResourceXmlSchemaProvider.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
protected virtual string GetSchemaResourceFullName(replacedembly curentreplacedembly) =>
curentreplacedembly.GetManifestResourceNames()
?.FirstOrDefault(rName => rName.EndsWith(SharedConstants.SuppressionFileXmlSchemaFileName));
19
View Source File : ChangeEventHandlerSignatureToGenericRefactoring.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
protected override async Task ComputeRefactoringsAsync(CodeRefactoringContext context, SemanticModel semanticModel, PXContext pxContext)
{
context.CancellationToken.ThrowIfCancellationRequested();
var root = await context.Doreplacedent.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var methodNode = root?.FindNode(context.Span)?.GetDeclaringMethodNode();
if (methodNode == null)
return;
IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodNode, context.CancellationToken);
if (IsSuitableForRefactoring(methodSymbol, pxContext))
{
var eventHandlerInfo = methodSymbol.GetEventHandlerInfo(pxContext);
if (eventHandlerInfo.SignatureType == EventHandlerSignatureType.Default
&& methodSymbol.Name.EndsWith("_" + eventHandlerInfo.Type, StringComparison.Ordinal)
&& pxContext.Events.EventHandlerSignatureTypeMap.TryGetValue( // check that there is a corresponding generic event args symbol
new EventInfo(eventHandlerInfo.Type, EventHandlerSignatureType.Generic), out var genericArgsSymbol))
{
(string dacName, string fieldName) = ParseMethodName(methodSymbol.Name, eventHandlerInfo.Type);
string replacedle = nameof(Resources.EventHandlerSignatureCodeActionreplacedle).GetLocalized().ToString();
CodeAction codeAction =
CodeAction.Create(replacedle, ct => ChangeSignatureAsync(context.Doreplacedent, root, semanticModel, methodNode, methodSymbol,
eventHandlerInfo.Type, genericArgsSymbol, dacName, fieldName, ct),
replacedle);
context.RegisterRefactoring(codeAction);
}
}
}
19
View Source File : ArrayData.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
public override void FromString(string value) {
if (Value != default)
Dat.ReferenceDataOffsets.Remove(ToString());
var value2 = TypeOfValue == FieldType.String || TypeOfValue == FieldType.ValueString ? value.Trim(' ') : Regex.Replace(value, @"\s", "");
if (!value2.StartsWith('[') || !value2.EndsWith(']'))
throw new InvalidCastException("\"" + value + "\" cannot be converted to an array");
if (TypeOfValue == FieldType.Unknown || value2 == "[]")
Value = Array.Empty<TypeOfValueInArray>();
else if (TypeOfValue == FieldType.ForeignRow) {
value2 = value2[1..^1]; // Trim '[' ']'
if (!value2.StartsWith('<') || !value2.EndsWith('>'))
throw new InvalidCastException("\"" + value + "\" cannot be converted to an array of ForeignKeyType(foreignrow)");
var sarray = value2[1..^1].Split(">,<"); // Trim '<' '>'
Value = new TypeOfValueInArray[sarray.Length];
for (var n = 0; n < sarray.Length; ++n) {
var d = new ForeignRowData(Dat);
d.FromString("<" + sarray[n] + ">");
Value[n] = (TypeOfValueInArray)(object)d;
}
} else {
var sarray = value2[1..^1].Split(','); // Trim '[' ']'
Value = new TypeOfValueInArray[sarray.Length];
switch (TypeOfValue) {
case FieldType.String:
case FieldType.ValueString:
for (var n = 0; n < sarray.Length; ++n)
Value[n] = (TypeOfValueInArray)IFieldData.FromString(sarray[n], TypeOfValue, Dat);
break;
default:
for (var n = 0; n < sarray.Length; ++n)
Value[n] = (TypeOfValueInArray)IFieldData.FromString(sarray[n], TypeOfValue, Dat).Value;
break;
}
}
Length = CalculateLength();
if (Offset == default) {
Offset = Dat.CurrentOffset;
Dat.CurrentOffset += Length;
Dat.ReferenceDatas[Offset] = this;
}
Dat.ReferenceDataOffsets[value] = Offset;
}
19
View Source File : IndexContainer.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
public static ulong FNV1a64Hash(string str)
{
if (str.EndsWith('/'))
str = str.TrimEnd('/') + "++";
else
str = str.ToLower() + "++";
var bs = Encoding.UTF8.GetBytes(str);
var hash = 0xCBF29CE484222325UL;
foreach (var by in bs)
hash = (hash ^ by) * 0x100000001B3UL;
// Equal to: bs.Aggregate(0xCBF29CE484222325UL, (current, by) => (current ^ by) * 0x100000001B3);
return hash;
}
19
View Source File : ConfigurationExtensions.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public static Dictionary<string, ExtensionConfigResult> FindImplementedExtensions(this IConfiguration configuration,
string rootName = Configuration.ConfigurationExtensions.DefaultRootLib)
{
if (string.IsNullOrEmpty(rootName))
throw new ArgumentNullException(nameof(rootName), "Root name must be provided");
Dictionary<string, ExtensionConfigResult> results = new();
string[]? replacedemblyNames;
// Has the user defined a using section within the root name?
if (!configuration.Hreplacedection(rootName, "Using"))
return results;
/*
There are 2 ways a user could list which replacedemblies are used
"Using": "[\"replacedembly.Name\"]"
"Using": ["replacedembly.Name"]
JSON or as Text.
*/
replacedemblyNames = string.IsNullOrEmpty(configuration[configuration.ConfigPath(rootName, "Using")])
? configuration.GetSection(configuration.ConfigPath(rootName, "Using")).Get<string[]>()
: Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(
configuration[configuration.ConfigPath(rootName, "Using")]);
#pragma warning disable 8604
foreach (var replacedembly in Findreplacedemblies(replacedemblyNames.Select(x=> x.StartsWith(Constants.LibName) ? x : $"{Constants.LibName}.{x}").ToArray()))
{
ExtensionConfigResult result = new();
foreach (var type in replacedembly.ExportedTypes
.Where(x => x.Name.EndsWith(Constants.ConfigSuffix) && !x.IsAbstract && !x.IsInterface))
{
string sectionName = type.Name;
string prefix = type.Name.Replace(Constants.ConfigSuffix, "");
result.ConfigType = type;
// Does a section exist with the clreplacedname? (DiscordConfiguration - for instance)
if(configuration.Hreplacedection( rootName, sectionName))
result.Section = new ConfigSection(ref configuration, type.Name, rootName);
// Does a section exist with the clreplacedname minus Configuration? (Discord - for Instance)
else if (configuration.Hreplacedection(rootName, prefix))
result.Section = new ConfigSection(ref configuration, prefix, rootName);
// IF THE SECTION IS NOT PROVIDED --> WE WILL USE DEFAULT CONFIG IMPLEMENTATION
/*
Now we need to find the type which should consume our config
In the event a user has some "fluff" between prefix and suffix we'll
just check for beginning and ending values.
Type should not be an interface or abstract, should also be replacedignable to BaseExtension
*/
var implementationType = replacedembly.ExportedTypes.FirstOrDefault(x =>
!x.IsAbstract && !x.IsInterface && x.Name.StartsWith(prefix) &&
x.Name.EndsWith(Constants.ExtensionSuffix) && x.IsreplacedignableTo(typeof(BaseExtension)));
// If the implementation type was found we can add it to our result set
if (implementationType != null)
{
result.ImplementationType = implementationType;
results.Add(implementationType.Name, result);
}
}
}
#pragma warning restore 8604
return results;
}
19
View Source File : JsonPosition.cs
License : MIT License
Project Creator : akaskela
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 : MagicPathParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel
License : GNU General Public License v3.0
Project Creator : AlanMorel
public static CoordF ParseCoordWithoutLastChar(string input)
{
if (input.EndsWith(','))
{
return ParseCoordFromString(input.Remove(input.Length - 1));
}
return ParseCoordFromString(input);
}
19
View Source File : AddressUtils.cs
License : MIT License
Project Creator : alexanderdna
License : MIT License
Project Creator : alexanderdna
public static bool TxInSignatureContainsPublicKey(string txInSignature, PublicKey publicKey)
{
int indexOfDelimiter = txInSignature.IndexOf('.');
if (indexOfDelimiter < 0) return false;
var publicKeyString = HexUtils.HexFromByteArray(publicKey.toDer());
if (txInSignature.Length < publicKeyString.Length) return false;
return txInSignature.EndsWith(publicKeyString);
}
19
View Source File : PluginManager.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
public void LoadPlugins(string pluginsPath)
{
this.GroupChatPluginsAutoInstalled.Clear();
this.GroupChatPluginsBuiltIn.Clear();
this.GroupChatPluginsManuallyInstalled.Clear();
this.MessageComposePluginsAutoInstalled.Clear();
this.MessageComposePluginsBuiltIn.Clear();
this.MessageComposePluginsManuallyInstalled.Clear();
Directory.CreateDirectory(pluginsPath);
Directory.CreateDirectory(Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory));
if (Directory.Exists(pluginsPath))
{
// Handle staged removals
foreach (var file in Directory.GetFiles(Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory), "*.rm"))
{
if (Path.GetFileNameWithoutExtension(file).EndsWith(PluginInstaller.StagingSuffix))
{
var originalPluginName = Path.GetFileNameWithoutExtension(file).Replace(PluginInstaller.StagingSuffix, string.Empty);
var originalPluginFullPath = Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory, originalPluginName);
if (new FileInfo(file).Length == 0)
{
// Delete the zero-byte staging stub
File.Delete(file);
// Delete the staged installation directory
if (Directory.Exists(originalPluginFullPath))
{
Directory.Delete(originalPluginFullPath, true);
}
}
}
}
// Handle staged upgrades
foreach (var directory in Directory.GetDirectories(Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory)))
{
if (Path.GetFileNameWithoutExtension(directory).EndsWith(PluginInstaller.StagingSuffix))
{
var originalPluginName = Path.GetFileNameWithoutExtension(directory).Replace(PluginInstaller.StagingSuffix, string.Empty);
var originalPluginFullPath = Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory, originalPluginName);
if (Directory.Exists(originalPluginFullPath))
{
Directory.Delete(originalPluginFullPath, true);
}
Directory.Move(directory, originalPluginFullPath);
}
}
var dllFileNames = Directory.GetFiles(pluginsPath, "*.dll", SearchOption.AllDirectories);
var replacedemblies = new List<replacedembly>(dllFileNames.Length);
foreach (string dllFile in dllFileNames)
{
var an = replacedemblyName.GetreplacedemblyName(dllFile);
var replacedembly = replacedembly.Load(an);
replacedemblies.Add(replacedembly);
}
var pluginType = typeof(PluginBase);
var pluginTypes = new List<Type>();
foreach (var replacedembly in replacedemblies)
{
if (replacedembly != null)
{
try
{
var types = replacedembly.GetTypes();
foreach (var type in types)
{
if (type.IsInterface || type.IsAbstract)
{
continue;
}
else
{
if (type.IsSubclreplacedOf(pluginType))
{
pluginTypes.Add(type);
}
}
}
}
catch (Exception)
{
Debug.WriteLine($"Failed to load plugin {replacedembly.FullName}");
}
}
}
var pluginInstaller = Ioc.Default.GetService<PluginInstaller>();
foreach (var type in pluginTypes)
{
var hostedreplacedemblyName = Path.GetFileNameWithoutExtension(Path.GetDirectoryName(type.Module.replacedembly.Location));
var installedPlugin = pluginInstaller.InstalledPlugins.FirstOrDefault(p => p.InstallationGuid == hostedreplacedemblyName);
var plugin = (PluginBase)Activator.CreateInstance(type);
if (plugin is IMessageComposePlugin messageComposePlugin)
{
if (installedPlugin == null)
{
this.MessageComposePluginsManuallyInstalled.Add(messageComposePlugin);
}
else
{
this.MessageComposePluginsAutoInstalled.Add(messageComposePlugin);
}
}
else if (plugin is IGroupChatPlugin groupChatPlugin)
{
if (installedPlugin == null)
{
this.GroupChatPluginsManuallyInstalled.Add(groupChatPlugin);
}
else
{
this.GroupChatPluginsAutoInstalled.Add(groupChatPlugin);
}
}
}
}
// Load plugins that ship directly in GMDC/Wpf
this.GroupChatPluginsBuiltIn.Add(new ImageGalleryPlugin());
}
19
View Source File : ArgumentParseHelper.cs
License : Apache License 2.0
Project Creator : alexyakunin
License : Apache License 2.0
Project Creator : alexyakunin
public static double ParseRelativeValue(string value, double defaultValue, bool negativeSubtractsFromDefault = false)
{
value = value?.Trim();
if (string.IsNullOrEmpty(value))
return defaultValue;
var offset = 0.0;
var unit = 1.0;
if (value.EndsWith('%')) {
value = value.Substring(0, value.Length - 1).Trim();
unit = defaultValue / 100;
}
else if (value.EndsWith("pct")) {
value = value.Substring(0, value.Length - 3).Trim();
unit = defaultValue / 100;
}
else if (value.EndsWith("pts")) {
value = value.Substring(0, value.Length - 3).Trim();
unit = defaultValue / 1000;
}
if (value.StartsWith('-') && negativeSubtractsFromDefault) {
offset = defaultValue;
}
return offset + double.Parse(value) * unit;
}
19
View Source File : PathExpansionPack.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public static bool EndsWithDirectorySeparator(string path) => path.EndsWith(DirectorySeparatorChar);
19
View Source File : PathExpansionPack.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public static bool EndsWithVolumeSeparator(string path) => path.EndsWith(VolumeSeparatorChar);
19
View Source File : PathExpansionPack.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public static string FixDirectoryPath(string dirPath)
{
if (dirPath.Length == 0)
return dirPath;
var result = FixPath(dirPath);
if (!result.EndsWith(DirectorySeparatorChar))
result += DirectorySeparatorChar;
return result;
}
19
View Source File : Steps.cs
License : Apache License 2.0
Project Creator : allure-framework
License : Apache License 2.0
Project Creator : allure-framework
private static void Handle(string[] tags)
{
if (tags != null && tags.Contains("attachment"))
{
var path = $"{Guid.NewGuid().ToString()}.txt";
File.WriteAllText(path, "hi there");
allure.AddAttachment(path);
allure.AddAttachment(path, "text file");
}
if (tags != null)
if (tags.Any(x => x.EndsWith(Status.failed.ToString()) || x.EndsWith(Status.broken.ToString())))
throw new Exception("Wasted");
else if (tags.Any(x => x == PluginHelper.IGNORE_EXCEPTION))
throw new IgnoreException();
}
19
View Source File : SelfLinkHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public static void SetInstanceAppSelfLinks(Instance instance, HttpRequest request)
{
string host = $"https://{request.Host.ToUriComponent()}";
string url = request.Path;
string selfLink = $"{host}{url}";
int start = selfLink.IndexOf("/instances");
if (start > 0)
{
selfLink = selfLink.Substring(0, start) + "/instances";
}
selfLink += $"/{instance.Id}";
if (!selfLink.EndsWith(instance.Id))
{
selfLink += instance.Id;
}
instance.SelfLinks ??= new ResourceLinks();
instance.SelfLinks.Apps = selfLink;
if (instance.Data != null)
{
foreach (DataElement dataElement in instance.Data)
{
dataElement.SelfLinks ??= new ResourceLinks();
dataElement.SelfLinks.Apps = $"{selfLink}/data/{dataElement.Id}";
}
}
}
19
View Source File : ProcessedReceivedData.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita
License : GNU General Public License v3.0
Project Creator : alvaroyurrita
public void _ComPort_SerialDataReceived(ComPort ReceivingComPort, ComPortSerialDataEventArgs args)
{
ReceiveDataBuffer.Append(args.SerialData);
if (rx_Changed != null) rx_Changed(args.SerialData);
CriticalProcessingReceivedData.Enter();
try
{
string delimiter = _delimiter.ToString();
string CompareBuffer = ReceiveDataBuffer.ToString();
foreach (var cmd in PresetStrings)
{
if (CompareBuffer.EndsWith(cmd.Command + delimiter))
{
if (!cmd.Active)
{
if (PresetStringReceived != null)
{
cmd.Active = true;
PresetStringReceived(cmd, cmd.Active);
}
}
}
else
{
if (cmd.Active)
{
if (PresetStringReceived != null)
{
cmd.Active = false;
PresetStringReceived(cmd, cmd.Active);
}
}
}
}
if (ReceiveDataBuffer.Length > 400) ReceiveDataBuffer.Remove(0, 256);
}
catch (Exception e)
{
ErrorLog.Error("Error Processsing Data Received - {0}", e.Message);
}
CriticalProcessingReceivedData.Leave();
}
19
View Source File : CsCodeGenerator.Structs.cs
License : MIT License
Project Creator : amerkoleci
License : MIT License
Project Creator : amerkoleci
private static void WriteField(CodeWriter writer, CppField field, bool isUnion = false, bool isReadOnly = false)
{
string csFieldName = NormalizeFieldName(field.Name);
if (isUnion)
{
writer.WriteLine("[FieldOffset(0)]");
}
if (field.Type is CppArrayType arrayType)
{
bool creplacedeFixed = false;
if (arrayType.ElementType is CppPrimitiveType)
{
creplacedeFixed = true;
}
else if (arrayType.ElementType is CppTypedef typedef
&& typedef.ElementType is CppPrimitiveType)
{
creplacedeFixed = true;
}
if (creplacedeFixed)
{
string csFieldType = GetCsTypeName(arrayType.ElementType, false);
writer.WriteLine($"public unsafe fixed {csFieldType} {csFieldName}[{arrayType.Size}];");
}
else
{
string unsafePrefix = string.Empty;
string csFieldType = GetCsTypeName(arrayType.ElementType, false);
if (csFieldType.EndsWith('*'))
{
unsafePrefix = "unsafe ";
}
for (int i = 0; i < arrayType.Size; i++)
{
writer.WriteLine($"public {unsafePrefix}{csFieldType} {csFieldName}_{i};");
}
}
}
else
{
// VkAllocationCallbacks members
if (field.Type is CppTypedef typedef &&
typedef.ElementType is CppPointerType pointerType &&
pointerType.ElementType is CppFunctionType functionType)
{
StringBuilder builder = new();
foreach(CppParameter parameter in functionType.Parameters)
{
string paramCsType = GetCsTypeName(parameter.Type, false);
// Otherwise we get interop issues with non blittable types
if (paramCsType == "VkBool32")
paramCsType = "uint";
builder.Append(paramCsType).Append(", ");
}
string returnCsName = GetCsTypeName(functionType.ReturnType, false);
// Otherwise we get interop issues with non blittable types
if (returnCsName == "VkBool32")
returnCsName = "uint";
builder.Append(returnCsName);
writer.WriteLine("#if NET5_0_OR_GREATER");
writer.WriteLine($"public unsafe delegate* unmanaged<{builder}> {csFieldName};");
writer.WriteLine("#else");
writer.WriteLine($"public IntPtr {csFieldName};");
writer.WriteLine("#endif");
return;
}
string csFieldType = GetCsTypeName(field.Type, false);
if (csFieldName.Equals("specVersion", StringComparison.OrdinalIgnoreCase) ||
csFieldName.Equals("applicationVersion", StringComparison.OrdinalIgnoreCase) ||
csFieldName.Equals("engineVersion", StringComparison.OrdinalIgnoreCase) ||
csFieldName.Equals("apiVersion", StringComparison.OrdinalIgnoreCase))
{
csFieldType = "VkVersion";
}
if (field.Type.ToString() == "ANativeWindow*")
{
csFieldType = "IntPtr";
}
else if (field.Type.ToString() == "CAMetalLayer*"
|| field.Type.ToString() == "const CAMetalLayer*")
{
csFieldType = "IntPtr";
}
string fieldPrefix = isReadOnly ? "readonly " : string.Empty;
if (csFieldType.EndsWith('*'))
{
fieldPrefix += "unsafe ";
}
writer.WriteLine($"public {fieldPrefix}{csFieldType} {csFieldName};");
}
}
19
View Source File : ScriptEditorPanel.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
public ScriptFileDoreplacedentTab OpenFile(string filename)
{
ScriptConfiguration foundconfig = new ScriptConfiguration();
// Find the most suitable script configuration to use
foreach(ScriptConfiguration cfg in scriptconfigs)
{
foreach(string ext in cfg.Extensions)
{
// Use this configuration if the extension matches
if(filename.EndsWith("." + ext, true, CultureInfo.InvariantCulture))
{
foundconfig = cfg;
break;
}
}
}
// Create new doreplacedent
ScriptFileDoreplacedentTab t = new ScriptFileDoreplacedentTab(this, foundconfig);
if(t.Open(filename))
{
// Mark any errors this script may have
if(compilererrors != null)
t.MarkScriptErrors(compilererrors);
// Add to tabs
tabs.TabPages.Add(t);
tabs.SelectedTab = t;
// Done
UpdateToolbar(true);
return t;
}
else
{
// Failed
return null;
}
}
19
View Source File : UTF8String.cs
License : GNU General Public License v3.0
Project Creator : anydream
License : GNU General Public License v3.0
Project Creator : anydream
public bool EndsWith(string value, bool ignoreCase, CultureInfo culture) {
return String.EndsWith(value, ignoreCase, culture);
}
19
View Source File : AIGeneralSettings.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
private bool ChangeStorageFolder(string proposedFolder)
{
if (string.Equals(proposedFolder, _storagePath, StringComparison.OrdinalIgnoreCase) || !replacedetPath.IsProjectPath(proposedFolder))
{
return false;
}
proposedFolder = replacedetPath.ProjectRelativePath(proposedFolder);
bool apexified = proposedFolder.EndsWith("Resources/" + AIManager.StorageFolder);
if (!proposedFolder.EndsWith("Resources") && !apexified)
{
EditorUtility.DisplayDialog("Invalid Storage Folder", "The storage folder selected must be a Resources folder. This can however be anywhere inside the replacedets folder.", "Ok");
return false;
}
if (!apexified)
{
proposedFolder = replacedetPath.Combine(proposedFolder, AIManager.StorageFolder);
}
replacedetPath.EnsurePath(proposedFolder);
//Move files from current storage location to new location.
var fullStoragePath = replacedetPath.GetFullPath(_storagePath);
if (Directory.Exists(fullStoragePath))
{
foreach (var replacedet in Directory.GetFiles(fullStoragePath, "*.replacedet", SearchOption.TopDirectoryOnly))
{
var fileName = Path.GetFileName(replacedet);
var msg = replacedetDatabase.Movereplacedet(replacedetPath.ProjectRelativePath(replacedet), replacedetPath.Combine(proposedFolder, fileName));
if (!string.IsNullOrEmpty(msg))
{
EditorUtility.DisplayDialog("Error Moving replacedets", msg, "Ok");
return false;
}
}
replacedetDatabase.Deletereplacedet(_storagePath);
}
_storagePath = proposedFolder;
return true;
}
19
View Source File : PlatformHelper.cs
License : GNU General Public License v3.0
Project Creator : Artentus
License : GNU General Public License v3.0
Project Creator : Artentus
public static void OpenDirectory(DirectoryInfo directory)
{
string path = directory.FullName;
if (!path.EndsWith(Path.DirectorySeparatorChar))
path += Path.DirectorySeparatorChar;
#if WIN32
Process.Start(new ProcessStartInfo()
{
FileName = path,
UseShellExecute = true,
Verb = "open"
});
#elif LINUX
Process.Start("xdg-open", path);
#elif OSX
Process.Start("open", path);
#else
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo()
{
FileName = path,
UseShellExecute = true,
Verb = "open"
});
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", path);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", path);
}
else
{
throw new PlatformNotSupportedException();
}
#endif
}
19
View Source File : ExtentContext.cs
License : Apache License 2.0
Project Creator : atata-framework
License : Apache License 2.0
Project Creator : atata-framework
private static IEnumerable<IExtentReporter> CreateReporters()
{
var htmlReporter = new ExtentHtmlReporter(
WorkingFolder.EndsWith(Path.DirectorySeparatorChar)
? WorkingFolder
: WorkingFolder + Path.DirectorySeparatorChar);
htmlReporter.Config.Doreplacedentreplacedle = Reportreplacedle;
yield return htmlReporter;
}
19
View Source File : DeployTask.cs
License : GNU General Public License v3.0
Project Creator : AtomCrafty
License : GNU General Public License v3.0
Project Creator : AtomCrafty
protected override void Execute() {
// init patch directory
if(flags.Has("init")) {
string deployDirectory = Helpers.AbsolutePath(arguments.Length > 0 ? arguments[0] : "autopatch");
string deployFilePath = Path.ChangeExtension(deployDirectory, Constants.ydr);
Dictionary<string, string> targets = new Dictionary<string, string>();
for(int i = 1; i < arguments.Length; i++) {
// parse targets in format name:path or just path
string[] tmp = arguments[i].Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
string name = tmp.Length > 1 && tmp[0].Length > 1 ? tmp[0] : Path.GetFileName(tmp[0]);
string path = Helpers.AbsolutePath(tmp.Length > 1 && tmp[0].Length > 1 ? tmp[1] : tmp[0]);
targets.Add(name, path);
}
if(targets.Count == 0) Fail("No target directories specified");
Directory.CreateDirectory(deployDirectory);
int fileCount = 0;
dynamic info = new JObject();
info.build = 0;
info.nameschema = "inc.{buildno}.{target}.patch.ykc";
info.deploydir = deployDirectory;
info.targets = new JArray();
foreach(var targetInfo in targets) {
string targetName = targetInfo.Key;
string targetPath = targetInfo.Value;
string[] files = Directory.GetFiles(targetPath, "*", SearchOption.AllDirectories);
dynamic target = new JObject();
{
target.name = targetName;
target.path = targetPath;
target.files = new JArray();
foreach(string file in files) {
// ignore unknown file types and hidden files
if(!DataTypes.ForExtension(DataTypes.BaseExtension(Path.GetExtension(file))).IncludeInArchive()) continue;
if(new FileInfo(file).Attributes.HasFlag(FileAttributes.Hidden)) continue;
dynamic entry = new JObject();
{
entry.name = Helpers.RelativePath(file, targetPath);
entry.size = Helpers.FileSize(file);
entry.hash = Helpers.FileHash(file);
entry.version = 0;
}
target.files.Add(entry);
fileCount++;
}
}
info.targets.Add(target);
Log("Added target '" + targetName + "' (" + target.files.Count + " files) [" + targetPath + "]", ConsoleColor.Yellow);
}
Log("Successfully added " + fileCount + " file in " + info.targets.Count + " targets", ConsoleColor.Green);
File.WriteAllText(deployFilePath, JsonConvert.SerializeObject(info, Formatting.Indented));
}
else {
if(arguments.Length == 0) Fail("No target file specified");
string deployFilePath = Helpers.AbsolutePath(arguments[0]);
int changedFiles = 0, newFiles = 0;
if(deployFilePath.EndsWith(Constants.ydr, StringComparison.OrdinalIgnoreCase)) {
dynamic info = JsonConvert.DeserializeObject(File.ReadAllText(deployFilePath));
info.build = (int)info.build + 1;
foreach(var target in info.targets) {
List<string> includedFiles = new List<string>();
string[] files = Directory.GetFiles((string)target.path, "*", SearchOption.AllDirectories);
foreach(string file in files) {
string localName = Helpers.RelativePath(file, (string)target.path);
// ignore unknown file types and hidden files
if(!DataTypes.ForExtension(DataTypes.BaseExtension(Path.GetExtension(localName))).IncludeInArchive()) continue;
if(new FileInfo(file).Attributes.HasFlag(FileAttributes.Hidden)) continue;
bool include = true, exists = false;
foreach(var localFile in target.files) {
if(localName.Equals((string)localFile.name, StringComparison.OrdinalIgnoreCase)) {
exists = true;
string hash = Helpers.FileHash(file);
long size = Helpers.FileSize(file);
if(size != (long)localFile.size || !hash.Equals((string)localFile.hash)) {
// update file entry if files differ
localFile.size = size;
localFile.hash = hash;
localFile.version = (int)localFile.version + 1;
}
else include = false;
break;
}
}
if(!exists) {
Log("[New file] " + localName, ConsoleColor.Green);
dynamic entry = new JObject();
{
entry.name = localName;
entry.size = Helpers.FileSize(file);
entry.hash = Helpers.FileHash(file);
entry.version = 1;
}
target.files.Add(entry);
newFiles++;
}
if(include) {
string mainFile = Path.ChangeExtension(localName, DataTypes.BaseExtension(Path.GetExtension(localName)));
if(!includedFiles.Contains(mainFile)) {
includedFiles.Add(mainFile);
if(exists) Log("[Changed] " + localName, ConsoleColor.Yellow);
if(exists) changedFiles++;
}
}
else {
Log("[Up to date] " + localName, ConsoleColor.Red);
}
// Log(include ? exists ? "Changed" : "New file" : "Up to date", ConsoleColor.Cyan);
}
if(includedFiles.Count > 0) {
bool verbose = flags.Has('v');
flags.Unset('v');
YukaArchive archive = new YukaArchive();
foreach(string file in includedFiles) {
dynamic factory = FileFactory.ForExtension(Path.GetExtension(file));
if(factory != null) {
string realname = Path.ChangeExtension(file, DataTypes.ForExtension(Path.GetExtension(file)).BinaryExtension());
Console.WriteLine(realname);
dynamic data = factory.FromSource(Path.Combine((string)target.path, file));
MemoryStream ms = new MemoryStream();
factory.ToBinary(data, ms);
archive.files[realname] = ms;
}
}
string name = (string)info.nameschema;
name = name.Replace("{buildno}", ((int)info.build).ToString("D3"));
name = name.Replace("{target}", ((string)target.name));
name = name.Replace("{date}", DateTime.Now.ToString("yyyy-MM-dd"));
name = name.Replace("{time}", DateTime.Now.ToString("HH-mm-ss"));
ArchiveFactory.Instance.ToSource(archive, Path.Combine((string)info.deploydir, name));
if(verbose) flags.Set('v');
}
}
Log("Deployed " + newFiles + " new files and " + changedFiles + " updates", ConsoleColor.Green);
File.WriteAllText(deployFilePath, JsonConvert.SerializeObject(info, Formatting.Indented));
}
}
if(flags.Has('w')) {
Console.ReadLine();
}
}
19
View Source File : PatchTask.cs
License : GNU General Public License v3.0
Project Creator : AtomCrafty
License : GNU General Public License v3.0
Project Creator : AtomCrafty
protected override void Execute() {
// init patch directory
if(flags.Has("init")) {
string fetchUrl = arguments.Length > 0 ? arguments[0] : "";
string gameDirectory = arguments.Length > 1 ? Helpers.AbsolutePath(arguments[1]) : Directory.GetCurrentDirectory();
string patchDirectory = arguments.Length > 2 ? Helpers.AbsolutePath(arguments[2]) : Path.Combine(gameDirectory, "autopatch");
string patchFilePath = Path.ChangeExtension(patchDirectory, Constants.ypl);
Directory.CreateDirectory(patchDirectory);
dynamic info = new JObject();
info.gamedir = gameDirectory;
info.patchdir = patchDirectory;
info.fetchurl = fetchUrl;
info.history = new JArray();
File.WriteAllText(patchFilePath, JsonConvert.SerializeObject(info, Formatting.Indented));
Console.WriteLine("GameDir: " + gameDirectory);
Console.WriteLine("PatchDir: " + patchDirectory);
Console.WriteLine("PatchFile: " + patchFilePath);
}
else {
if(arguments.Length == 0) Fail("No target file specified");
string targetBasePath = Helpers.AbsolutePath(arguments[0]);
// patch archive
if(targetBasePath.EndsWith(Constants.ykc, StringComparison.OrdinalIgnoreCase)) {
if(arguments.Length == 1) Fail("No patch file specified");
string patchBasePath = Helpers.AbsolutePath(arguments[1]);
if(!File.Exists(targetBasePath)) Fail("The specified target archive does not exist");
if(!File.Exists(patchBasePath)) Fail("The specified patch archive does not exist");
Patch(targetBasePath, patchBasePath);
}
// patch file
else if(targetBasePath.EndsWith(Constants.ypl, StringComparison.OrdinalIgnoreCase)) {
dynamic info = JsonConvert.DeserializeObject(File.ReadAllText(targetBasePath));
string gameDirectory = info.gamedir;
string patchDirectory = info.patchdir;
string fetchUrl = info.fetchurl;
List<string> history = new List<string>();
foreach(string f in info.history) {
history.Add(f);
}
if(!Directory.Exists(gameDirectory)) Fail("Game directory does not exist");
if(!Directory.Exists(patchDirectory)) Fail("Patch directory does not exist");
// download new patch files
int finishedDownloads = 0, skippedDownloads = 0;
if(fetchUrl != null && fetchUrl.Length > 2) {
using(WebClient web = new WebClient()) {
Log("Fetching patch list from " + fetchUrl, ConsoleColor.Cyan);
string[] remoteFiles = web.DownloadString(fetchUrl).Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string fileUri in remoteFiles) {
if(fileUri == "") continue;
string fileName = Path.GetFileName(fileUri);
string filePath = Path.Combine(patchDirectory, fileName);
if(File.Exists(filePath)) {
skippedDownloads++;
}
else {
Log("Downloading " + fileName, ConsoleColor.Yellow);
web.DownloadFile(fileUri, filePath);
finishedDownloads++;
}
}
}
}
if(skippedDownloads + finishedDownloads > 0) {
Log("Downloaded " + finishedDownloads + " patches, skipped " + skippedDownloads, ConsoleColor.Green);
}
// apply patch files
int appliedPatches = 0, skippedPatches = 0;
string[] localFiles = Directory.GetFiles(patchDirectory, "*." + Constants.ykc);
foreach(string filePath in localFiles) {
string fileName = Path.GetFileName(filePath);
if(history.Contains(fileName)) {
skippedPatches++;
}
else {
bool found = false;
for(int i = 1; i <= 5; i++) {
string archiveName = "data0" + i;
string archivePath = Path.Combine(gameDirectory, archiveName + '.' + Constants.ykc);
if(fileName.Contains(archiveName) && File.Exists(archivePath)) {
if(flags.Has('v')) {
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Applying patch " + fileName);
Console.ResetColor();
}
found = true;
Patch(archivePath, filePath);
appliedPatches++;
break;
}
}
if(found) {
history.Add(fileName);
}
else {
Log("Could not determine target archive for patch '" + fileName + "'", ConsoleColor.Red);
}
}
}
if(skippedPatches + appliedPatches > 0) {
Log("Applied " + appliedPatches + " patches, skipped " + skippedPatches, ConsoleColor.Green);
}
info.history = JArray.FromObject(history.ToArray());
File.WriteAllText(targetBasePath, JsonConvert.SerializeObject(info, Formatting.Indented));
}
}
if(flags.Has('w')) {
Console.ReadLine();
}
}
19
View Source File : UriHelper.cs
License : Apache License 2.0
Project Creator : atteneder
License : Apache License 2.0
Project Creator : atteneder
public static bool? IsGltfBinary( Uri uri ) {
string path = uri.IsAbsoluteUri ? uri.LocalPath : uri.OriginalString;
var index = path.LastIndexOf('.',path.Length-1, Mathf.Min(5,path.Length) );
if(index<0) return null;
if(path.EndsWith(GltfGlobals.glbExt, StringComparison.OrdinalIgnoreCase)) {
return true;
}
if(path.EndsWith(GltfGlobals.gltfExt, StringComparison.OrdinalIgnoreCase)) {
return false;
}
return null;
}
19
View Source File : LambdaUtilities.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public static ConvertManifestContentToSdkManifestResult ConvertManifestContentToSdkManifest(string targetFramework, string packageManifestContent)
{
var originalDoc = XDoreplacedent.Parse(packageManifestContent);
var sdkType = originalDoc.Root.Attribute("Sdk")?.Value ?? "Microsoft.NET.Sdk";
var isWebSdk = string.Equals(sdkType, "Microsoft.NET.Sdk.Web", StringComparison.OrdinalIgnoreCase);
if (string.Equals("netcoreapp2.1", targetFramework) && !isWebSdk)
return new ConvertManifestContentToSdkManifestResult(false, packageManifestContent);
var root = new XElement("Project");
root.SetAttributeValue("Sdk", "Microsoft.NET.Sdk");
var itemGroup = new XElement("ItemGroup");
root.Add(itemGroup);
Version dotnetSdkVersion;
try
{
dotnetSdkVersion = Amazon.Common.DotNetCli.Tools.DotNetCLIWrapper.GetSdkVersion();
}
catch (Exception e)
{
throw new LambdaToolsException("Error detecting .NET SDK version: \n\t" + e.Message, LambdaToolsException.LambdaErrorCode.FailedToDetectSdkVersion, e );
}
if (isWebSdk)
{
if(string.Equals("netcoreapp2.1", targetFramework, StringComparison.OrdinalIgnoreCase))
{
if (dotnetSdkVersion < LambdaConstants.MINIMUM_DOTNET_SDK_VERSION_FOR_ASPNET_LAYERS)
{
throw new LambdaToolsException($"To create a runtime package store layer for an ASP.NET Core project " +
$"version {LambdaConstants.MINIMUM_DOTNET_SDK_VERSION_FOR_ASPNET_LAYERS} " +
"or above of the .NET Core SDK must be installed. " +
"If a 2.1.X SDK is used then the \"dotnet store\" command will include all " +
"of the ASP.NET Core dependencies that are already available in Lambda.",
LambdaToolsException.LambdaErrorCode.LayerNetSdkVersionMismatch);
}
// These were added to make sure the ASP.NET Core dependencies are filter if any of the packages
// depend on them.
// See issue for more info: https://github.com/dotnet/cli/issues/10784
var aspNerCorePackageReference = new XElement("PackageReference");
aspNerCorePackageReference.SetAttributeValue("Include", "Microsoft.AspNetCore.App");
itemGroup.Add(aspNerCorePackageReference);
var aspNerCoreUpdatePackageReference = new XElement("PackageReference");
aspNerCoreUpdatePackageReference.SetAttributeValue("Update", "Microsoft.NETCore.App");
aspNerCoreUpdatePackageReference.SetAttributeValue("Publish", "false");
itemGroup.Add(aspNerCoreUpdatePackageReference);
}
else
{
var frameworkReference = new XElement("FrameworkReference");
frameworkReference.SetAttributeValue("Include", "Microsoft.AspNetCore.App");
var frameworkReferenceGroupItemGroup = new XElement("ItemGroup");
frameworkReferenceGroupItemGroup.Add(frameworkReference);
root.Add(frameworkReferenceGroupItemGroup);
}
}
foreach (var packageReference in originalDoc.XPathSelectElements("//ItemGroup/PackageReference"))
{
var packageName = packageReference.Attribute("Include")?.Value;
var version = packageReference.Attribute("Version")?.Value;
if (string.Equals(packageName, "Microsoft.AspNetCore.App", StringComparison.OrdinalIgnoreCase) ||
string.Equals(packageName, "Microsoft.AspNetCore.All", StringComparison.OrdinalIgnoreCase))
continue;
var newRef = new XElement("PackageReference");
newRef.SetAttributeValue("Include", packageName);
newRef.SetAttributeValue("Version", version);
itemGroup.Add(newRef);
}
// In .NET Core 3.1 the dotnet store command will include system dependencies like System.Runtime if
// any of the packages referenced in the packages included explicit references system dependencies.
// This is common on older packages or versions of packages before .NET Core 2.1. Newtonsoft.Json version 9.0.1
// is an example of this behavior.
//
// To avoid these system dependencies getting added to the layer we need to inject the list of system
// dependency to prune from the store graph.
//
// For further information on the issue check out this GitHub issue: https://github.com/dotnet/sdk/issues/10973
if (string.Equals(targetFramework, "netcoreapp3.1", StringComparison.OrdinalIgnoreCase))
{
var lambdareplacedembly = typeof(LambdaUtilities).replacedembly;
string manifestName;
if (isWebSdk)
{
manifestName = lambdareplacedembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(LambdaConstants.PRUNE_LIST_SDKWEB_XML));
}
else
{
manifestName = lambdareplacedembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(LambdaConstants.PRUNE_LIST_SDK_XML));
}
string pruneListString;
using (var stream = lambdareplacedembly.GetManifestResourceStream(manifestName))
{
pruneListString = new StreamReader(stream).ReadToEnd();
}
var pruneListElement = XElement.Parse(pruneListString);
root.Add(pruneListElement);
}
var updatedDoc = new XDoreplacedent(root);
var updatedContent = updatedDoc.ToString();
return new ConvertManifestContentToSdkManifestResult(true, updatedContent);
}
19
View Source File : LambdaPackager.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
private static IList<string> CalculateRuntimeHierarchy()
{
var runtimeHierarchy = new List<string>();
var lambdareplacedembly = typeof(LambdaPackager).GetTypeInfo().replacedembly;
// The full name for the embedded resource changes between the dotnet CLI and AWS Toolkit for VS so just look for the resource by is file name.
var manifestName = lambdareplacedembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(LambdaConstants.RUNTIME_HIERARCHY));
using (var stream = typeof(LambdaPackager).GetTypeInfo().replacedembly.GetManifestResourceStream(manifestName))
using (var reader = new StreamReader(stream))
{
var rootData = JsonMapper.ToObject(reader.ReadToEnd());
var runtimes = rootData["runtimes"];
// Use a queue to do a breadth first search through the list of runtimes.
var queue = new Queue<string>();
queue.Enqueue(LambdaConstants.LEGACY_RUNTIME_HIERARCHY_STARTING_POINT);
while(queue.Count > 0)
{
var runtime = queue.Dequeue();
if (runtimeHierarchy.Contains(runtime))
continue;
runtimeHierarchy.Add(runtime);
var imports = runtimes[runtime]["#import"];
if (imports != null)
{
foreach (JsonData importedRuntime in imports)
{
queue.Enqueue(importedRuntime.ToString());
}
}
}
}
return runtimeHierarchy;
}
19
View Source File : EventInfoFilters.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
private static bool ExcludeKinesisTapSecurityEventsFilter(EventRecord eventInfo)
{
if (SECURITY_EVENTS_LABEL.Equals(eventInfo.LogName))
{
if (eventInfo.Properties != null)
{
if (eventInfo.Properties.Any(o => (o.Value as string)?.EndsWith(ConfigConstants.KINESISTAP_EXE_NAME, StringComparison.OrdinalIgnoreCase) ?? false))
return false;
}
}
return true;
}
19
View Source File : FileSystem.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
public virtual string CombinePaths(string first, params string[] others)
{
var result = (first ?? string.Empty).TrimEnd();
if (others == null) return result;
for(var i=0; i<others.Length; i++)
{
var other = others[i];
if (other==null) continue;
other = other.TrimStart();
if (other.Length==0) continue;
if (result.Length>0)
foreach(var ps in GeneralCapabilities.PathSeparatorCharacters)
if (result.EndsWith( ps.ToString()))
{
result = result.Substring(0, result.Length-1);
break;
}
foreach(var ps in GeneralCapabilities.PathSeparatorCharacters)
if (other.StartsWith( ps.ToString()))
{
other = other.Length>1 ? other.Substring(1) : string.Empty;
break;
}
result += GeneralCapabilities.PathSeparatorCharacters[0];
result += other;
result = result.TrimEnd();
}
return result;
}
19
View Source File : DiagnosticsController.cs
License : Apache License 2.0
Project Creator : Azure-App-Service
License : Apache License 2.0
Project Creator : Azure-App-Service
private void AddFilesToZip(ZipArchive zip)
{
foreach (var path in _paths)
{
if (Directory.Exists(path))
{
var dir = new DirectoryInfo(path);
if (path.EndsWith(Constants.LogFilesPath, StringComparison.Ordinal))
{
foreach (var info in dir.GetFileSystemInfos())
{
var directoryInfo = info as DirectoryInfo;
if (directoryInfo != null)
{
// excluding FREB as it contains user sensitive data such as authorization header
if (!info.Name.StartsWith("W3SVC", StringComparison.OrdinalIgnoreCase))
{
zip.AddDirectory(directoryInfo, _tracer, Path.Combine(dir.Name, info.Name));
}
}
else
{
zip.AddFile((FileInfo)info, _tracer, dir.Name);
}
}
}
else
{
zip.AddDirectory(dir, _tracer, Path.GetFileName(path));
}
}
else if (FileSystemHelpers.FileExists(path))
{
zip.AddFile(path, _tracer, String.Empty);
}
}
}
19
View Source File : VfsControllerBase.cs
License : Apache License 2.0
Project Creator : Azure-App-Service
License : Apache License 2.0
Project Creator : Azure-App-Service
internal string GetLocalFilePath()
{
// Restore the original extension if we had added a dummy
// See comment in TraceModule.OnBeginRequest
string result = GetOriginalLocalFilePath();
if (result.EndsWith(Constants.DummyRazorExtension, StringComparison.Ordinal))
{
result = result.Substring(0, result.Length - Constants.DummyRazorExtension.Length);
}
return result;
}
19
View Source File : PushDeploymentController.cs
License : Apache License 2.0
Project Creator : Azure-App-Service
License : Apache License 2.0
Project Creator : Azure-App-Service
private void ExtractTriggers(IRepository repository, ArtifactDeploymentInfo zipDeploymentInfo)
{
FileSystemHelpers.EnsureDirectory(zipDeploymentInfo.SyncFunctionsTriggersPath);
// Loading the zip file depends on how fast the file system is.
// Tested Azure Files share with a zip containing 120k files (160 MBs)
// takes 20 seconds to load. On my machine it takes 900 msec.
using (var zip = ZipFile.OpenRead(Path.Combine(_environment.SitePackagesPath, zipDeploymentInfo.ArtifactFileName)))
{
var entries = zip.Entries
// Only select host.json, proxies.json, or function.json that are from top level directories only
// Tested with a zip containing 120k files, and this took 90 msec
// on my machine.
.Where(e =>
e.FullName.Equals(Constants.FunctionsHostConfigFile, StringComparison.OrdinalIgnoreCase) ||
e.FullName.Equals(Constants.ProxyConfigFile, StringComparison.OrdinalIgnoreCase) ||
isFunctionJson(e.FullName));
foreach (var entry in entries)
{
var path = Path.Combine(zipDeploymentInfo.SyncFunctionsTriggersPath, entry.FullName);
FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(path));
entry.ExtractToFile(path, overwrite: true);
}
}
CommitRepo(repository, zipDeploymentInfo);
bool isFunctionJson(string fullName)
{
return fullName.EndsWith(Constants.FunctionsConfigFile) &&
fullName.Count(c => c == '/' || c == '\\') == 1;
}
}
19
View Source File : GOWatcher.cs
License : MIT License
Project Creator : badamczewski
License : MIT License
Project Creator : badamczewski
private void Initialize(string goFile, string outAsmFile)
{
XConsole.WriteLine("GO Lang Watcher Initialize:");
XConsole.WriteLine($"`Input File`: {goFile}");
XConsole.WriteLine($"`ASM File`: {outAsmFile}");
if (File.Exists(goFile) == false)
XConsole.WriteLine("'[WARNING]': Input File doesn't exist");
if (File.Exists(outAsmFile) == false)
XConsole.WriteLine("'[WARNING]': ASM File doesn't exist");
_pathToGOCompiler = _configuration["GOCompilerPath"];
if (_pathToGOCompiler.EndsWith(Path.DirectorySeparatorChar) == false)
{
_pathToGOCompiler += Path.DirectorySeparatorChar;
}
if(Directory.Exists(_pathToGOCompiler) == false)
XConsole.WriteLine("'[WARNING]': Compiler Directory Not Found");
XConsole.WriteLine($"`Compiler Path`: {_pathToGOCompiler}");
}
19
View Source File : ManagedDialogViewModel.cs
License : MIT License
Project Creator : bcssov
License : MIT License
Project Creator : bcssov
public void Ok()
{
if (SelectingFolder)
{
if (SelectedItems.Count > 0)
{
CompleteRequested?.Invoke(SelectedItems.Select(p => p.Path).ToArray());
}
else
{
CompleteRequested?.Invoke(new[] { Location });
}
}
else if (_savingFile)
{
if (!string.IsNullOrWhiteSpace(FileName))
{
var ext = !string.IsNullOrWhiteSpace(_defaultExtension) ?
(!_defaultExtension.StartsWith(".") ? $".{_defaultExtension}" : _defaultExtension) :
(!(SelectedFilter?.Extensions.FirstOrDefault()).StartsWith(".") ? $".{SelectedFilter?.Extensions.FirstOrDefault()}" : SelectedFilter?.Extensions.FirstOrDefault());
if (!string.IsNullOrWhiteSpace(ext) && !FileName.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
{
FileName += ext;
}
CompleteRequested?.Invoke(new[] { Path.Combine(Location, FileName) });
}
}
else
{
CompleteRequested?.Invoke(SelectedItems.Select(i => i.Path).ToArray());
}
}
19
View Source File : ModMergeExporter.cs
License : MIT License
Project Creator : bcssov
License : MIT License
Project Creator : bcssov
private Task<bool> CopyStreamAsync(string modPath, string modFile, string exportPath)
{
static async Task<bool> copyStream(Stream s, FileStream fs)
{
await s.CopyToAsync(fs);
await fs.DisposeAsync();
await s.DisposeAsync();
fs.Close();
s.Close();
return true;
}
var retry = new RetryStrategy();
var outPath = Path.Combine(exportPath, modFile);
var stream = reader.GetStream(modPath, modFile);
// If image and no stream try switching extension
if (Shared.Constants.ImageExtensions.Any(s => modFile.EndsWith(s, StringComparison.OrdinalIgnoreCase)) && stream == null)
{
var segments = modFile.Split(".", StringSplitOptions.RemoveEmptyEntries);
var file = string.Join(".", segments.Take(segments.Length - 1));
foreach (var item in Shared.Constants.ImageExtensions)
{
stream = reader.GetStream(modPath, file + item);
if (stream != null)
{
break;
}
}
}
if (!Directory.Exists(Path.GetDirectoryName(outPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(outPath));
}
if (File.Exists(outPath))
{
DiskOperations.DeleteFile(outPath);
}
var fs = new FileStream(outPath, FileMode.Create, FileAccess.Write, FileShare.Read);
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
return retry.RetryActionAsync(() =>
{
return copyStream(stream, fs);
});
}
19
View Source File : ArchiveFileReader.cs
License : MIT License
Project Creator : bcssov
License : MIT License
Project Creator : bcssov
public virtual bool CanRead(string path, bool searchSubFolders = true)
{
return File.Exists(path) && (path.EndsWith(Constants.ZipExtension, StringComparison.OrdinalIgnoreCase) || path.EndsWith(Constants.BinExtension, StringComparison.OrdinalIgnoreCase));
}
19
View Source File : DiskFileReader.cs
License : MIT License
Project Creator : bcssov
License : MIT License
Project Creator : bcssov
public virtual IReadOnlyCollection<IFileInfo> Read(string path, IEnumerable<string> allowedPaths, bool searchSubFolders = true)
{
var files = Directory.GetFiles(path, "*", searchSubFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
if (files?.Length > 0)
{
var result = new List<IFileInfo>();
foreach (var file in files)
{
var relativePath = file.Replace(path, string.Empty).Trim(Path.DirectorySeparatorChar);
if (searchSubFolders)
{
if (!relativePath.Contains(Path.DirectorySeparatorChar) ||
relativePath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Any(s => s.StartsWith(".")) ||
(allowedPaths?.Count() > 0 && !allowedPaths.Any(p => relativePath.StartsWith(p, StringComparison.OrdinalIgnoreCase))))
{
continue;
}
}
var info = DIResolver.Get<IFileInfo>();
var fileInfo = new System.IO.FileInfo(file);
info.IsReadOnly = fileInfo.IsReadOnly;
info.Size = fileInfo.Length;
using var stream = File.OpenRead(file);
info.FileName = relativePath;
if (Constants.TextExtensions.Any(s => file.EndsWith(s, StringComparison.OrdinalIgnoreCase)))
{
using var streamReader = new StreamReader(stream, true);
var text = streamReader.ReadToEnd();
streamReader.Close();
streamReader.Dispose();
info.IsBinary = false;
info.Content = text.SplitOnNewLine(false);
info.ContentSHA = text.CalculateSHA();
}
else
{
info.IsBinary = true;
using var fs = new FileStream(file, FileMode.Open, FileAccess.Read);
info.ContentSHA = fs.CalculateSHA();
}
result.Add(info);
}
return result;
}
return null;
}
19
View Source File : JsonFileReader.cs
License : MIT License
Project Creator : bcssov
License : MIT License
Project Creator : bcssov
public bool CanRead(string path, bool searchSubFolders = true)
{
return path.EndsWith(Constants.JsonExtension, StringComparison.OrdinalIgnoreCase);
}
19
View Source File : Reader.cs
License : MIT License
Project Creator : bcssov
License : MIT License
Project Creator : bcssov
public virtual IFileInfo GetFileInfo(string rootPath, string file)
{
var fileInfo = GetStreamInternal(rootPath, file);
using var stream = fileInfo.Item1;
if (stream != null)
{
var info = DIResolver.Get<IFileInfo>();
info.FileName = file;
info.IsReadOnly = fileInfo.Item2;
info.Size = stream.Length;
if (Constants.TextExtensions.Any(s => file.EndsWith(s, StringComparison.OrdinalIgnoreCase)))
{
using var streamReader = new StreamReader(stream, true);
var text = streamReader.ReadToEnd();
streamReader.Close();
streamReader.Dispose();
info.IsBinary = false;
info.Content = text.SplitOnNewLine(false);
info.ContentSHA = text.CalculateSHA();
}
else
{
info.IsBinary = true;
info.ContentSHA = stream.CalculateSHA();
}
return info;
}
return null;
}
19
View Source File : Reader.cs
License : MIT License
Project Creator : bcssov
License : MIT License
Project Creator : bcssov
public virtual Task<MemoryStream> GetImageStreamAsync(string rootPath, string file)
{
if (Constants.ImageExtensions.Any(p => file.EndsWith(p, StringComparison.OrdinalIgnoreCase)))
{
var stream = GetStream(rootPath, file);
return imageReader.Parse(stream, file);
}
return Task.FromResult((MemoryStream)null);
}
19
View Source File : Comments.cs
License : MIT License
Project Creator : bcssov
License : MIT License
Project Creator : bcssov
public static string GetEmptyCommentType(string filename)
{
if (filename.EndsWith(Constants.ShaderExtension, StringComparison.OrdinalIgnoreCase) || filename.EndsWith(Constants.FxhExtension, StringComparison.OrdinalIgnoreCase))
{
return Constants.EmptyShaderComment;
}
return Constants.EmptyOverwriteComment;
}
19
View Source File : StellarisValidation.cs
License : MIT License
Project Creator : bcssov
License : MIT License
Project Creator : bcssov
private bool IsValidExtension(string file)
{
return Shared.Constants.TextExtensions.Any(s => file.EndsWith(s, StringComparison.OrdinalIgnoreCase));
}
19
View Source File : PluginManager.cs
License : GNU General Public License v3.0
Project Creator : BepInEx
License : GNU General Public License v3.0
Project Creator : BepInEx
private static IEnumerable<IPlugin> LoadPluginsFromFile(string file, string exeName)
{
var plugins = new List<IPlugin>();
if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
return plugins;
try
{
var replacedembly = replacedembly.LoadFrom(file);
foreach (var t in GetTypesSafe(replacedembly))
if (typeof(IPlugin).IsreplacedignableFrom(t))
try
{
var pluginInstance = Activator.CreateInstance(t) as IPlugin;
if (pluginInstance == null)
{
IPALoader.Logger.LogWarning($"[WRN] Could not load {t.FullName} because types mismatch. Please check if you have multiple instances of IPA installed.");
continue;
}
string[] filter = null;
if (pluginInstance is IEnhancedPlugin plugin)
filter = plugin.Filter;
var exeNameTrimmed = exeName.ToLower().Replace(".exe", "").Trim();
if (filter == null || filter.Any(f => f.ToLower().Replace(".exe", "").Trim() == exeNameTrimmed))
plugins.Add(pluginInstance);
}
catch (Exception e)
{
IPALoader.Logger.LogWarning($"[WARN] Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
}
}
catch (Exception e)
{
IPALoader.Logger.LogError($"[ERROR] Could not load {Path.GetFileName(file)}! {e}");
}
return plugins;
}
19
View Source File : UI_SetControl.cs
License : GNU General Public License v3.0
Project Creator : berichan
License : GNU General Public License v3.0
Project Creator : berichan
public static bool IsInvalidFabricArray(this string[] fa)
{
foreach (string f in fa)
if (!(f.EndsWith("=" + ItemRemakeInfo.InvalidCheck) || f == string.Empty))
return false;
return true;
}
19
View Source File : UI_SetControl.cs
License : GNU General Public License v3.0
Project Creator : berichan
License : GNU General Public License v3.0
Project Creator : berichan
public static string[] TruncateEndInvalidValues(this string[] sa)
{
List<string> ls = new List<string>(sa);
for (int i = ls.Count-1; i > 0; --i)
{
if (ls[i].EndsWith("=" + ItemRemakeInfo.InvalidCheck) || ls[i] == string.Empty)
ls.RemoveAt(i);
else
break;
}
if (ls.Count > 0)
ls[0] = ls[0].Replace("=" + ItemRemakeInfo.InvalidCheck, string.Empty);
return ls.ToArray();
}
19
View Source File : System_StringWrap.cs
License : MIT License
Project Creator : bjfumac
License : MIT License
Project Creator : bjfumac
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int EndsWith(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 2)
{
System.String obj = (System.String)ToLua.CheckObject(L, 1, typeof(System.String));
string arg0 = ToLua.CheckString(L, 2);
bool o = obj.EndsWith(arg0);
LuaDLL.lua_pushboolean(L, o);
return 1;
}
else if (count == 3)
{
System.String obj = (System.String)ToLua.CheckObject(L, 1, typeof(System.String));
string arg0 = ToLua.CheckString(L, 2);
System.StringComparison arg1 = (System.StringComparison)ToLua.CheckObject(L, 3, typeof(System.StringComparison));
bool o = obj.EndsWith(arg0, arg1);
LuaDLL.lua_pushboolean(L, o);
return 1;
}
else if (count == 4)
{
System.String obj = (System.String)ToLua.CheckObject(L, 1, typeof(System.String));
string arg0 = ToLua.CheckString(L, 2);
bool arg1 = LuaDLL.luaL_checkboolean(L, 3);
System.Globalization.CultureInfo arg2 = (System.Globalization.CultureInfo)ToLua.CheckObject<System.Globalization.CultureInfo>(L, 4);
bool o = obj.EndsWith(arg0, arg1, arg2);
LuaDLL.lua_pushboolean(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: System.String.EndsWith");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
19
View Source File : Pluralizer.cs
License : Apache License 2.0
Project Creator : bricelam
License : Apache License 2.0
Project Creator : bricelam
string InternalPluralize(string word)
{
if (IsNoOpWord(word))
return word;
var suffixWord = GetSuffixWord(word, out var prefixWord);
// by me -> by me
if (IsNoOpWord(suffixWord))
return prefixWord + suffixWord;
// handle the word that do not inflect in the plural form
if (IsUninflective(suffixWord))
return prefixWord + suffixWord;
// if word is one of the known plural forms, then just return
if (_knownPluralWords.Contains(suffixWord.ToLowerInvariant()) || IsPlural(suffixWord))
return prefixWord + suffixWord;
// handle irregular plurals, e.g. "ox" -> "oxen"
if (_irregularPluralsList.TryGetValue(suffixWord, out var plural))
return prefixWord + plural;
// handle irregular inflections for common suffixes, e.g. "mouse" -> "mice"
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "man" },
(s) => s.Remove(s.Length - 2, 2) + "en",
out var newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "louse", "mouse" },
(s) => s.Remove(s.Length - 4, 4) + "ice",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "tooth" },
(s) => s.Remove(s.Length - 4, 4) + "eeth",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "goose" },
(s) => s.Remove(s.Length - 4, 4) + "eese",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "foot" },
(s) => s.Remove(s.Length - 3, 3) + "eet",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "zoon" },
(s) => s.Remove(s.Length - 3, 3) + "oa",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "cis", "sis", "xis" },
(s) => s.Remove(s.Length - 2, 2) + "es",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// handle replacedimilated clreplacedical inflections, e.g. vertebra -> vertebrae
if (_replacedimilatedClreplacedicalInflectionList.TryGetValue(suffixWord, out plural))
return prefixWord + plural;
// Handle the clreplacedical variants of modern inflections
// CONSIDER here is the only place we took the clreplacedical variants instead of the anglicized
if (_clreplacedicalInflectionList.TryGetValue(suffixWord, out plural))
return prefixWord + plural;
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "trix" },
(s) => s.Remove(s.Length - 1, 1) + "ces",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "eau", "ieu" },
(s) => s + "x",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "inx", "anx", "ynx" },
(s) => s.Remove(s.Length - 1, 1) + "ges",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// [cs]h and ss that take es as plural form
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "ch", "sh", "ss" },
(s) => s + "es",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// f, fe that take ves as plural form
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "alf", "elf", "olf", "eaf", "arf" },
(s) => s.EndsWith("deaf", true, _culture) ? s : s.Remove(s.Length - 1, 1) + "ves",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "nife", "life", "wife" },
(s) => s.Remove(s.Length - 2, 2) + "ves",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// y takes ys as plural form if preceded by a vowel, but ies if preceded by a consonant, e.g. stays, skies
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "ay", "ey", "iy", "oy", "uy" },
(s) => s + "s",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// CONSIDER proper noun handling, Marys, Tonys, ignore for now
if (suffixWord.EndsWith("y", true, _culture))
return prefixWord + suffixWord.Remove(suffixWord.Length - 1, 1) + "ies";
// handle some of the words o -> os, and [vowel]o -> os, and the rest are o->oes
if (_oSuffixList.TryGetValue(suffixWord, out plural))
return prefixWord + plural;
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "ao", "eo", "io", "oo", "uo" },
(s) => s + "s",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (suffixWord.EndsWith("o", true, _culture))
return prefixWord + suffixWord + "es";
if (suffixWord.EndsWith("x", true, _culture))
return prefixWord + suffixWord + "es";
// cats, bags, hats, speakers
return prefixWord + suffixWord + "s";
}
19
View Source File : Pluralizer.cs
License : Apache License 2.0
Project Creator : bricelam
License : Apache License 2.0
Project Creator : bricelam
string InternalSingularize(string word)
{
if (IsNoOpWord(word))
return word;
var suffixWord = GetSuffixWord(word, out var prefixWord);
if (IsNoOpWord(suffixWord))
return prefixWord + suffixWord;
// handle the word that is the same as the plural form
if (IsUninflective(suffixWord))
return prefixWord + suffixWord;
// if word is one of the known singular words, then just return
if (_knownSingularWords.Contains(suffixWord.ToLowerInvariant()))
return prefixWord + suffixWord;
// handle simple irregular verbs, e.g. was -> were
if (_irregularVerbReverseList.TryGetValue(suffixWord, out var singular))
return prefixWord + singular;
// handle irregular plurals, e.g. "ox" -> "oxen"
if (_irregularPluralsReverseList.TryGetValue(suffixWord, out singular))
return prefixWord + singular;
// handle singularization for words ending with sis and pluralized to ses,
// e.g. "ses" -> "sis"
if (_wordsEndingWithSisReverseList.TryGetValue(suffixWord, out singular))
return prefixWord + singular;
// handle words ending with se, e.g. "ses" -> "se"
if (_wordsEndingWithSeReverseList.TryGetValue(suffixWord, out singular))
return prefixWord + singular;
// handle irregular inflections for common suffixes, e.g. "mouse" -> "mice"
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "men" },
(s) => s.Remove(s.Length - 2, 2) + "an",
out var newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "lice", "mice" },
(s) => s.Remove(s.Length - 3, 3) + "ouse",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "teeth" },
(s) => s.Remove(s.Length - 4, 4) + "ooth",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "geese" },
(s) => s.Remove(s.Length - 4, 4) + "oose",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "feet" },
(s) => s.Remove(s.Length - 3, 3) + "oot",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "zoa" },
(s) => s.Remove(s.Length - 2, 2) + "oon",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// [cs]h and ss that take es as plural form, this is being moved up since the sses will be override by the ses
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "ches", "shes", "sses" },
(s) => s.Remove(s.Length - 2, 2),
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// handle replacedimilated clreplacedical inflections, e.g. vertebra -> vertebrae
if (_replacedimilatedClreplacedicalInflectionReverseList.TryGetValue(suffixWord, out singular))
return prefixWord + singular;
// Handle the clreplacedical variants of modern inflections
// CONSIDER here is the only place we took the clreplacedical variants instead of the anglicized
if (_clreplacedicalInflectionReverseList.TryGetValue(suffixWord, out singular))
return prefixWord + singular;
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "trices" },
(s) => s.Remove(s.Length - 3, 3) + "x",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "eaux", "ieux" },
(s) => s.Remove(s.Length - 1, 1),
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "inges", "anges", "ynges" },
(s) => s.Remove(s.Length - 3, 3) + "x",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// f, fe that take ves as plural form
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "alves", "elves", "olves", "eaves", "arves" },
(s) => s.Remove(s.Length - 3, 3) + "f",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "nives", "lives", "wives" },
(s) => s.Remove(s.Length - 3, 3) + "fe",
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// y takes ys as plural form if preceded by a vowel, but ies if preceded by a consonant, e.g. stays, skies
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "ays", "eys", "iys", "oys", "uys" },
(s) => s.Remove(s.Length - 1, 1),
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// CONSIDER proper noun handling, Marys, Tonys, ignore for now
if (suffixWord.EndsWith("ies", true, _culture))
return prefixWord + suffixWord.Remove(suffixWord.Length - 3, 3) + "y";
// handle some of the words o -> os, and [vowel]o -> os, and the rest are o->oes
if (_oSuffixReverseList.TryGetValue(suffixWord, out singular))
return prefixWord + singular;
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "aos", "eos", "ios", "oos", "uos" },
(s) => suffixWord.Remove(suffixWord.Length - 1, 1),
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
// CONSIDER limitation on the lines below, e.g. crisis -> crises -> cris
// all the word ending with sis, xis, cis, their plural form cannot be singularized correctly,
// since words ending with c and cis both will get pluralized to ces
// after searching the dictionary, the number of cis is just too small(7) that
// we treat them as special case
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "ces" },
(s) => s.Remove(s.Length - 1, 1),
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (TryInflectOnSuffixInWord(
suffixWord,
new[] { "ces", "ses", "xes" },
(s) => s.Remove(s.Length - 2, 2),
out newSuffixWord))
{
return prefixWord + newSuffixWord;
}
if (suffixWord.EndsWith("oes", true, _culture))
return prefixWord + suffixWord.Remove(suffixWord.Length - 2, 2);
if (suffixWord.EndsWith("ss", true, _culture))
return prefixWord + suffixWord;
if (suffixWord.EndsWith("s", true, _culture))
return prefixWord + suffixWord.Remove(suffixWord.Length - 1, 1);
// word is a singular
return prefixWord + suffixWord;
}
See More Examples