Here are the examples of the csharp api string.ToLowerInvariant() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4524 Examples
19
Source : GhostEmote.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public static MTexture GetIcon(string emote, float time) {
Atlas atlas;
if ((atlas = GetIconAtlas(ref emote)) == null)
return null;
List<string> iconPaths = new(emote.Split(' '));
if (iconPaths.Count > 1 && int.TryParse(iconPaths[0], out int fps)) {
iconPaths.RemoveAt(0);
} else {
fps = 7; // Default FPS.
}
List<MTexture> icons = iconPaths.SelectMany(iconPath => {
iconPath = iconPath.Trim();
List<MTexture> subs = atlas.orig_GetAtlreplacedubtextures(iconPath);
if (subs.Count != 0)
return subs;
if (atlas.Has(iconPath))
return new List<MTexture>() { atlas[iconPath] };
if (iconPath.ToLowerInvariant() == "end")
return new List<MTexture>() { null };
return new List<MTexture>();
}).ToList();
if (icons.Count == 0)
return null;
if (icons.Count == 1)
return icons[0];
int index = (int) Math.Floor(time * fps);
if (index >= icons.Count - 1 && icons[icons.Count - 1] == null)
return icons[icons.Count - 2];
return icons[index % icons.Count];
}
19
Source : Ribbon.cs
with GNU General Public License v3.0
from 0dteam
with GNU General Public License v3.0
from 0dteam
static string CalculateMD5(string filename)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
19
Source : CelesteNetClientRC.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
private static void HandleRequest(HttpListenerContext c) {
Logger.Log(LogLevel.VVV, "rc", $"Requested: {c.Request.RawUrl}");
string url = c.Request.RawUrl;
int indexOfSplit = url.IndexOf('?');
if (indexOfSplit != -1)
url = url.Substring(0, indexOfSplit);
RCEndPoint endpoint =
EndPoints.FirstOrDefault(ep => ep.Path == c.Request.RawUrl) ??
EndPoints.FirstOrDefault(ep => ep.Path == url) ??
EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == c.Request.RawUrl.ToLowerInvariant()) ??
EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == url.ToLowerInvariant()) ??
EndPoints.FirstOrDefault(ep => ep.Path == "/404");
endpoint.Handle(c);
}
19
Source : Frontend.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
private void HandleRequest(HttpRequestEventArgs c) {
Logger.Log(LogLevel.VVV, "frontend", $"{c.Request.RemoteEndPoint} requested: {c.Request.RawUrl}");
string url = c.Request.RawUrl;
int indexOfSplit = url.IndexOf('?');
if (indexOfSplit != -1)
url = url.Substring(0, indexOfSplit);
RCEndpoint? endpoint =
EndPoints.FirstOrDefault(ep => ep.Path == c.Request.RawUrl) ??
EndPoints.FirstOrDefault(ep => ep.Path == url) ??
EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == c.Request.RawUrl.ToLowerInvariant()) ??
EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == url.ToLowerInvariant());
if (endpoint == null) {
RespondContent(c, "frontend/" + url.Substring(1));
return;
}
c.Response.Headers.Set("Cache-Control", "no-store, max-age=0, s-maxage=0, no-cache, no-transform");
if (endpoint.Auth && !IsAuthorized(c)) {
c.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
RespondJSON(c, new {
Error = "Unauthorized."
});
return;
}
endpoint.Handle(this, c);
}
19
Source : ChatModule.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void Handle(CelesteNetConnection? con, DataChat msg) {
if (PrepareAndLog(con, msg) == null)
return;
if ((!msg.CreatedByServer || msg.Player == null) && msg.Text.StartsWith(Settings.CommandPrefix)) {
if (msg.Player != null) {
// Player should at least receive msg ack.
msg.Color = Settings.ColorCommand;
msg.Target = msg.Player;
ForceSend(msg);
}
// TODO: Improve or rewrite. This comes from GhostNet, which adopted it from disbot (0x0ade's C# Discord bot).
ChatCMDEnv env = new(this, msg);
string cmdName = env.FullText.Substring(Settings.CommandPrefix.Length);
cmdName = cmdName.Split(ChatCMD.NameDelimiters)[0].ToLowerInvariant();
if (cmdName.Length == 0)
return;
ChatCMD? cmd = Commands.Get(cmdName);
if (cmd != null) {
env.Cmd = cmd;
Task.Run(() => {
try {
cmd.ParseAndRun(env);
} catch (Exception e) {
env.Error(e);
}
});
} else {
env.Send($"Command {cmdName} not found!", color: Settings.ColorError);
}
return;
}
if (msg.Player != null && Server.PlayersByID.TryGetValue(msg.Player.ID, out CelesteNetPlayerSession? session) &&
Server.UserData.Load<UserChatSettings>(session.UID).AutoChannelChat) {
msg.Target = msg.Player;
Commands.Get<ChatCMDChannelChat>().ParseAndRun(new ChatCMDEnv(this, msg));
return;
}
Server.BroadcastAsync(msg);
}
19
Source : XnaToFnaUtil.Processor.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public void CheckAndDestroyLock(MethodDefinition method, int instri) {
Instruction instr = method.Body.Instructions[instri];
/* replaced UGLY HACK DO NOT I SAY DO NOT USE THIS EVERYWHERE
* *ahem*
* """Fix""" some games *cough* DUCK GAME *cough* looping for CONTENT to LOAD.
* I deserve to be hanged for this.
* -ade
*/
if (instri >= 1 &&
(instr.OpCode == OpCodes.Brfalse || instr.OpCode == OpCodes.Brfalse_S ||
instr.OpCode == OpCodes.Brtrue || instr.OpCode == OpCodes.Brtrue_S) &&
((Instruction) instr.Operand).Offset < instr.Offset && instr.Previous.Operand != null) {
// Check if field load / method call contains "load" or "content"
string name =
(instr.Previous.Operand as FieldReference)?.Name ??
(instr.Previous.Operand as MethodReference)?.Name ??
instr.Previous.Operand.ToString();
name = name.ToLowerInvariant();
if (instri - method.Body.Instructions.IndexOf((Instruction) instr.Operand) <= 3 &&
name != null && (name.Contains("load") || name.Contains("content"))) {
// Replace previous, possible volatile and this with nop
Log($"[PostProcess] [HACK!!!] NOPing possible content loading waiting loop in {method.GetFindableID()}");
if (instr.Previous?.Previous.OpCode == OpCodes.Volatile)
instr.Previous.Previous.OpCode = OpCodes.Nop;
instr.Previous.OpCode = OpCodes.Nop;
instr.Previous.Operand = null;
instr.OpCode = OpCodes.Nop;
instr.Operand = null;
}
}
/* OH FOR replaced SAKE THIS IS EVEN WORSE
* *ahem*
* """Fix""" some games *cough* DUCK GAME *cough* locking up the main thread with a lock while LOADing CONTENT.
* I deserve to be hanged for this, too.
* -ade
*/
if (instri >= 3 && instr.OpCode == OpCodes.Call &&
((MethodReference) instr.Operand).GetFindableID() ==
"System.Void System.Threading.Monitor::Enter(System.Object,System.Boolean&)") {
// Check for content / load in context
if (method.DeclaringType.FullName.ToLowerInvariant().Contains("content") ||
method.Name.ToLowerInvariant().Contains("load") || method.Name.ToLowerInvariant().Contains("content")) {
// "The input must be false.", MSDN says.
Log($"[PostProcess] [HACK!!!] Destroying possible content loading lock in {method.GetFindableID()}");
DestroyMonitorLock(method, instri);
} else {
// Check for the previous load field, maximally 4 (dup, st, ld in between) behind.
for (int i = instri; 0 < i && instri - 4 <= i; i--) {
string name =
(method.Body.Instructions[i].Operand as FieldReference)?.Name ??
(method.Body.Instructions[i].Operand as MethodReference)?.Name ??
method.Body.Instructions[i].Operand?.ToString();
name = name?.ToLowerInvariant();
if (name != null && (name.Contains("load") || name.Contains("content"))) {
// "The input must be false.", MSDN says.
Log($"[PostProcess] [HACK!!!] Destroying possible content loading lock in {method.GetFindableID()}");
DestroyMonitorLock(method, instri);
break;
}
}
}
}
}
19
Source : IrdTests.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
[TestCase("BLUS31604", "0A37A83C")]
[TestCase("BLUS30259", "4f5e86e7")]
public async Task DiscDecryptionKeyTest(string productCode, string expectedKey)
{
var searchResults = await Client.SearchAsync(productCode, CancellationToken.None).ConfigureAwait(false);
replacedert.That(searchResults?.Data?.Count, Is.EqualTo(1));
var ird = await Client.DownloadAsync(searchResults.Data[0], "ird", CancellationToken.None).ConfigureAwait(false);
replacedert.That(ird, Is.Not.Null);
var decryptionKey = Decrypter.DecryptDiscKey(ird.Data1).ToHexString();
replacedert.That(decryptionKey, Does.StartWith(expectedKey.ToLowerInvariant()));
}
19
Source : B2CAuthService.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
private async Task<IAccount> GetCachedAccounts()
{
var accounts = await _pca.GetAccountsAsync();
return accounts.FirstOrDefault(a =>
a.HomeAccountId?.ObjectId?.Split('.')?[0]?.EndsWith(_signUpSignInFlowName.ToLowerInvariant()) ?? false);
}
19
Source : ConfigItem.cs
with MIT License
from 3F
with MIT License
from 3F
protected virtual string Sensitivity(string name)
{
if(!SensitivityComparing) {
return name;
}
return name?.ToLowerInvariant();
}
19
Source : MicroVM.Assembler.cs
with MIT License
from a-downing
with MIT License
from a-downing
void AllocateRegisters() {
var names = Enum.GetNames(typeof(CPU.Register));
for(int i = 0; i < names.Length; i++) {
var name = names[i].ToLowerInvariant();
symbols.Add(name, new Symbol {
name = name,
var = new Variable{ val32 = new CPU.Value32{ Int = i } },
type = Symbol.Type.REGISTER
});
}
}
19
Source : DecorationMaster.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public override string GetVersion()
{
replacedembly asm = replacedembly.GetExecutingreplacedembly();
string ver = Version.ToString("0.000");
using SHA1 sha1 = SHA1.Create();
using FileStream stream = File.OpenRead(asm.Location);
byte[] hashBytes = sha1.ComputeHash(stream);
string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
return $"{ver}-{hash.Substring(0, 6)}";
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal virtual void CreateTextCommand(IDbCommand cmd, string query, string criteria = null, object parameters = null)
{
bool hasWhere = query.ToLowerInvariant().Contains("where");
if (!string.IsNullOrEmpty(criteria))
{
//add WHERE statement if not exists in query or criteria
if (!hasWhere && !criteria.ToLowerInvariant().Contains("where"))
query = query + " WHERE ";
}
query = query + " " + criteria;
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
ParameterCache.AddParameters(parameters, cmd);
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal virtual void CreateReadAllPagedNoOffsetCommand<T>(IDbCommand cmd, string query, string orderBy, int pageSize, PageNavigationEnum navigation, object[] lastOrderByColumnValues = null, object lastKeyId = null, object parameters = null)
{
string[] orderByColumns = orderBy.Split(',');
string[] orderByDirection = new string[orderByColumns.Length];
for (int i = 0; i < orderByColumns.Length; i++)
{
if (orderByColumns[i].ToLowerInvariant().Contains("desc"))
{
orderByDirection[i] = "DESC";
orderByColumns[i] = orderByColumns[i].ToLowerInvariant().Replace("desc", "").Trim();
}
else
{
orderByDirection[i] = "ASC";
orderByColumns[i] = orderByColumns[i].ToLowerInvariant().Replace("asc", "").Trim();
}
}
if (orderByColumns.Length == 0)
throw new MissingMemberException("Orderby column(s) is missing");
if ((navigation == PageNavigationEnum.Next || navigation == PageNavigationEnum.Previous) && lastOrderByColumnValues.Length != orderByColumns.Length)
throw new MissingMemberException("For Next and Previous Navigation Length of Last Values must be equal to orderby columns length");
if ((navigation == PageNavigationEnum.Next || navigation == PageNavigationEnum.Previous) && lastKeyId == null)
throw new MissingMemberException("For Next and Previous Navigation Last KeyId is required");
TableAttribute tableInfo = EnreplacedyCache.Get(typeof(T));
bool hasWhere = query.ToLowerInvariant().Contains("where");
StringBuilder pagedCriteria = new StringBuilder();
StringBuilder pagedOrderBy = new StringBuilder();
if (!hasWhere)
pagedCriteria.Append(" WHERE 1=1");
for (int i = 0; i < orderByColumns.Length; i++)
{
string applyEquals = (i <= orderByColumns.Length - 2 ? "=" : "");
if (navigation == PageNavigationEnum.Next)
{
//when multiple orderbycolumn - apply '>=' or '<=' till second last column
if (orderByDirection[i] == "ASC")
pagedCriteria.Append($" AND (({orderByColumns[i]} = @p_{orderByColumns[i]} {GetPrimaryColumnCriteriaForPagedQuery(tableInfo,">")}) OR {orderByColumns[i]} >{applyEquals} @p_{orderByColumns[i]})");
else
pagedCriteria.Append($" AND (({orderByColumns[i]} = @p_{orderByColumns[i]} {GetPrimaryColumnCriteriaForPagedQuery(tableInfo, "<")}) OR ({orderByColumns[i]} IS NULL OR {orderByColumns[i]} <{applyEquals} @p_{orderByColumns[i]}))");
}
else if (navigation == PageNavigationEnum.Previous)
{
if (orderByDirection[i] == "ASC")
pagedCriteria.Append($" AND (({orderByColumns[i]} = @p_{orderByColumns[i]} {GetPrimaryColumnCriteriaForPagedQuery(tableInfo, "<")}) OR ({orderByColumns[i]} IS NULL OR {orderByColumns[i]} <{applyEquals} @p_{orderByColumns[i]}))");
else
pagedCriteria.Append($" AND (({orderByColumns[i]} = @p_{orderByColumns[i]} {GetPrimaryColumnCriteriaForPagedQuery(tableInfo, ">")}) OR {orderByColumns[i]} >{applyEquals} @p_{orderByColumns[i]})");
}
if (navigation == PageNavigationEnum.Next || navigation == PageNavigationEnum.Previous)
{
//add Parameter for Last value of ordered column
DbType dbType;
//see if column exists in TableInfo
tableInfo.Columns.TryGetValue(orderByColumns[i], out ColumnAttribute orderByColumn);
if (orderByColumn != null)
dbType = orderByColumn.ColumnDbType;
else
TypeCache.TypeToDbType.TryGetValue(lastOrderByColumnValues[i].GetType(), out dbType);
cmd.AddInParameter("@p_" + orderByColumns[i], dbType, lastOrderByColumnValues[i]);
}
if (i > 0) pagedOrderBy.Append(",");
if (navigation == PageNavigationEnum.Last || navigation == PageNavigationEnum.Previous)
{
//reverse sort as we are going backward
pagedOrderBy.Append($"{orderByColumns[i]} {(orderByDirection[i] == "ASC" ? "DESC" : "ASC")}");
}
else
{
pagedOrderBy.Append($"{orderByColumns[i]} {orderByDirection[i]}");
}
}
//add keyfield parameter for Next and Previous navigation
if (navigation == PageNavigationEnum.Next || navigation == PageNavigationEnum.Previous)
{
//add LastKeyId Parameter
if (tableInfo.PkColumnList.Count > 1)
{
if (!(lastKeyId is T))
{
throw new InvalidOperationException("Enreplacedy has multiple primary keys. Preplaced enreplacedy setting Primary Key attributes.");
}
int index = 0;
foreach (ColumnAttribute pkCol in tableInfo.PkColumnList)
{
cmd.AddInParameter("@p_" + pkCol.Name, pkCol.ColumnDbType, tableInfo.GetKeyId(lastKeyId, pkCol));
index++;
}
}
else
{
cmd.AddInParameter("@p_" + tableInfo.PkColumn.Name, tableInfo.PkColumn.ColumnDbType, lastKeyId);
}
}
//add keyfield in orderby clause. Direction will be taken from 1st orderby column
if (navigation == PageNavigationEnum.Last || navigation == PageNavigationEnum.Previous)
{
//reverse sort as we are going backward
if (tableInfo.PkColumnList.Count > 1)
{
foreach (ColumnAttribute pkCol in tableInfo.PkColumnList)
{
pagedOrderBy.Append($",{pkCol.Name} {(orderByDirection[0] == "ASC" ? "DESC" : "ASC")}");
}
}
else
{
pagedOrderBy.Append($",{tableInfo.PkColumn.Name} {(orderByDirection[0] == "ASC" ? "DESC" : "ASC")}");
}
}
else
{
if (tableInfo.PkColumnList.Count > 1)
{
foreach (ColumnAttribute pkCol in tableInfo.PkColumnList)
{
pagedOrderBy.Append($",{pkCol.Name} {orderByDirection[0]}");
}
}
else
{
pagedOrderBy.Append($",{tableInfo.PkColumn.Name} {orderByDirection[0]}");
}
}
cmd.CommandType = CommandType.Text;
if (this is MsSqlDatabase)
cmd.CommandText = $"SELECT * FROM (SELECT TOP {pageSize} * FROM ({query} {pagedCriteria.ToString()}) AS r1 ORDER BY {pagedOrderBy}) AS r2 ORDER BY {orderBy}";
else
cmd.CommandText = $"SELECT * FROM ({query} {pagedCriteria.ToString()} ORDER BY {pagedOrderBy} LIMIT {pageSize}) AS r ORDER BY {orderBy}";
ParameterCache.AddParameters(parameters, cmd); //ParameterCache.GetFromCache(parameters, cmd).Invoke(parameters, cmd);
}
19
Source : WexApi.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
private string InternalQuery(NameValueDictionary args)
{
lock (m_nonceLock)
{
args.Add("nonce", GetNonce().ToString(CultureInfo.InvariantCulture));
var dataStr = BuildPostData(args);
var data = Encoding.ASCII.GetBytes(dataStr);
using (var httpContent = new FormUrlEncodedContent(args))
{
using (var request = new HttpRequestMessage(HttpMethod.Post, WebApi.RootUrl + "/tapi"))
{
request.Headers.Add("Key", m_key);
request.Headers.Add("Sign", ByteArrayToString(m_hashMaker.ComputeHash(data)).ToLowerInvariant());
request.Content = httpContent;
var response = WebApi.Client.SendAsync(request).Result;
var resultString = response.Content.ReadreplacedtringAsync().Result;
return resultString;
}
}
}
}
19
Source : WexPair.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
public static WexPair FromString(string pairName) {
if (pairName == null) throw new ArgumentNullException(nameof(pairName));
if (Enum.TryParse(pairName.ToLowerInvariant(), out WexPair ret))
{
return ret;
}
return WexPair.Unknown;
}
19
Source : TradeType.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
public static string ToString(TradeType tradeType) {
return Enum.GetName(typeof(TradeType), tradeType).ToLowerInvariant();
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public static Database Get(IDbConnection con)
{
string key = con.GetType().Name + "," + con.ConnectionString;
Database db;
try
{
cacheLock.EnterReadLock();
if (dbs.TryGetValue(key, out db)) return db;
}
finally
{
cacheLock.ExitReadLock();
}
if (key.ToLowerInvariant().Contains("npgsqlconnection"))
db = new PgSqlDatabase();
else if (key.ToLowerInvariant().Contains("sqliteconnection"))
db = new SQLiteDatabase();
else
db = new MsSqlDatabase();
try
{
cacheLock.EnterWriteLock();
return dbs[key] = db;
}
finally
{
cacheLock.ExitWriteLock();
}
}
19
Source : OracleDatabase.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public override DBVersionInfo FetchDBServerInfo(IDbConnection connection)
{
if (connection == null) throw new Exception("Required valid connection object to initialise database details");
string query = @"SELECT version();";
bool isConOpen = connection.State == ConnectionState.Open;
try
{
if (!isConOpen) connection.Open();
IDbCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
DBVersionInfo dbVersion = new DBVersionInfo();
using (IDataReader rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
string strVersion = rdr.GetString(0);
string[] versionParts = strVersion.Split(',');
if (versionParts.Length > 0)
{
dbVersion.ProductName = versionParts[0];
if (versionParts[versionParts.Length - 1].ToLowerInvariant().Trim().Contains("64-bit"))
dbVersion.Is64Bit = true;
}
}
rdr.Close();
}
cmd.CommandText = "SHOW server_version;";
using (IDataReader rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
dbVersion.Version = new Version(rdr.GetString(0));
}
rdr.Close();
}
return dbVersion;
}
catch
{
//ignore error
return null;
}
finally
{
if (!isConOpen && connection.State == ConnectionState.Open) connection.Close();
}
}
19
Source : ChangesetConverter.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
private static string ConvertFileExtensionToLowerCase(string fileName)
{
var slashIndex = Math.Max(fileName.LastIndexOf('/'), fileName.LastIndexOf('\\'));
var pointIndex = fileName.LastIndexOf('.');
if (pointIndex < slashIndex || pointIndex < 1 || pointIndex >= fileName.Length - 1)
return fileName;
#pragma warning disable CA1308 // Normalize strings to uppercase
return fileName.Substring(0, pointIndex + 1) + fileName.Substring(pointIndex + 1, fileName.Length - (pointIndex + 1)).ToLowerInvariant();
#pragma warning restore CA1308 // Normalize strings to uppercase
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal virtual StringBuilder CreateSelectCommand(IDbCommand cmd, string query, string criteria = null, object parameters = null)
{
bool hasWhere = query.ToLowerInvariant().Contains("where");
StringBuilder cmdText = new StringBuilder(query);
if (!string.IsNullOrEmpty(criteria))
{
//add WHERE statement if not exists in query or criteria
if (!hasWhere && !criteria.ToLowerInvariant().Contains("where"))
cmdText.Append(" WHERE ");
cmdText.Append(criteria);
}
ParameterCache.AddParameters(parameters, cmd);
return cmdText;
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal void AppendStatusCriteria(StringBuilder cmdText, RecordStatusEnum status = RecordStatusEnum.All)
{
if (status == RecordStatusEnum.All) return; //nothing to do
//add missing where clause
if (!cmdText.ToString().ToLowerInvariant().Contains("where"))
cmdText.Append(" WHERE ");
if (status == RecordStatusEnum.Active)
cmdText.Append($" {Config.ISACTIVE_COLUMN.Name}={BITTRUEVALUE}");
else if (status == RecordStatusEnum.InActive)
cmdText.Append($" {Config.ISACTIVE_COLUMN.Name}={BITFALSEVALUE}");
}
19
Source : BTCChinaAPI.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
public string getDeposits(CurrencyType currency, bool pendingonly = true)
{
const string method = "getDeposits";
string mParams = "\"" + System.Enum.GetName(typeof(CurrencyType), currency) + "\"";
if (!pendingonly)
mParams += "," + pendingonly.ToString(CultureInfo.InvariantCulture).ToLowerInvariant();
return DoMethod(BuildParams(method, mParams));
}
19
Source : BTCChinaAPI.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
public string getWithdrawals(CurrencyType currency, bool pendingonly = true)
{
const string method = "getWithdrawals";
string mParams = "\"" + System.Enum.GetName(typeof(CurrencyType), currency) + "\"";
if (!pendingonly)
mParams += "," + pendingonly.ToString(CultureInfo.InvariantCulture).ToLowerInvariant();
return DoMethod(BuildParams(method, mParams));
}
19
Source : BTCChinaAPI.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
public IEnumerable<Order> getOrders(bool openonly = true, MarketType markets = MarketType.BTCCNY, uint limit = 1000, uint offset = 0, bool withdetails = false)
{
//due to the complexity of parameters, all default values are explicitly set.
const string method = "getOrders";
string mParams = openonly.ToString(CultureInfo.InvariantCulture).ToLowerInvariant() +
",\"" + System.Enum.GetName(typeof(MarketType), markets) + "\"," +
limit.ToString(CultureInfo.InvariantCulture) + "," +
offset.ToString(CultureInfo.InvariantCulture) + "," +
withdetails.ToString(CultureInfo.InvariantCulture).ToLowerInvariant();
var response = DoMethod(BuildParams(method, mParams));
var jobj = JObject.Parse(response);
if (jobj["result"] != null)
{
var orders = jobj["result"]["order"];
foreach (var orderItem in orders)
{
var order = Order.ReadFromJObject(orderItem);
yield return order;
}
};
}
19
Source : WexPair.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
public static string ToString(WexPair v) {
return Enum.GetName(typeof(WexPair), v).ToLowerInvariant();
}
19
Source : Repository.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public static string NormalizeLogin(string login)
{
char[] invalidFileChars = Path.GetInvalidFileNameChars();
foreach (var c in invalidFileChars) if (login.Contains(c)) login = login.Replace(c, '_');
return login.ToLowerInvariant();
}
19
Source : GuidGenerator.cs
with MIT License
from abock
with MIT License
from abock
protected sealed override Guid GenerateGuid(IEnumerable<string> args)
{
var name = args.FirstOrDefault();
if (string.IsNullOrEmpty(name))
throw new Exception("Must specify NAME as the first positional argument.");
if (name == "-")
name = Console.In.ReadToEnd();
var @namespace = args.Skip(1).FirstOrDefault();
Guid namespaceGuid = default;
if (!string.IsNullOrEmpty(@namespace))
{
switch (@namespace.ToLowerInvariant())
{
case "url":
namespaceGuid = GuidNamespace.URL;
break;
case "dns":
namespaceGuid = GuidNamespace.DNS;
break;
case "oid":
namespaceGuid = GuidNamespace.OID;
break;
default:
if (!Guid.TryParse(@namespace, out namespaceGuid))
throw new Exception("Invalid namespace GUID");
break;
}
}
if (namespaceGuid == default)
namespaceGuid = GuidNamespace.URL;
return generator(namespaceGuid, name);
}
19
Source : Program.cs
with MIT License
from abock
with MIT License
from abock
static int Main(string[] args)
{
bool showVersion = false;
int numberOfIds = 1;
var firstArg = args.FirstOrDefault();
if (string.IsNullOrEmpty(firstArg) || firstArg[0] == '-' || firstArg[0] == '/')
{
switch (firstArg?.Substring(1).ToLowerInvariant())
{
case "h":
case "?":
case "help":
case "-help":
break;
default:
args = new[] { "v4" }
.Concat(args)
.ToArray();
break;
}
}
var suite = new CommandSet("idgen")
{
{ "Usage: idgen COMMAND [OPTIONS]+" },
{ "" },
{ $" idgen v{version}" },
{ $" https://github.com/abock/idgen"},
{ $" {copyright}"},
{ "" },
{ "OPTIONS:" },
{ "" },
{
"h|?|help",
"Show this help.",
v => { }
},
{
"V|version",
"Show the idgen version.",
v => showVersion = true
},
{
"n=",
"Generate {NUMBER} of identifiers", v =>
{
if (!NumberParse.TryParse (v, out numberOfIds) || numberOfIds < 0)
throw new Exception (
"NUMBER must be a positive integer, or zero, for the -number option.");
}
},
{ "" },
{ "COMMANDS:" },
{ "" }
};
var generators = new IIdGenerator[]
{
new GuidGenerator.V4 (),
new GuidGenerator.V5 (),
new GuidGenerator.V3 (),
new NanoidGenerator (),
new HashidsGenerator (),
new XcodeIdGenerator (),
new PhoneGenerator ()
};
foreach (var generator in generators)
{
var hasOptions = generator.Options?.Any(o => !string.IsNullOrEmpty(o.Prototype)) ?? false;
var usageLine = hasOptions ? "[OPTIONS]+" : null;
if (!string.IsNullOrEmpty(generator.UsageArguments))
{
if (usageLine != null)
usageLine += " ";
usageLine += generator.UsageArguments;
}
if (usageLine != null)
usageLine = " " + usageLine;
var optionSet = new OptionSet
{
{ $"Usage: {suite.Suite} {generator.Command}{usageLine}" },
};
if (hasOptions)
{
optionSet.Add("");
optionSet.Add("OPTIONS:");
optionSet.Add("");
foreach (Option option in generator.Options)
optionSet.Add(option);
}
suite.Add(new Command(generator.Command, generator.CommandDescription)
{
Options = optionSet,
Run = commandArgs => RunCommand(generator, commandArgs)
});
}
void RunCommand(IIdGenerator generator, IEnumerable<string> commandArgs)
{
if (showVersion)
{
Console.WriteLine(version);
return;
}
for (int i = 0; i < numberOfIds; i++)
{
foreach (var id in generator.Generate(commandArgs))
{
if (id != null)
Console.WriteLine(id);
}
}
}
suite.Add(
"\n" +
"NOTE: any argument that expects a number my be specified in decimal, " +
"binary (0b1001), or hex (0xabcd and ab123h) notation. Numbers may " +
"also contain digit separators (_ and ,) and arbitrary whitespace.");
try
{
suite.Run(args);
}
catch (Exception e)
{
Error(e.Message);
return 2;
}
return 0;
}
19
Source : PageRenderService.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public async Task<string> Render(Page page, Layout? layout)
{
string content = page.Content;
var features = new HashSet<string>(page.Features.Items.Select(x => x.ToLowerInvariant()));
if (features.Contains(nameof(PageFeature.Markdown).ToLowerInvariant()))
{
content = await MarkdownRenderService.RenderHtml(content);
}
if (layout is null)
{
return content;
}
else
{
var template = Template.Parse(layout.Template);
Context context = new Context
{
replacedle = page.replacedle,
Content = content
};
foreach (var item in page.Properties.Raw)
{
context.Properties.Add(item.Key, JsonConvert.DeserializeObject<dynamic>(item.Value));
}
return await template.RenderAsync(new
{
Context = context,
Props = context.Properties,
Content = context.Content
}, member => member.Name);
}
}
19
Source : PostCommand.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public override Command Configure()
{
var result = base.Configure();
result.AddOption(new Option<bool>($"--{nameof(CArgument.Remote).ToLowerInvariant()}", "Remote"));
return result;
}
19
Source : PostCommand.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public override Command Configure()
{
var result = base.Configure();
result.AddOption(new Option<string>($"--{nameof(CArgument.Id).ToLowerInvariant()}", "Id"));
result.AddOption(new Option<string>($"--{nameof(CArgument.replacedle).ToLowerInvariant()}", "replacedle"));
result.AddOption(new Option<PostType>($"--{nameof(CArgument.Type).ToLowerInvariant()}", "Type"));
return result;
}
19
Source : AddCommand.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public override Command Configure()
{
var result = base.Configure();
result.AddArgument(new Argument<string>(nameof(CArgument.Name).ToLowerInvariant(), "Remote server name"));
result.AddArgument(new Argument<string>(nameof(CArgument.Uri).ToLowerInvariant(), "Remote server URI"));
result.AddOption(new Option<RemoteType>($"--{nameof(CArgument.Type).ToLowerInvariant()}", "Type"));
result.AddOption(new Option<string>($"--{nameof(CArgument.Token).ToLowerInvariant()}", "Token"));
return result;
}
19
Source : ConfigCommand.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public override Command Configure()
{
var result = base.Configure();
result.AddArgument(new Argument<string>(nameof(CArgument.Name).ToLowerInvariant(), () => string.Empty, "Remote server name"));
result.AddArgument(new Argument<string?>(nameof(CArgument.Uri).ToLowerInvariant(), () => null, "Remote server URI"));
result.AddOption(new Option<RemoteType?>($"--{nameof(CArgument.Type).ToLowerInvariant()}", () => null, "Type"));
result.AddOption(new Option<string?>($"--{nameof(CArgument.Token).ToLowerInvariant()}", () => null, "Token"));
return result;
}
19
Source : LoginCommand.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public override Command Configure()
{
var result = base.Configure();
result.AddArgument(new Argument<string>(nameof(CArgument.Name).ToLowerInvariant(), () => string.Empty, "Remote server name"));
return result;
}
19
Source : RemoveCommand.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public override Command Configure()
{
var result = base.Configure();
result.AddArgument(new Argument<string>(nameof(CArgument.Name).ToLowerInvariant(), "Remote server name"));
return result;
}
19
Source : CompleteCommand.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public override Command Configure()
{
var result = base.Configure();
result.AddOption(new Option<bool>($"--{nameof(CArgument.Force).ToLowerInvariant()}", "Override ID, Time, Category"));
return result;
}
19
Source : PushCommand.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public override Command Configure()
{
var result = base.Configure();
result.AddOption(new Option<bool>($"--{nameof(CArgument.Full).ToLowerInvariant()}", "Delete diff data (only for API remote)"));
return result;
}
19
Source : RemoteCommand.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public override Command Configure()
{
var result = base.Configure();
result.AddCommand(new Remotes.AddCommand().Build());
result.AddCommand(new Remotes.RemoveCommand().Build());
result.AddCommand(new Remotes.ConfigCommand().Build());
result.AddCommand(new Remotes.LoginCommand().Build());
result.AddArgument(new Argument<string?>(nameof(CArgument.Current).ToLowerInvariant(), () => null, "Current remote name"));
return result;
}
19
Source : WorldDatabaseWithEntityCache.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool IsCreatureNameInWorldDatabase(string name)
{
if (creatureWeenieNamesLowerInvariantCache.TryGetValue(name.ToLowerInvariant(), out _))
return true;
using (var context = new WorldDbContext())
{
return IsCreatureNameInWorldDatabase(context, name);
}
}
19
Source : PostMetadata.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
public PostMetadata(Post data)
{
id = data.Id;
replacedle = data.replacedle;
author = data.Author;
creationTime = data.CreationTime.ToString();
modificationTime = data.ModificationTime.ToString();
category = data.Category.Items.ToArray();
keywords = data.Keywords.Items.ToArray();
type = Enum.GetName(typeof(PostType), data.Type)?.ToLowerInvariant() ?? string.Empty;
}
19
Source : CheckUtil.cs
with MIT License
from actions
with MIT License
from actions
public static async Task<CheckResult> DownloadExtraCA(this IHostContext hostContext, string url, string pat)
{
var result = new CheckResult();
try
{
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** ****");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** Download SSL Certificate from {url} ");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** ****");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
var uri = new Uri(url);
var env = new Dictionary<string, string>()
{
{ "HOSTNAME", uri.Host },
{ "PORT", uri.IsDefaultPort ? (uri.Scheme.ToLowerInvariant() == "https" ? "443" : "80") : uri.Port.ToString() },
{ "PATH", uri.AbsolutePath },
{ "PAT", pat }
};
var proxy = hostContext.WebProxy.GetProxy(uri);
if (proxy != null)
{
env["PROXYHOST"] = proxy.Host;
env["PROXYPORT"] = proxy.IsDefaultPort ? (proxy.Scheme.ToLowerInvariant() == "https" ? "443" : "80") : proxy.Port.ToString();
if (hostContext.WebProxy.HttpProxyUsername != null ||
hostContext.WebProxy.HttpsProxyUsername != null)
{
env["PROXYUSERNAME"] = hostContext.WebProxy.HttpProxyUsername ?? hostContext.WebProxy.HttpsProxyUsername;
env["PROXYPreplacedWORD"] = hostContext.WebProxy.HttpProxyPreplacedword ?? hostContext.WebProxy.HttpsProxyPreplacedword;
}
else
{
env["PROXYUSERNAME"] = "";
env["PROXYPreplacedWORD"] = "";
}
}
else
{
env["PROXYHOST"] = "";
env["PROXYPORT"] = "";
env["PROXYUSERNAME"] = "";
env["PROXYPreplacedWORD"] = "";
}
using (var processInvoker = hostContext.CreateService<IProcessInvoker>())
{
processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
{
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} [STDOUT] {args.Data}");
}
});
processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
{
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} [STDERR] {args.Data}");
}
});
var downloadCertScript = Path.Combine(hostContext.GetDirectory(WellKnownDirectory.Bin), "checkScripts", "downloadCert");
var node12 = Path.Combine(hostContext.GetDirectory(WellKnownDirectory.Externals), "node12", "bin", $"node{IOUtil.ExeExtension}");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Run '{node12} \"{downloadCertScript}\"' ");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} {StringUtil.ConvertToJson(env)}");
await processInvoker.ExecuteAsync(
hostContext.GetDirectory(WellKnownDirectory.Root),
node12,
$"\"{downloadCertScript}\"",
env,
true,
CancellationToken.None);
}
result.Preplaced = true;
}
catch (Exception ex)
{
result.Preplaced = false;
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** ****");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** Download SSL Certificate from '{url}' failed with error: {ex}");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** ****");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
}
return result;
}
19
Source : NodeJsCheck.cs
with MIT License
from actions
with MIT License
from actions
private async Task<CheckResult> CheckNodeJs(string url, string pat, bool extraCA = false)
{
var result = new CheckResult();
try
{
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** ****");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** Make Http request to {url} using node.js ");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** ****");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
// Request to github.com or ghes server
Uri requestUrl = new Uri(url);
var env = new Dictionary<string, string>()
{
{ "HOSTNAME", requestUrl.Host },
{ "PORT", requestUrl.IsDefaultPort ? (requestUrl.Scheme.ToLowerInvariant() == "https" ? "443" : "80") : requestUrl.Port.ToString() },
{ "PATH", requestUrl.AbsolutePath },
{ "PAT", pat }
};
var proxy = HostContext.WebProxy.GetProxy(requestUrl);
if (proxy != null)
{
env["PROXYHOST"] = proxy.Host;
env["PROXYPORT"] = proxy.IsDefaultPort ? (proxy.Scheme.ToLowerInvariant() == "https" ? "443" : "80") : proxy.Port.ToString();
if (HostContext.WebProxy.HttpProxyUsername != null ||
HostContext.WebProxy.HttpsProxyUsername != null)
{
env["PROXYUSERNAME"] = HostContext.WebProxy.HttpProxyUsername ?? HostContext.WebProxy.HttpsProxyUsername;
env["PROXYPreplacedWORD"] = HostContext.WebProxy.HttpProxyPreplacedword ?? HostContext.WebProxy.HttpsProxyPreplacedword;
}
else
{
env["PROXYUSERNAME"] = "";
env["PROXYPreplacedWORD"] = "";
}
}
else
{
env["PROXYHOST"] = "";
env["PROXYPORT"] = "";
env["PROXYUSERNAME"] = "";
env["PROXYPreplacedWORD"] = "";
}
if (extraCA)
{
env["NODE_EXTRA_CA_CERTS"] = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), "download_ca_cert.pem");
}
using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
{
processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
{
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} [STDOUT] {args.Data}");
}
});
processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data))
{
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} [STDERR] {args.Data}");
}
});
var makeWebRequestScript = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), "checkScripts", "makeWebRequest.js");
var node12 = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), "node12", "bin", $"node{IOUtil.ExeExtension}");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Run '{node12} \"{makeWebRequestScript}\"' ");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} {StringUtil.ConvertToJson(env)}");
await processInvoker.ExecuteAsync(
HostContext.GetDirectory(WellKnownDirectory.Root),
node12,
$"\"{makeWebRequestScript}\"",
env,
true,
CancellationToken.None);
}
result.Preplaced = true;
}
catch (Exception ex)
{
result.Preplaced = false;
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** ****");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** Make https request to {url} using node.js failed with error: {ex}");
if (result.Logs.Any(x => x.Contains("UNABLE_TO_VERIFY_LEAF_SIGNATURE") ||
x.Contains("UNABLE_TO_GET_ISSUER_CERT_LOCALLY") ||
x.Contains("SELF_SIGNED_CERT_IN_CHAIN")))
{
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** Https request failed due to SSL cert issue.");
result.SslError = true;
}
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} **** ****");
result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
}
return result;
}
19
Source : StringUtil.cs
with MIT License
from actions
with MIT License
from actions
public static bool ConvertToBoolean(string value, bool defaultValue = false)
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
switch (value.ToLowerInvariant())
{
case "1":
case "true":
case "$true":
return true;
case "0":
case "false":
case "$false":
return false;
default:
return defaultValue;
}
}
19
Source : IOUtil.cs
with MIT License
from actions
with MIT License
from actions
public static string GetSha256Hash(string path)
{
string hashString = path.ToLowerInvariant();
using (SHA256 sha256hash = SHA256.Create())
{
byte[] data = sha256hash.ComputeHash(Encoding.UTF8.GetBytes(hashString));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
string hash = sBuilder.ToString();
return hash;
}
}
19
Source : AttributesQueryContext.cs
with MIT License
from actions
with MIT License
from actions
public override int GetHashCode()
{
int hashCode = Scope.GetHashCode();
hashCode = (hashCode * 499) ^ (ContainerName != null ? ContainerName.ToLowerInvariant().GetHashCode() : 0);
hashCode = (hashCode * 499) ^ (ModifiedSince != null ? ModifiedSince.GetHashCode() : 0);
hashCode = (hashCode * 499) ^ (ModifiedAfterRevision != null ? ModifiedAfterRevision.GetHashCode() : 0);
hashCode = (hashCode * 499) ^ (CoreAttributes != null ? CoreAttributes.GetHashCode() : 0);
return hashCode;
}
19
Source : Program.cs
with MIT License
from actions
with MIT License
from actions
public static async Task<int> MainAsync(IHostContext context, string[] args)
{
Tracing trace = context.GetTrace(nameof(GitHub.Runner.Worker));
if (StringUtil.ConvertToBoolean(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_ATTACH_DEBUGGER")))
{
await WaitForDebugger(trace);
}
// We may want to consider registering this handler in Worker.cs, similiar to the unloading/SIGTERM handler
//ITerminal registers a CTRL-C handler, which keeps the Runner.Worker process running
//and lets the Runner.Listener handle gracefully the exit.
var term = context.GetService<ITerminal>();
try
{
trace.Info($"Version: {BuildConstants.RunnerPackage.Version}");
trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");
context.WritePerfCounter("WorkerProcessStarted");
// Validate args.
ArgUtil.NotNull(args, nameof(args));
ArgUtil.Equal(3, args.Length, nameof(args.Length));
ArgUtil.NotNullOrEmpty(args[0], $"{nameof(args)}[0]");
ArgUtil.Equal("spawnclient", args[0].ToLowerInvariant(), $"{nameof(args)}[0]");
ArgUtil.NotNullOrEmpty(args[1], $"{nameof(args)}[1]");
ArgUtil.NotNullOrEmpty(args[2], $"{nameof(args)}[2]");
var worker = context.GetService<IWorker>();
// Run the worker.
return await worker.RunAsync(
pipeIn: args[1],
pipeOut: args[2]);
}
catch (Exception ex)
{
// Populate any exception that cause worker failure back to runner.
Console.WriteLine(ex.ToString());
try
{
trace.Error(ex);
}
catch (Exception e)
{
// make sure we don't crash the app on trace error.
// since IOException will throw when we run out of disk space.
Console.WriteLine(e.ToString());
}
}
return 1;
}
19
Source : EditorDocumentWindow.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void replacedignLanguageAndTextForFileType(string text) {
var requiresDefaultText = (text == null);
if (!requiresDefaultText)
editor.Doreplacedent.SetText(text);
var extension = Path.GetExtension(this.Data.FileName).ToLowerInvariant();
editor.Doreplacedent.Language = this.GetOrCreateLanguage(extension);
if (requiresDefaultText)
editor.Doreplacedent.SetText(this.GetDefaultText(extension));
// Update symbol selector visibility
symbolSelectorBorder.Visibility = (editor.Doreplacedent.Language.GetNavigableSymbolProvider() != null ? Visibility.Visible : Visibility.Collapsed);
symbolSelector.AreMemberSymbolsSupported = (editor.Doreplacedent.Language.Key != "Python");
}
19
Source : MainControl.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void CreateSyntaxEditorDoreplacedent(string extension, string fileName, string text) {
if (fileName != null) {
// Load the file's text
try {
if (File.Exists(fileName))
text = File.ReadAllText(fileName);
}
catch {
text = String.Empty;
}
}
else {
// Ensure a filename has been set
fileName = String.Format("Doreplacedent{0}{1}", ++doreplacedentIndex, extension.ToLowerInvariant());
}
// Create doreplacedent data
var data = new DoreplacedentData();
data.FileName = fileName;
data.NotifyDoreplacedentOutlineUpdated = this.NotifyDoreplacedentOutlineUpdated;
data.NotifySearchAction = this.NotifyEditorViewSearch;
// Create the doreplacedent
var doreplacedentWindow = new EditorDoreplacedentWindow(data, text);
dockSite.DoreplacedentWindows.Add(doreplacedentWindow);
// Activate the doreplacedent
doreplacedentWindow.Activate();
}
19
Source : SimpleLexer.cs
with MIT License
from Actipro
with MIT License
from Actipro
protected virtual int ParseIdentifier(ITextBufferReader reader, char ch) {
// Get the entire word
int startOffset = reader.Offset - 1;
while (!reader.IsAtEnd) {
char ch2 = reader.Read();
// NOTE: This could be improved by supporting \u escape sequences
if ((!char.IsLetterOrDigit(ch2)) && (ch2 != '_')) {
reader.ReadReverse();
break;
}
}
// Determine if the word is a keyword
if (Char.IsLetter(ch)) {
int value;
String subString = reader.GetSubstring(startOffset, reader.Offset - startOffset);
if (!caseSensitive)
subString = subString.ToLowerInvariant();
return keywords.TryGetValue(subString, out value) ? value : SimpleTokenId.Identifier;
}
else
return SimpleTokenId.Identifier;
}
19
Source : TypoInViewDelegateNameAnalyzer.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private string FindNearestView(List<string> viewCandidatesNames, IMethodSymbol method)
{
string methodName = method.Name.ToLowerInvariant();
int minDistance = int.MaxValue;
string nearestViewName = null;
foreach (var viewName in viewCandidatesNames)
{
int distance = StringExtensions.LevenshteinDistance(methodName, viewName.ToLowerInvariant());
if (distance <= MaximumDistance && distance < minDistance)
{
minDistance = distance;
nearestViewName = viewName;
}
}
return nearestViewName;
}
See More Examples