Here are the examples of the csharp api string.ToUpperInvariant() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1497 Examples
19
Source : OkHttpNetworkHandler.cs
with MIT License
from alexrainman
with MIT License
from alexrainman
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
var url = new Java.Net.URL(java_uri);
var body = default(RequestBody);
if (request.Content != null)
{
var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
var contentType = "text/plain";
if (request.Content.Headers.ContentType != null)
{
contentType = string.Join(" ", request.Content.Headers.GetValues("Content-Type"));
}
body = RequestBody.Create(bytes, MediaType.Parse(contentType));
}
var requestBuilder = new Request.Builder()
.Method(request.Method.Method.ToUpperInvariant(), body)
.Url(url);
if (DisableCaching)
{
requestBuilder.CacheControl(noCacheCacheControl);
}
var keyValuePairs = request.Headers
.Union(request.Content != null ?
request.Content.Headers :
Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>());
// Add Cookie Header if there's any cookie for the domain in the cookie jar
var stringBuilder = new StringBuilder();
if (client.CookieJar() != null)
{
var jar = client.CookieJar();
var cookies = jar.LoadForRequest(HttpUrl.Get(url));
foreach (var cookie in cookies)
{
stringBuilder.Append(cookie.Name() + "=" + cookie.Value() + ";");
}
}
foreach (var kvp in keyValuePairs)
{
if (kvp.Key == "Cookie")
{
foreach (var val in kvp.Value)
stringBuilder.Append(val + ";");
}
else
{
requestBuilder.AddHeader(kvp.Key, String.Join(getHeaderSeparator(kvp.Key), kvp.Value));
}
}
if (stringBuilder.Length > 0)
{
requestBuilder.AddHeader("Cookie", stringBuilder.ToString().TrimEnd(';'));
}
if (Timeout != null)
{
var clientBuilder = client.NewBuilder();
var timeout = (long)Timeout.Value.TotalSeconds;
clientBuilder.ConnectTimeout(timeout, TimeUnit.Seconds);
clientBuilder.WriteTimeout(timeout, TimeUnit.Seconds);
clientBuilder.ReadTimeout(timeout, TimeUnit.Seconds);
client = clientBuilder.Build();
}
cancellationToken.ThrowIfCancellationRequested();
var rq = requestBuilder.Build();
var call = client.NewCall(rq);
// NB: Even closing a socket must be done off the UI thread. Cray!
cancellationToken.Register(() => Task.Run(() => call.Cancel()));
var resp = default(Response);
try
{
resp = await call.EnqueueAsync().ConfigureAwait(false);
var newReq = resp.Request();
var newUri = newReq == null ? null : newReq.Url().Uri();
request.RequestUri = new Uri(newUri.ToString());
if (throwOnCaptiveNetwork && newUri != null)
{
if (url.Host != newUri.Host)
{
throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString()));
}
}
}
catch (IOException ex)
{
if (ex.Message.ToLowerInvariant().Contains("canceled"))
{
throw new System.OperationCanceledException();
}
// Calling HttpClient methods should throw .Net Exception when fail #5
throw new HttpRequestException(ex.Message, ex);
}
var respBody = resp.Body();
cancellationToken.ThrowIfCancellationRequested();
var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());
ret.RequestMessage = request;
ret.ReasonPhrase = resp.Message();
// ReasonPhrase is empty under HTTPS #8
if (string.IsNullOrEmpty(ret.ReasonPhrase))
{
try
{
ret.ReasonPhrase = ((ReasonPhrases)resp.Code()).ToString().Replace('_', ' ');
}
#pragma warning disable 0168
catch (Exception ex)
{
ret.ReasonPhrase = "Unreplacedigned";
}
#pragma warning restore 0168
}
if (respBody != null)
{
var content = new ProgressStreamContent(respBody.ByteStream(), CancellationToken.None);
content.Progress = getAndRemoveCallbackFromRegister(request);
ret.Content = content;
}
else
{
ret.Content = new ByteArrayContent(new byte[0]);
}
var respHeaders = resp.Headers();
foreach (var k in respHeaders.Names())
{
ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
}
return ret;
}
19
Source : RecordClass.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
public static bool TryParseShortString(string s, out RecordClreplaced recordClreplaced, bool allowAny = true)
{
if (String.IsNullOrEmpty(s))
{
recordClreplaced = RecordClreplaced.Invalid;
return false;
}
switch (s.ToUpperInvariant())
{
case "IN":
recordClreplaced = RecordClreplaced.INet;
return true;
case "CH":
recordClreplaced = RecordClreplaced.Chaos;
return true;
case "HS":
recordClreplaced = RecordClreplaced.Hesiod;
return true;
case "NONE":
recordClreplaced = RecordClreplaced.None;
return true;
case "*":
if (allowAny)
{
recordClreplaced = RecordClreplaced.Any;
return true;
}
else
{
recordClreplaced = RecordClreplaced.Invalid;
return false;
}
default:
if (s.StartsWith("CLreplaced", StringComparison.InvariantCultureIgnoreCase))
{
ushort clreplacedValue;
if (UInt16.TryParse(s.Substring(5), out clreplacedValue))
{
recordClreplaced = (RecordClreplaced) clreplacedValue;
return true;
}
}
recordClreplaced = RecordClreplaced.Invalid;
return false;
}
}
19
Source : NSUrlSessionHandler.cs
with MIT License
from alexrainman
with MIT License
from alexrainman
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var headers = request.Headers as IEnumerable<KeyValuePair<string, IEnumerable<string>>>;
var ms = new MemoryStream();
if (request.Content != null)
{
await request.Content.CopyToAsync(ms).ConfigureAwait(false);
headers = headers.Union(request.Content.Headers).ToArray();
}
// Add Cookie Header if any cookie for the domain in the cookie store
var stringBuilder = new StringBuilder();
var cookies = NSHttpCookieStorage.SharedStorage.Cookies
.Where(c => c.Domain == request.RequestUri.Host)
.Where(c => Utility.PathMatches(request.RequestUri.AbsolutePath, c.Path))
.ToList();
foreach (var cookie in cookies)
{
stringBuilder.Append(cookie.Name + "=" + cookie.Value + ";");
}
var rq = new NSMutableUrlRequest()
{
AllowsCellularAccess = true,
Body = NSData.FromArray(ms.ToArray()),
CachePolicy = (!this.DisableCaching ? NSUrlRequestCachePolicy.UseProtocolCachePolicy : NSUrlRequestCachePolicy.ReloadIgnoringCacheData),
Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => {
if (x.Key == "Cookie")
{
foreach (var val in x.Value)
stringBuilder.Append(val + ";");
}
else
{
acc.Add(new NSString(x.Key), new NSString(String.Join(getHeaderSeparator(x.Key), x.Value)));
}
return acc;
}),
HttpMethod = request.Method.ToString().ToUpperInvariant(),
Url = NSUrl.FromString(request.RequestUri.AbsoluteUri),
};
if (stringBuilder.Length > 0)
{
var copy = new NSMutableDictionary(rq.Headers);
copy.Add(new NSString("Cookie"), new NSString(stringBuilder.ToString().TrimEnd(';')));
rq.Headers = copy;
}
if (Timeout != null)
rq.TimeoutInterval = Timeout.Value.TotalSeconds;
var op = session.CreateDataTask(rq);
cancellationToken.ThrowIfCancellationRequested();
var ret = new TaskCompletionSource<HttpResponseMessage>();
cancellationToken.Register(() => ret.TrySetCanceled());
lock (inflightRequests)
{
inflightRequests[op] = new InflightOperation()
{
FutureResponse = ret,
Request = request,
Progress = getAndRemoveCallbackFromRegister(request),
ResponseBody = new ByteArrayListStream(),
CancellationToken = cancellationToken,
};
}
op.Resume();
return await ret.Task.ConfigureAwait(false);
}
19
Source : CloudEventContent.cs
with MIT License
from aliencube
with MIT License
from aliencube
private void SetCloudEventHeaders()
{
this.Headers.Add(CeEventTypeHeaderKey.ToUpperInvariant(), this.CloudEvent.EventType);
if (!string.IsNullOrWhiteSpace(this.CloudEvent.EventTypeVersion))
{
this.Headers.Add(CeEventTypeVersionHeaderKey.ToUpperInvariant(), this.CloudEvent.EventTypeVersion);
}
this.Headers.Add(CeCloudEventsVersionHeaderKey.ToUpperInvariant(), this.CloudEvent.CloudEventsVersion);
this.Headers.Add(CeSourceHeaderKey.ToUpperInvariant(), this.CloudEvent.Source.ToString());
this.Headers.Add(CeEventIdHeaderKey.ToUpperInvariant(), this.CloudEvent.EventId);
if (this.CloudEvent.EventTime.HasValue)
{
this.Headers.Add(CeEventTimeHeaderKey.ToUpperInvariant(), this.CloudEvent.EventTime.Value.ToString(TimestampFormat));
}
if (this.CloudEvent.SchemaUrl != null)
{
this.Headers.Add(CeSchemaUrlHeaderKey.ToUpperInvariant(), this.CloudEvent.SchemaUrl.ToString());
}
}
19
Source : MKL_IgnoreFortranAndUpperCaseDeclsPass.cs
with MIT License
from allisterb
with MIT License
from allisterb
public override bool VisitFunctionDecl(Function function)
{
if (function.PreprocessedEnreplacedies.Any(p => p.ToString().StartsWith("_MKL_API") || p.ToString().StartsWith("_mkl_api")))
{
function.ExplicitlyIgnore();
return false;
}
if (function.Name.EndsWith("_") || function.Name.ToUpperInvariant() == function.Name)
{
function.ExplicitlyIgnore();
return false;
}
return true;
}
19
Source : CountryCodeFlagConverter.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string code)
{
var resourceName = string.Format("{0}DrawingImage", code.ToUpperInvariant());
if (Application.Current.Resources.Contains(resourceName))
return Application.Current.Resources[resourceName];
}
return null;
}
19
Source : SelfUpdatePromptPage.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
public void CheckForUpdates()
{
try
{
Parallel.ForEach(new List<Action>()
{
() =>
{
// Get self-update.
var res = Properties.SettingsEx.Default.SelfUpdateDiscovery;
Trace.TraceInformation("Downloading self-update JSON discovery from {0}...", res.Uri.AbsoluteUri);
var obj = Properties.Settings.Default.ResponseCache.GetSeq(res, Window.Abort.Token);
var repoVersion = new Version((string)obj["version"]);
Trace.TraceInformation("Online version: {0}", repoVersion.ToString());
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
AvailableVersion = repoVersion;
Changelog = eduJSON.Parser.GetValue(obj, "changelog_uri", out string changelogUri) ? new Uri(changelogUri) : null;
Wizard.SelfUpdateProgressPage.DownloadUris = new List<Uri>(((List<object>)obj["uri"]).Select(uri => new Uri(res.Uri, (string)uri)));
Wizard.SelfUpdateProgressPage.Hash = ((string)obj["hash-sha256"]).FromHexToBin();
Wizard.SelfUpdateProgressPage.Arguments = eduJSON.Parser.GetValue(obj, "arguments", out string installerArguments) ? installerArguments : null;
}));
},
() =>
{
// Evaluate installed products.
Version productVersion = null;
var productId = Properties.Settings.Default.SelfUpdateBundleId.ToUpperInvariant();
Trace.TraceInformation("Evaluating installed products...");
using (var hklmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
using (var uninstallKey = hklmKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false))
{
foreach (var productKeyName in uninstallKey.GetSubKeyNames())
{
Window.Abort.Token.ThrowIfCancellationRequested();
using (var productKey = uninstallKey.OpenSubKey(productKeyName))
{
var bundleUpgradeCode = productKey.GetValue("BundleUpgradeCode");
if ((bundleUpgradeCode is string bundleUpgradeCodeString && bundleUpgradeCodeString.ToUpperInvariant() == productId ||
bundleUpgradeCode is string[] bundleUpgradeCodeArray && bundleUpgradeCodeArray.FirstOrDefault(code => code.ToUpperInvariant() == productId) != null) &&
productKey.GetValue("BundleVersion") is string bundleVersionString)
{
// Our product entry found.
productVersion = new Version(productKey.GetValue("DisplayVersion") is string displayVersionString ? displayVersionString : bundleVersionString);
Trace.TraceInformation("Installed version: {0}", productVersion.ToString());
break;
}
}
}
}
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { InstalledVersion = productVersion; }));
},
},
action =>
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
try { action(); }
finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
});
}
catch (AggregateException ex)
{
var nonCancelledException = ex.InnerExceptions.Where(innerException => !(innerException is OperationCanceledException));
if (nonCancelledException.Any())
throw new AggregateException(Resources.Strings.ErrorSelfUpdateDetection, nonCancelledException.ToArray());
throw new OperationCanceledException();
}
//// Mock the values for testing.
//InstalledVersion = new Version(1, 0);
//Properties.Settings.Default.SelfUpdateLastReminder = DateTime.MinValue;
try
{
if (new Version(Properties.Settings.Default.SelfUpdateLastVersion) == AvailableVersion &&
(Properties.Settings.Default.SelfUpdateLastReminder == DateTime.MaxValue ||
(DateTime.UtcNow - Properties.Settings.Default.SelfUpdateLastReminder).TotalDays < 3))
{
// We already prompted user for this version.
// Either user opted not to be reminded of this version update again,
// or it has been less than three days since the last prompt.
Trace.TraceInformation("Update deferred by user choice.");
return;
}
}
catch { }
if (InstalledVersion == null)
{
// Nothing to update.
Trace.TraceInformation("Product not installed or version could not be determined.");
return; // Quit self-updating.
}
if (AvailableVersion <= InstalledVersion)
{
// Product already up-to-date.
Trace.TraceInformation("Update not required.");
return;
}
// We're in the background thread - raise the prompt event via dispatcher.
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
if (Wizard.NavigateTo.CanExecute(this))
{
Properties.Settings.Default.SelfUpdateLastVersion = AvailableVersion.ToString();
Properties.Settings.Default.SelfUpdateLastReminder = DateTime.UtcNow;
Wizard.NavigateTo.Execute(this);
}
}));
}
19
Source : FourCC.cs
with MIT License
from amerkoleci
with MIT License
from amerkoleci
public string ToString(string format, IFormatProvider formatProvider)
{
if (string.IsNullOrEmpty(format))
{
format = "G";
}
if (formatProvider == null)
{
formatProvider = CultureInfo.CurrentCulture;
}
return format.ToUpperInvariant() switch
{
"G" => ToString(),
"I" => _value.ToString("X08", formatProvider),
_ => _value.ToString(format, formatProvider),
};
19
Source : SvnItem.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public static string MakeRelativeNoCase(string relativeFrom, string path)
{
string rp = MakeRelative(relativeFrom.ToUpperInvariant(), path.ToUpperInvariant());
if (string.IsNullOrEmpty(rp) || IsValidPath(rp))
return path;
int back = rp.LastIndexOf("..\\", StringComparison.Ordinal);
if (back >= 0)
{
int rest = rp.Length - back - 3;
return rp.Substring(0, back + 3) + path.Substring(path.Length - rest, rest);
}
else
return path.Substring(path.Length - rp.Length, rp.Length);
}
19
Source : SvnSccProvider.Enlistment.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
protected override void Translate_SolutionRenamed(string oldName, string newName)
{
string oldDir = Path.GetDirectoryName(oldName);
string newDir = Path.GetDirectoryName(newName);
string newNameU = newName.ToUpperInvariant();
if (oldDir == newDir)
return;
string oldDirRoot = Path.GetPathRoot(oldDir);
Dictionary<string, string> oldNameMap = new Dictionary<string, string>(_trueNameMap);
_trueNameMap.Clear();
foreach (KeyValuePair<string, string> kv in oldNameMap)
{
if (!IsSafeSccPath(kv.Key) || !IsSafeSccPath(kv.Value))
{
// Just copy translations like http://localhost
_trueNameMap.Add(kv.Key, kv.Value);
continue;
}
string newRel = SvnItem.MakeRelativeNoCase(newName, kv.Key);
if (IsSafeSccPath(newRel))
continue; // Not relative from .sln after
string newPath = Path.GetFullPath(Path.Combine(newDir, newRel));
if (newPath == kv.Key)
continue; // No translation necessary after the rename
_trueNameMap[kv.Key] = newPath;
}
}
19
Source : AnkhDiff.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
bool TryGetValue(string key, bool vsStyle, string arg, out string value)
{
if (key == null)
throw new ArgumentNullException("key");
key = key.ToUpperInvariant();
value = null;
string v;
switch (key)
{
case "BASE":
if (DiffArgs != null)
value = DiffArgs.BaseFile;
else
return false;
break;
case "BNAME":
case "BASENAME":
if (DiffArgs != null)
value = DiffArgs.Basereplacedle ?? Path.GetFileName(DiffArgs.BaseFile);
else
return false;
break;
case "MINE":
if (DiffArgs != null)
value = DiffArgs.MineFile;
else
return false;
break;
case "YNAME":
case "MINENAME":
if (DiffArgs != null)
value = DiffArgs.Minereplacedle ?? Path.GetFileName(DiffArgs.MineFile);
else
return false;
break;
case "THEIRS":
if (MergeArgs != null)
value = MergeArgs.TheirsFile;
else
return false;
break;
case "TNAME":
case "THEIRNAME":
case "THEIRSNAME":
if (MergeArgs != null)
value = MergeArgs.Theirsreplacedle ?? Path.GetFileName(MergeArgs.TheirsFile);
else
return false;
break;
case "MERGED":
if (MergeArgs != null)
value = MergeArgs.MergedFile;
else
return false;
break;
case "MERGEDNAME":
case "MNAME":
if (MergeArgs != null)
value = MergeArgs.Mergedreplacedle ?? Path.GetFileName(MergeArgs.MergedFile);
else
return false;
break;
case "PATCHFILE":
if (PatchArgs != null)
value = PatchArgs.PatchFile;
else
return false;
break;
case "APPLYTODIR":
if (PatchArgs != null)
value = PatchArgs.ApplyTo;
else
return false;
break;
case "APPPATH":
v = _diff.GetAppPath(arg, _toolMode);
value = _diff.SubsreplaceduteArguments(v ?? "", DiffArgs, _toolMode);
break;
case "APPTEMPLATE":
v = _diff.GetAppTemplate(arg, _toolMode);
value = _diff.SubsreplaceduteArguments(v ?? "", DiffArgs, _toolMode);
break;
case "PROGRAMFILES":
// Return the environment variable if using environment variable style
value = (vsStyle ? null : Environment.GetEnvironmentVariable(key)) ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
break;
case "COMMONPROGRAMFILES":
// Return the environment variable if using environment variable style
value = (vsStyle ? null : Environment.GetEnvironmentVariable(key)) ?? Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles);
break;
case "HOSTPROGRAMFILES":
// Use the WOW64 program files directory if available, otherwise just program files
value = Environment.GetEnvironmentVariable("PROGRAMW6432") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
break;
case "APPDATA":
value = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
break;
case "LOCALAPPDATA":
value = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
break;
case "READONLY":
if (DiffArgs != null && DiffArgs.ReadOnly)
value = "1";
else
value = "";
break;
case "VSHOME":
IVsSolution sol = GetService<IVsSolution>(typeof(SVsSolution));
if (sol == null)
return false;
object val;
if (VSErr.Succeeded(sol.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out val)))
value = val as string;
return true;
default:
// Just replace with "" if unknown
v = Environment.GetEnvironmentVariable(key);
if (!string.IsNullOrEmpty(v))
value = v;
return (value != null);
}
return true;
}
19
Source : ProjectTracker.Solution.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from 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;
}
19
Source : AnkhEditorFactory.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
static void AddEditorInfo(Hashtable editors, string ext, EditorInfo ei)
{
ext = ext.ToUpperInvariant();
EditorInfo other = (EditorInfo)editors[ext];
if (other != null)
{
EditorInfo previous = null;
while (other != null && other.Priority > ei.Priority)
{
previous = other;
other = other.Next;
}
if (previous == null)
{
editors[ext] = ei;
ei.Next = other;
}
else
{
ei.Next = previous.Next;
previous.Next = ei;
}
}
else
{
editors[ext] = ei;
}
}
19
Source : AnkhEditorFactory.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public virtual EditorInfo GetRegisteredEditorInfo(string extension)
{
string key = extension.ToUpperInvariant();
return (EditorInfo)GetEditors(this.site)[key];
}
19
Source : UwpProjectPostProcess.cs
with MIT License
from anderm
with MIT License
from anderm
private static void UpdateDefineConstants(XmlElement defineConstants, string configuration, string platform)
{
if (defineConstants == null)
{
return;
}
IEnumerable<string> symbols = defineConstants.InnerText.Split(';').Except(new[]
{
string.Empty,
BuildSLNUtilities.BuildSymbolDebug,
BuildSLNUtilities.BuildSymbolRelease,
BuildSLNUtilities.BuildSymbolMaster
}).Union(new[] { configuration.ToUpperInvariant() });
defineConstants.InnerText = string.Join(";", symbols.ToArray());
//UnityEngine.Debug.LogFormat("Updating defines for Configuration|Platform: {0}|{1} => {2}", configuration, platform, defineConstants.InnerText);
}
19
Source : SqlNameMangling.cs
with GNU General Public License v3.0
from anderson-joyle
with GNU General Public License v3.0
from anderson-joyle
public static string GetSqlTableName(string tableName)
{
tableName = tableName.ToUpperInvariant();
if (ReservedKeywordsSet.Contains(tableName))
{
tableName += "_";
}
return tableName;
}
19
Source : SqlNameMangling.cs
with GNU General Public License v3.0
from anderson-joyle
with GNU General Public License v3.0
from anderson-joyle
public static string GetValidSqlName(string nameOfField, int arrayIndex)
{
// Support for Table Extension
nameOfField = nameOfField.Contains(ExtensionNameSeparator) ? nameOfField.Replace(ExtensionNameSeparator, '$') : nameOfField;
nameOfField = nameOfField.ToUpperInvariant();
if (nameOfField[0] == '.')
{
nameOfField = "$" + nameOfField.Substring(1);
}
else if (nameOfField[0] == ':')
{
nameOfField = X + nameOfField.Substring(1);
}
else if (nameOfField[0] == '_')
{
nameOfField = X + nameOfField.Substring(1);
}
StringBuilder filtered = new StringBuilder(nameOfField.Length);
for (int i = 0; i < nameOfField.Length; i++)
{
char current = nameOfField[i];
if (current > 127)
{
filtered.Append(X);
}
else
{
filtered.Append(current);
}
}
nameOfField = filtered.ToString();
if (arrayIndex > 1)
{
// generate array fields like Dim, Dim2_, Dim3_ ...
nameOfField += arrayIndex + "_";
}
// handle reserved keywords like "key", "percent" etc.
else if (ReservedKeywordsSet.Contains(nameOfField))
{
nameOfField += "_";
}
return nameOfField;
}
19
Source : SqlNameMangling.cs
with GNU General Public License v3.0
from anderson-joyle
with GNU General Public License v3.0
from anderson-joyle
public static string GetValidSqlNameForField(string fieldName)
{
fieldName = fieldName.ToUpperInvariant();
Boolean hasReservedWord = ReservedKeywordsSet.Contains(fieldName);
// split Dim[2] in [] {"Dim", 2}
var arrayField = fieldName.Split(ArrayIndexFieldSplitter, StringSplitOptions.RemoveEmptyEntries);
if (arrayField.Count() > 1)
{
// Dim[1] is Dim, Dim[2] is Dim2_, Key[1] is Key_ and Key[2] is Key_2_ (key is reserved word)
int arrayIndex = Convert.ToInt32(arrayField[1], CultureInfo.InvariantCulture);
fieldName = arrayField[0];
if (hasReservedWord)
{
fieldName += "_";
}
if (arrayIndex > 1)
{
fieldName += arrayField[1] + "_";
}
}
else if (hasReservedWord)
{
fieldName += "_";
}
return fieldName;
}
19
Source : DeepL_Website.cs
with GNU General Public License v3.0
from AndrasMumm
with GNU General Public License v3.0
from AndrasMumm
public async Task ForceTranslate()
{
double spanDiff = MaxDelaySeconds - MinDelaySeconds;
double waitIntervalMs = MaxDelaySeconds + (RandomNumbers.NextDouble() * spanDiff) * 1000;
double timeWeNeedToWait = waitIntervalMs - DateTime.Now.Subtract(_LastTimeTranslated).Milliseconds;
if (timeWeNeedToWait > 0)
{
Thread.Sleep((int)Math.Floor(timeWeNeedToWait));
}
try
{
await _Sem.WaitAsync();
RequestListManipMutex.WaitOne();
_CurrentlyTranslating = _Requests;
_Requests = new List<TranslationRequest>();
RequestListManipMutex.ReleaseMutex();
await EnsureSetupState();
_TranslationCount++;
_ID++;
// construct json content
long r = (long)(DateTime.UtcNow - Epoch).TotalMilliseconds;
long n = 1;
var builder = new StringBuilder();
builder.Append("{\"jsonrpc\":\"2.0\",\"method\": \"LMT_handle_jobs\",\"params\":{\"jobs\":[");
List<UntranslatedTextInfo> untranslatedTextInfos = new List<UntranslatedTextInfo>();
foreach (var translationRequest in _CurrentlyTranslating)
{
List<TranslationPart> parts = NewlineSplitter
.Split(translationRequest.Text)
.Select(x => new TranslationPart { Value = x, IsTranslatable = !NewlineSplitter.IsMatch(x) })
.ToList();
var usableParts = parts
.Where(x => x.IsTranslatable)
.Select(x => x.Value)
.ToArray();
for (int i = 0; i < usableParts.Length; i++)
{
var usablePart = usableParts[i];
builder.Append("{\"kind\":\"default\",\"preferred_num_beams\":1,\"raw_en_sentence\":\""); // yes.. "en" no matter what source language is used
builder.Append(JsonHelper.Escape(usablePart));
var addedContext = new HashSet<string>();
builder.Append("\",\"raw_en_context_before\":[");
bool addedAnyBefore = false;
foreach (var contextBefore in translationRequest.PreContext)
{
if (!addedContext.Contains(contextBefore))
{
builder.Append("\"");
builder.Append(JsonHelper.Escape(contextBefore));
builder.Append("\"");
builder.Append(",");
addedAnyBefore = true;
}
}
for (int j = 0; j < i; j++)
{
if (!addedContext.Contains(usableParts[j]))
{
builder.Append("\"");
builder.Append(JsonHelper.Escape(usableParts[j]));
builder.Append("\"");
builder.Append(",");
addedAnyBefore = true;
}
}
if (addedAnyBefore)
{
builder.Remove(builder.Length - 1, 1);
}
builder.Append("],\"raw_en_context_after\":[");
bool addedAnyAfter = false;
for (int j = i + 1; j < usableParts.Length; j++)
{
if (!addedContext.Contains(usableParts[j]))
{
builder.Append("\"");
builder.Append(JsonHelper.Escape(usableParts[j]));
builder.Append("\"");
builder.Append(",");
addedAnyAfter = true;
}
}
foreach (var contextAfter in translationRequest.PostContext)
{
if (!addedContext.Contains(contextAfter))
{
builder.Append("\"");
builder.Append(JsonHelper.Escape(contextAfter));
builder.Append("\"");
builder.Append(",");
addedAnyAfter = true;
}
}
if (addedAnyAfter)
{
builder.Remove(builder.Length - 1, 1);
}
//builder.Append("],\"quality\":\"fast\"},");
builder.Append("]},");
n += usablePart.Count(c => c == 'i');
}
untranslatedTextInfos.Add(new UntranslatedTextInfo { TranslationParts = parts, UntranslatedText = translationRequest.Text });
}
builder.Remove(builder.Length - 1, 1); // remove final ","
var timestamp = r + (n - r % n);
builder.Append("],\"lang\":{\"user_preferred_langs\":[\"");
builder.Append("en".ToUpperInvariant());
builder.Append("\",\"");
builder.Append("zh".ToUpperInvariant());
builder.Append("\"],\"source_lang_user_selected\":\"");
builder.Append("zh".ToUpperInvariant());
builder.Append("\",\"target_lang\":\"");
builder.Append("en".ToUpperInvariant());
builder.Append("\"},\"priority\":1,\"commonJobParams\":{\"formality\":null},\"timestamp\":");
builder.Append(timestamp.ToString(CultureInfo.InvariantCulture));
builder.Append("},\"id\":");
builder.Append(_ID);
builder.Append("}");
var content = builder.ToString();
var stringContent = new StringContent(content);
using var request = new HttpRequestMessage(HttpMethod.Post, HttpsServicePointTemplateUrl);
AddHeaders(request, stringContent, RequestType.Translation);
request.Content = stringContent;
// create request
using var response = await _Client.SendAsync(request);
response.ThrowIfBlocked();
response.EnsureSuccessStatusCode();
var str = await response.Content.ReadreplacedtringAsync();
ExtractTranslation(str, untranslatedTextInfos);
_LastTimeTranslated = DateTime.Now;
}
catch (BlockedException)
{
Reset();
throw;
}
finally
{
_Sem.Release();
}
}
19
Source : RegistryExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
public static RegistryHive GetRegistryHive(string fullName)
{
int index = fullName.IndexOf('\\');
string root = index >= 0 ? fullName.Substring(0, index) : fullName;
switch (root.ToUpperInvariant())
{
case LocalMachine:
return RegistryHive.LocalMachine;
case CurrentUser:
return RegistryHive.CurrentUser;
case ClreplacedesRoot:
return RegistryHive.ClreplacedesRoot;
}
throw new ArgumentException();
}
19
Source : HaveIBeenPwnedPasswordChecker.cs
with MIT License
from andrew-schofield
with MIT License
from andrew-schofield
private async Task<List<HaveIBeenPwnedPreplacedwordEntry>> GetBreaches(IProgress<ProgressItem> progressIndicator, IEnumerable<PwEntry> entries, Func<bool> canContinue)
{
List<HaveIBeenPwnedPreplacedwordEntry> allBreaches = new List<HaveIBeenPwnedPreplacedwordEntry>();
int counter = 0;
SHA1 sha = new SHA1CryptoServiceProvider();
Dictionary<string, bool> cache = new Dictionary<string, bool>();
foreach (var entry in entries)
{
if (!canContinue())
{
break;
}
counter++;
progressIndicator.Report(new ProgressItem((uint)((double)counter / entries.Count() * 100), string.Format("Checking \"{0}\" for breaches", entry.Strings.ReadSafe(PwDefs.replacedleField))));
if(entry.Strings.Get(PwDefs.PreplacedwordField) == null || string.IsNullOrWhiteSpace(entry.Strings.ReadSafe(PwDefs.PreplacedwordField)) || entry.Strings.ReadSafe(PwDefs.PreplacedwordField).StartsWith("{REF:")) continue;
var preplacedwordHash = string.Join("", sha.ComputeHash(entry.Strings.Get(PwDefs.PreplacedwordField).ReadUtf8()).Select(x => x.ToString("x2"))).ToUpperInvariant();
if (cache.ContainsKey(preplacedwordHash))
{
if (cache[preplacedwordHash])
{
allBreaches.Add(new HaveIBeenPwnedPreplacedwordEntry(entry.Strings.ReadSafe(PwDefs.UserNameField), entry.GetUrlDomain(), entry));
}
continue;
}
var prefix = preplacedwordHash.Substring(0, 5);
using (var response = await client.GetAsync(string.Format(API_URL, prefix)))
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
cache[preplacedwordHash] = false;
var stream = await response.Content.ReadreplacedtreamAsync();
using (var reader = new StreamReader(stream))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
var parts = line.Split(':');
var suffix = parts[0];
var count = int.Parse(parts[1]);
if (prefix + suffix == preplacedwordHash)
{
allBreaches.Add(new HaveIBeenPwnedPreplacedwordEntry(entry.Strings.ReadSafe(PwDefs.UserNameField), entry.GetUrlDomain(), entry));
cache[preplacedwordHash] = true;
}
}
}
}
}
}
return allBreaches;
}
19
Source : PathUtility.cs
with MIT License
from AndresTraks
with MIT License
from AndresTraks
public static string MakeRelativePath(string fromPath, string toPath)
{
if (string.IsNullOrEmpty(fromPath)) throw new ArgumentNullException(nameof(fromPath));
if (string.IsNullOrEmpty(toPath)) throw new ArgumentNullException(nameof(toPath));
var fromUri = new Uri(fromPath);
var toUri = new Uri(toPath);
if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.
var relativeUri = fromUri.MakeRelativeUri(toUri);
var relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.ToUpperInvariant() == "FILE")
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
19
Source : HelpPageSampleKey.cs
with GNU General Public License v3.0
from andysal
with GNU General Public License v3.0
from andysal
public override int GetHashCode()
{
int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();
if (MediaType != null)
{
hashCode ^= MediaType.GetHashCode();
}
if (SampleDirection != null)
{
hashCode ^= SampleDirection.GetHashCode();
}
if (ParameterType != null)
{
hashCode ^= ParameterType.GetHashCode();
}
foreach (string parameterName in ParameterNames)
{
hashCode ^= parameterName.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
19
Source : RequestReader.cs
with MIT License
from angelobreuer
with MIT License
from angelobreuer
private static Version GetHttpVersion(string versionString) => versionString.ToUpperInvariant()
19
Source : ToUpperConverter.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
return value.ToString().ToUpperInvariant();
else
return value;
}
19
Source : MatchingTextureSet.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void InitRegex()
{
// Make the regex string that handles all filters
StringBuilder regexstr = new StringBuilder("");
foreach (string s in this.filters)
{
// Make sure filter is in uppercase
string ss = s.ToUpperInvariant();
// Escape regex characters
ss = ss.Replace("+", "\\+");
ss = ss.Replace("\\", "\\\\");
ss = ss.Replace("|", "\\|");
ss = ss.Replace("{", "\\{");
ss = ss.Replace("[", "\\[");
ss = ss.Replace("(", "\\(");
ss = ss.Replace(")", "\\)");
ss = ss.Replace("^", "\\^");
ss = ss.Replace("$", "\\$");
ss = ss.Replace(".", "\\.");
ss = ss.Replace("#", "\\#");
ss = ss.Replace(" ", "\\ ");
// Replace the ? with the regex code for single character
ss = ss.Replace("?", ".");
// Replace the * with the regex code for optional multiple characters
ss = ss.Replace("*", ".*?");
// When a filter has already added, insert a conditional OR operator
if (regexstr.Length > 0) regexstr.Append("|");
// Open group without backreferencing
regexstr.Append("(?:");
// Must be start of string
regexstr.Append("\\A");
// Add the filter
regexstr.Append(ss);
// Must be end of string
regexstr.Append("\\Z");
// Close group
regexstr.Append(")");
}
// No filters added? Then make a never-matching regex
if (this.filters.Count == 0) regexstr.Append("\\Z\\A");
// Make the regex
regex = new Regex(regexstr.ToString(), RegexOptions.Compiled |
RegexOptions.CultureInvariant);
}
19
Source : PK3StructuredReader.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private ICollection<ImageData> LoadDirectoryImagesAndCategorize(string path, int imagetype, Dictionary<long, ImageData> targetlist, bool bFlat)
{
List<ImageData> images = new List<ImageData>();
string[] files;
string name;
int maxTextureNameLength = General.Map.Config.MaxTextureNamelength;
// Go for all files
files = GetAllFiles(path, true);
foreach (string f in files)
{
// Make the texture name from filename without extension
name = Path.GetFileNameWithoutExtension(f).ToUpperInvariant();
if ((maxTextureNameLength > 0) && (name.Length > maxTextureNameLength)) name = name.Substring(0, maxTextureNameLength);
if (name.Length > 0)
{
// Add image to list
ImageData src = CreateImage(name, f, imagetype);
// Check if exists in target list
if (!targetlist.ContainsKey(src.LongName))
{
targetlist.Add(src.LongName, src);
// can't be out of bounds by definition
string subfolder = Path.GetDirectoryName(f.Substring(path.Length + 1));
if (subfolder.Length > 0)
{
if (!subtexturesets.ContainsKey(subfolder))
{
subtexturesets.Add(subfolder, new ResourceTextureSet(subfolder + " (" + Getreplacedle() + ")", location));
}
if (bFlat)
{
subtexturesets[subfolder].AddFlat(src);
}
else
{
subtexturesets[subfolder].AddTexture(src);
}
}
}
}
else
{
// Can't load image without name
General.ErrorLogger.Add(ErrorType.Error, "Can't load an unnamed texture from \"" + path + "\". Please consider giving names to your resources.");
}
}
// Return result
return images;
}
19
Source : ScriptEditorControl.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public void SetupStyles(ScriptConfiguration config)
{
Stream lexersdata;
StreamReader lexersreader;
Configuration lexercfg = new Configuration();
SortedList<string, string> autocompletelist;
string[] resnames;
int imageindex;
// Make collections
stylelookup = new Dictionary<int, ScriptStyleType>();
autocompletelist = new SortedList<string, string>(StringComparer.Ordinal);
// Keep script configuration
if(scriptconfig != config) scriptconfig = config;
// Find a resource named Lexers.cfg
resnames = General.Thisreplacedembly.GetManifestResourceNames();
foreach(string rn in resnames)
{
// Found one?
if(rn.EndsWith(LEXERS_RESOURCE, StringComparison.InvariantCultureIgnoreCase))
{
// Get a stream from the resource
lexersdata = General.Thisreplacedembly.GetManifestResourceStream(rn);
lexersreader = new StreamReader(lexersdata, Encoding.ASCII);
// Load configuration from stream
lexercfg.InputConfiguration(lexersreader.ReadToEnd());
// Done with the resource
lexersreader.Dispose();
lexersdata.Dispose();
}
}
// Check if specified lexer exists and set the lexer to use
string lexername = "lexer" + scriptconfig.Lexer.ToString(CultureInfo.InvariantCulture);
if(!lexercfg.SettingExists(lexername)) throw new InvalidOperationException("Unknown lexer " + scriptconfig.Lexer + " specified in script configuration!");
scriptedit.Lexer = scriptconfig.Lexer;
// Set the default style and settings
scriptedit.StyleSetFont(DEFAULT_STYLE, General.Settings.ScriptFontName);
scriptedit.StyleSetSize(DEFAULT_STYLE, General.Settings.ScriptFontSize);
scriptedit.StyleSetBold(DEFAULT_STYLE, General.Settings.ScriptFontBold);
scriptedit.StyleSereplacedalic(DEFAULT_STYLE, false);
scriptedit.StyleSetUnderline(DEFAULT_STYLE, false);
scriptedit.StyleSetCase(DEFAULT_STYLE, ScriptCaseVisible.Mixed);
scriptedit.StyleSetFore(DEFAULT_STYLE, General.Colors.PlainText.ToColorRef());
scriptedit.StyleSetBack(DEFAULT_STYLE, General.Colors.ScriptBackground.ToColorRef());
scriptedit.CaretPeriod = SystemInformation.CaretBlinkTime;
scriptedit.CaretFore = General.Colors.ScriptBackground.Inverse().ToColorRef();
scriptedit.StyleBits = 7;
// These don't work?
scriptedit.TabWidth = General.Settings.ScriptTabWidth;
scriptedit.IsUseTabs = false;
scriptedit.IsTabIndents = true;
scriptedit.Indent = General.Settings.ScriptTabWidth;
scriptedit.IsBackSpaceUnIndents = true;
// This applies the default style to all styles
scriptedit.StyleClearAll();
// Set the code page to use
scriptedit.CodePage = scriptconfig.CodePage;
// Set the default to something normal (this is used by the autocomplete list)
scriptedit.StyleSetFont(DEFAULT_STYLE, this.Font.Name);
scriptedit.StyleSetBold(DEFAULT_STYLE, this.Font.Bold);
scriptedit.StyleSereplacedalic(DEFAULT_STYLE, this.Font.Italic);
scriptedit.StyleSetUnderline(DEFAULT_STYLE, this.Font.Underline);
scriptedit.StyleSetSize(DEFAULT_STYLE, (int)Math.Round(this.Font.SizeInPoints));
// Set style for linenumbers and margins
scriptedit.StyleSetBack((int)ScriptStylesCommon.LineNumber, General.Colors.ScriptBackground.ToColorRef());
// Clear all keywords
for(int i = 0; i < 9; i++) scriptedit.KeyWords(i, null);
// Now go for all elements in the lexer configuration
// We are looking for the numeric keys, because these are the
// style index to set and the value is our ScriptStyleType
IDictionary dic = lexercfg.ReadSetting(lexername, new Hashtable());
foreach(DictionaryEntry de in dic)
{
// Check if this is a numeric key
int stylenum = -1;
if(int.TryParse(de.Key.ToString(), out stylenum))
{
// Add style to lookup table
stylelookup.Add(stylenum, (ScriptStyleType)(int)de.Value);
// Apply color to style
int colorindex = 0;
switch((ScriptStyleType)(int)de.Value)
{
case ScriptStyleType.PlainText: colorindex = ColorCollection.PLAINTEXT; break;
case ScriptStyleType.Comment: colorindex = ColorCollection.COMMENTS; break;
case ScriptStyleType.Constant: colorindex = ColorCollection.CONSTANTS; break;
case ScriptStyleType.Keyword: colorindex = ColorCollection.KEYWORDS; break;
case ScriptStyleType.LineNumber: colorindex = ColorCollection.LINENUMBERS; break;
case ScriptStyleType.Literal: colorindex = ColorCollection.LITERALS; break;
default: colorindex = ColorCollection.PLAINTEXT; break;
}
scriptedit.StyleSetFore(stylenum, General.Colors.Colors[colorindex].ToColorRef());
}
}
// Create the keywords list and apply it
imageindex = (int)ImageIndex.ScriptKeyword;
int keywordsindex = lexercfg.ReadSetting(lexername + ".keywordsindex", -1);
if(keywordsindex > -1)
{
StringBuilder keywordslist = new StringBuilder("");
foreach(string k in scriptconfig.Keywords)
{
if(keywordslist.Length > 0) keywordslist.Append(" ");
keywordslist.Append(k);
autocompletelist.Add(k.ToUpperInvariant(), k + "?" + imageindex.ToString(CultureInfo.InvariantCulture));
}
string words = keywordslist.ToString();
if(scriptconfig.CaseSensitive)
scriptedit.KeyWords(keywordsindex, words);
else
scriptedit.KeyWords(keywordsindex, words.ToLowerInvariant());
}
// Create the constants list and apply it
imageindex = (int)ImageIndex.ScriptConstant;
int constantsindex = lexercfg.ReadSetting(lexername + ".constantsindex", -1);
if(constantsindex > -1)
{
StringBuilder constantslist = new StringBuilder("");
foreach(string c in scriptconfig.Constants)
{
if(constantslist.Length > 0) constantslist.Append(" ");
constantslist.Append(c);
autocompletelist.Add(c.ToUpperInvariant(), c + "?" + imageindex.ToString(CultureInfo.InvariantCulture));
}
string words = constantslist.ToString();
if(scriptconfig.CaseSensitive)
scriptedit.KeyWords(constantsindex, words);
else
scriptedit.KeyWords(constantsindex, words.ToLowerInvariant());
}
// Sort the autocomplete list
List<string> autocompleteplainlist = new List<string>(autocompletelist.Values);
autocompletestring = string.Join(" ", autocompleteplainlist.ToArray());
// Show/hide the functions bar
functionbar.Visible = (scriptconfig.FunctionRegEx.Length > 0);
// Rearrange the layout
scriptedit.ClearDoreplacedentStyle();
scriptedit.SetText(scriptedit.GetText(scriptedit.TextSize));
this.PerformLayout();
}
19
Source : PK3StructuredReader.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private ICollection<ImageData> LoadDirectoryImages(string path, int imagetype, bool includesubdirs)
{
List<ImageData> images = new List<ImageData>();
string[] files;
string name;
int maxTextureNameLength = General.Map.Config.MaxTextureNamelength;
// Go for all files
files = GetAllFiles(path, includesubdirs);
foreach(string f in files)
{
// Make the texture name from filename without extension
name = Path.GetFileNameWithoutExtension(f).ToUpperInvariant();
if ((maxTextureNameLength > 0) && (name.Length > maxTextureNameLength)) name = name.Substring(0, maxTextureNameLength);
if (name.Length > 0)
{
// Add image to list
images.Add(CreateImage(name, f, imagetype));
}
else
{
// Can't load image without name
General.ErrorLogger.Add(ErrorType.Error, "Can't load an unnamed texture from \"" + path + "\". Please consider giving names to your resources.");
}
}
// Return result
return images;
}
19
Source : Lump.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
internal void Rename(string newname)
{
// Make name
this.fixedname = MakeFixedName(newname, WAD.ENCODING);
this.name = MakeNormalName(this.fixedname, WAD.ENCODING).ToUpperInvariant();
this.longname = MakeLongName(newname);
// Write changes
owner.WriteHeaders();
}
19
Source : WAD.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public int FindLumpIndex(string name, int start, int end)
{
byte[] fixedname;
long longname = Lump.MakeLongName(name);
// Fix end when it exceeds length
if(end > (lumps.Count - 1)) end = lumps.Count - 1;
// Make sure name is in uppercase
name = name.ToUpperInvariant();
// Make fixed name
fixedname = Lump.MakeFixedName(name, ENCODING);
// Loop through the lumps
for(int i = start; i <= end; i++)
{
/*
// Check if first byte matches
if(lumps[i].FixedName[0] == fixedname[0])
{
// Check if the lump name matches
if(lumps[i].Name.StartsWith(name, false, CultureInfo.InvariantCulture))
{
// Found the lump!
return i;
}
}
*/
// Check if the lump name matches
if(lumps[i].LongName == longname)
{
// Found the lump!
return i;
}
}
// Nothing found
return -1;
}
19
Source : BuilderPlug.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
protected void AddFolderRecursive(string in_path, ToolStripMenuItem cur_menu)
{
string[] scripts_files = Directory.GetFiles(in_path);
string[] subdirectories = Directory.GetDirectories(in_path);
List<ToolStripItem> file_items = new List<ToolStripItem>(scripts_files.Length);
foreach (string path in subdirectories)
{
string shortname = Path.GetFileName(path);
if (!shortname.StartsWith(".") && shortname.ToLowerInvariant() != "include")
{
StringBuilder ui_text = new StringBuilder("&");
ui_text.Append(shortname.Substring(0, 1).ToUpperInvariant());
ui_text.Append(shortname.Substring(1));
ToolStripMenuItem item = new ToolStripMenuItem(ui_text.ToString());
AddFolderRecursive(path, item);
file_items.Add(item);
}
}
foreach (string path in scripts_files)
{
if (Path.GetExtension(path) == ".lua")
{
StringBuilder ui_text = new StringBuilder("&");
ui_text.Append(Path.GetFileNameWithoutExtension(path).Substring(0, 1).ToUpperInvariant());
ui_text.Append(Path.GetFileNameWithoutExtension(path).Substring(1).ToLowerInvariant());
ToolStripItem item = new ToolStripMenuItem(ui_text.ToString());
item.Tag = "luaquickaccess;" + path;
item.Click += new System.EventHandler(this.InvokeTaggedAction);
file_items.Add(item);
}
}
cur_menu.DropDownItems.AddRange(file_items.ToArray());
}
19
Source : BuilderPlug.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void Load()
{
// Check if the map format has a DIALOGUE lump we can edit
bool editlump = false;
foreach(KeyValuePair<string, MapLumpInfo> lump in General.Map.Config.MapLumps)
{
if(lump.Key.Trim().ToUpperInvariant() == "DIALOGUE")
editlump = true;
}
if(editlump)
{
// Load tools (this adds our button to the toolbar)
if(toolsform == null)
toolsform = new ToolsForm();
}
}
19
Source : Functions.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
[ParserFunction]
public static string Upper(this string s)
{
return s.ToUpperInvariant();
}
19
Source : CybtansModelBinder.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private static void SetValue(ModelBindingContext bindingContext, object obj, string value, string property)
{
if (obj is IReflectorMetadataProvider reflectorMetadata)
{
var accesor = reflectorMetadata.GetAccesor();
var propCode = accesor.GetPropertyCode(Pascal(property));
var propType = accesor.GetPropertyType(propCode);
propType = Nullable.GetUnderlyingType(propType) ?? propType;
reflectorMetadata.SetValue(Pascal(property),
propType != typeof(string) ?
Convert.ChangeType(value, propType) :
value);
}
else
{
var prop = bindingContext.ModelMetadata.Properties.FirstOrDefault(x => x.Name.ToUpperInvariant() == property.ToUpperInvariant());
prop?.PropertySetter(obj,
prop.ModelType != typeof(string) ?
Convert.ChangeType(value, prop.UnderlyingOrModelType) :
value);
}
}
19
Source : CybtansModelBinder.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private static void SetValue(ModelBindingContext bindingContext, object obj, object value, string property)
{
if (obj is IReflectorMetadataProvider reflectorMetadata)
{
var accesor = reflectorMetadata.GetAccesor();
var propCode = accesor.GetPropertyCode(Pascal(property));
var propType = accesor.GetPropertyType(propCode);
propType = Nullable.GetUnderlyingType(propType) ?? propType;
reflectorMetadata.SetValue(Pascal(property), value);
}
else
{
var prop = bindingContext.ModelMetadata.Properties.FirstOrDefault(x => x.Name.ToUpperInvariant() == property.ToUpperInvariant());
prop?.PropertySetter(obj, value);
}
}
19
Source : PdbDocument.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public override int GetHashCode() {
return (Url ?? string.Empty).ToUpperInvariant().GetHashCode();
}
19
Source : UTF8String.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public UTF8String ToUpperInvariant() {
return new UTF8String(String.ToUpperInvariant());
}
19
Source : Utils.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
static string GetCanonicalLocale(string locale) {
var s = locale.ToUpperInvariant();
if (s == "NEUTRAL")
s = string.Empty;
return s;
}
19
Source : ResourceName.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public int CompareTo(ResourceName other) {
if (HasId != other.HasId) {
// Sort names before ids
return HasName ? -1 : 1;
}
if (HasId)
return id.CompareTo(other.id);
else
return name.ToUpperInvariant().CompareTo(other.name.ToUpperInvariant());
}
19
Source : TypeNameParser.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
replacedemblyRef ReadreplacedemblyRef() {
var asmRef = new replacedemblyRefUser();
if (ownerModule != null)
ownerModule.UpdateRowId(asmRef);
asmRef.Name = ReadreplacedemblyNameId();
SkipWhite();
if (PeekChar() != ',')
return asmRef;
ReadChar();
while (true) {
SkipWhite();
int c = PeekChar();
if (c == -1 || c == ']')
break;
if (c == ',') {
ReadChar();
continue;
}
string key = ReadId();
SkipWhite();
if (PeekChar() != '=')
continue;
ReadChar();
string value = ReadId();
switch (key.ToUpperInvariant()) {
case "VERSION":
asmRef.Version = Utils.ParseVersion(value);
break;
case "CONTENTTYPE":
if (value.Equals("WindowsRuntime", StringComparison.OrdinalIgnoreCase))
asmRef.ContentType = replacedemblyAttributes.ContentType_WindowsRuntime;
else
asmRef.ContentType = replacedemblyAttributes.ContentType_Default;
break;
case "RETARGETABLE":
if (value.Equals("Yes", StringComparison.OrdinalIgnoreCase))
asmRef.IsRetargetable = true;
else
asmRef.IsRetargetable = false;
break;
case "PUBLICKEY":
if (value.Equals("null", StringComparison.OrdinalIgnoreCase) ||
value.Equals("neutral", StringComparison.OrdinalIgnoreCase))
asmRef.PublicKeyOrToken = new PublicKey();
else
asmRef.PublicKeyOrToken = PublicKeyBase.CreatePublicKey(Utils.ParseBytes(value));
break;
case "PUBLICKEYTOKEN":
if (value.Equals("null", StringComparison.OrdinalIgnoreCase) ||
value.Equals("neutral", StringComparison.OrdinalIgnoreCase))
asmRef.PublicKeyOrToken = new PublicKeyToken();
else
asmRef.PublicKeyOrToken = PublicKeyBase.CreatePublicKeyToken(Utils.ParseBytes(value));
break;
case "CULTURE":
case "LANGUAGE":
if (value.Equals("neutral", StringComparison.OrdinalIgnoreCase))
asmRef.Culture = UTF8String.Empty;
else
asmRef.Culture = value;
break;
}
}
return asmRef;
}
19
Source : OptionConverter.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static long ToFileSize(string argValue, long defaultValue)
{
if (argValue == null)
{
return defaultValue;
}
string s = argValue.Trim().ToUpperInvariant();
long multiplier = 1;
int index;
if ((index = s.IndexOf("KB")) != -1)
{
multiplier = 1024;
s = s.Substring(0, index);
}
else if ((index = s.IndexOf("MB")) != -1)
{
multiplier = 1024 * 1024;
s = s.Substring(0, index);
}
else if ((index = s.IndexOf("GB")) != -1)
{
multiplier = 1024 * 1024 * 1024;
s = s.Substring(0, index);
}
if (s != null)
{
// Try again to remove whitespace between the number and the size specifier
s = s.Trim();
long longVal;
if (SystemInfo.TryParse(s, out longVal))
{
return longVal * multiplier;
}
else
{
LogLog.Error(declaringType, "OptionConverter: ["+ s +"] is not in the correct file size syntax.");
}
}
return defaultValue;
}
19
Source : ExcelVBAProject.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private string GetString(byte[] value, int max)
{
string ret = "";
for (int i = 0; i <= max; i++)
{
if (value[i] < 16)
{
ret += "0" + value[i].ToString("x");
}
else
{
ret += value[i].ToString("x");
}
}
return ret.ToUpperInvariant();
}
19
Source : CoumpundDocumentItem.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public int CompareTo(CompoundDoreplacedenreplacedem other)
{
if(Name.Length < other.Name.Length)
{
return -1;
}
else if(Name.Length > other.Name.Length)
{
return 1;
}
var n1 = Name.ToUpperInvariant();
var n2 = other.Name.ToUpperInvariant();
for (int i=0;i<n1.Length;i++)
{
if(n1[i] < n2[i])
{
return -1;
}
else if(n1[i] > n2[i])
{
return 1;
}
}
return 0;
}
19
Source : ARControlsExtensions.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public static string ApplyTransform (this string self, TextTransform transform)
{
if (string.IsNullOrEmpty(self))
return self;
switch (transform)
{
case TextTransform.Uppercase:
return self.ToUpperInvariant();
case TextTransform.Lowercase:
return self.ToLowerInvariant();
default:
return self;
}
}
19
Source : AttributedTextValueConverter.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return null;
var asConverterParameter = parameter as ATConverterParameterModel;
if (asConverterParameter != null)
{
var text = string.Format(asConverterParameter.StringFormat?.Invoke(value) ?? "{0}", value).TrimStart().TrimEnd();
if (asConverterParameter.Uppercase)
text = text.ToUpperInvariant();
var attrString = new NSMutableAttributedString(str: text,
font: asConverterParameter.Font,
foregroundColor: asConverterParameter.ForegroundColor,
strokeColor: asConverterParameter.ForegroundColor,
underlineStyle: asConverterParameter.UnderlineStyle,
strikethroughStyle: asConverterParameter.StrikethroughStyle,
kerning: asConverterParameter.Kerning);
if (asConverterParameter.IncludedCurrency)
{
attrString.AddAttribute(UIStringAttributeKey.Font, UIFont.SystemFontOfSize(asConverterParameter.Font.PointSize), new NSRange(text.IndexOf('\u20BD'), 1));
}
return attrString;
}
return null;
}
19
Source : UserDialogs.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public Task<bool> Confirm(string message, string button, bool autoHide = false)
{
var compat = TopActivity as AppCompatActivity;
if (compat == null)
return Task.FromResult(false);
var tcs = new TaskCompletionSource<bool>();
Task.Run(async () =>
{
var snackBar = await CreateSnackbar(compat, message);
if (snackBar != null)
compat.RunOnUiThread(() =>
{
if (!string.IsNullOrEmpty(button))
{
snackBar.SetAction(button.ToUpperInvariant(), x =>
{
tcs.TrySetResult(true);
snackBar.Dismiss();
});
//snackBar.SetActionTextColor(color.Value.ToNative());
}
snackBar.Show();
});
});
return tcs.Task;
}
19
Source : ARNotificationView.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
private void InitializeWithButtonreplacedle(UITextView textView, string buttonreplacedle)
{
BackgroundColor = Theme.ControlPalette.Notifications.Confirm.Background.ToUIColor();
_button = new UIButton(UIButtonType.Custom);
_button.SetupStyle(Theme.ControlPalette.Notifications.Confirm.Button);
_button.Setreplacedle(buttonreplacedle.ToUpperInvariant(), UIControlState.Normal);
_button.TouchDown += (sender, e) =>
{
_hiddenTimer?.Stop();
_hintTimer?.Stop();
};
_button.TouchCancel += (sender, e) => OnTouchCancel();
_button.SizeToFit();
var buttonWidth = Math.Max(_button.Frame.Width, 44);
_button.Frame = new CGRect(Frame.Width - buttonWidth - 16, TEXT_VIEW_OFFSET, buttonWidth, TEXT_VIEW_HEIGHT);
textView.Frame = new CGRect(16, TEXT_VIEW_OFFSET, Frame.Width - 32 - buttonWidth, TEXT_VIEW_HEIGHT);
AddSubviews(textView, _button);
}
19
Source : BasketViewController.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
protected virtual void BindNextButton(UIButton nextButton, MvxFluentBindingDescriptionSet<BasketViewController, IBasketViewModel> set)
{
set.Bind(nextButton)
.For("replacedle")
.To(vm => vm.Amount)
.WithConversion(
"StringFormat",
new StringFormatParameter { StringFormat = (arg) =>
{
var str = $"{LocalizationService.GetLocalizableString(BasketConstants.RESX_NAME, "Basket_OrderBy")} {((decimal)arg).ToString(AppSettings.CurrencyFormat, AppSettings.SettingsCulture.NumberFormat)}";
return BasketTheme.NextButton.Uppercasereplacedle ? str.ToUpperInvariant() : str;
}
});
set.Bind(nextButton).To(vm => vm.NextCommand);
set.Bind(nextButton).For(s => s.Enabled).To(vm => vm.CanGoNext);
set.Bind(nextButton).For("Visibility").To(vm => vm.Items.Count).WithConversion("Visibility");
}
19
Source : FullOrderViewController.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
protected virtual void BindNextButton(UIButton nextButton, MvxFluentBindingDescriptionSet<FullOrderViewController, IFullOrderViewModel> set)
{
set.Bind(nextButton)
.For("replacedle")
.To(vm => vm.DeliveryViewModel.Amount)
.WithConversion(
"StringFormat",
new StringFormatParameter
{
StringFormat = (arg) =>
{
var str = $"{LocalizationService.GetLocalizableString(BasketConstants.RESX_NAME, "Order_OrderBy")} {((decimal)arg).ToString(AppSettings.CurrencyFormat, AppSettings.SettingsCulture.NumberFormat)}";
return OrderTheme.NextButton.Uppercasereplacedle ? str.ToUpperInvariant() : str;
}
});
set.Bind(nextButton).To(vm => vm.NextCommand);
set.Bind(nextButton).For(s => s.Enabled).To(vm => vm.CanGoNext);
}
See More Examples