Here are the examples of the csharp api char.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3273 Examples
19
Source : CacheManager.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static KeysetId Index(char indexerChr, bool validateKeys = false)
{
return new KeysetId("CKS_IND_" + indexerChr.ToString(), validateKeys);
}
19
Source : CelesteNetChatComponent.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void OnTextInput(char c) {
if (!Active)
return;
if (c == (char) 13) {
// Enter - send.
// Handled in Update.
} else if (c == (char) 8 && _CursorIndex > 0) {
// Backspace - trim.
if (Typing.Length > 0) {
int trim = 1;
// extra CursorIndex check since at index=1 using trim=1 is fine
if (_ControlHeld && _CursorIndex > 1) {
// adjust Ctrl+Backspace for having a space right before cursor
int _adjustedCursor = CursorIndex;
if (Typing[_CursorIndex - 1] == ' ')
_adjustedCursor--;
int prevWord = Typing.LastIndexOf(" ", _adjustedCursor - 1);
// if control is held and a space is found, trim from cursor back to space
if (prevWord >= 0)
trim = _adjustedCursor - prevWord;
// otherwise trim whole input back from cursor as it is one word
else
trim = _adjustedCursor;
}
// remove <trim> amount of characters before cursor
Typing = Typing.Remove(_CursorIndex - trim, trim);
_CursorIndex -= trim;
}
_RepeatIndex = 0;
_Time = 0;
} else if (c == (char) 127 && CursorIndex < Typing.Length) {
// Delete - remove character after cursor.
if (_ControlHeld && Typing[_CursorIndex] != ' ') {
int nextWord = Typing.IndexOf(" ", _CursorIndex);
// if control is held and a space is found, remove from cursor to space
if (nextWord >= 0) {
// include the found space in removal
nextWord++;
Typing = Typing.Remove(_CursorIndex, nextWord - _CursorIndex);
} else {
// otherwise remove everything after cursor
Typing = Typing.Substring(0, _CursorIndex);
}
} else {
// just remove single char
Typing = Typing.Remove(_CursorIndex, 1);
}
_RepeatIndex = 0;
_Time = 0;
} else if (!char.IsControl(c)) {
if (CursorIndex == Typing.Length) {
// Any other character - append.
Typing += c;
} else {
// insert into string if cursor is not at the end
Typing = Typing.Insert(_CursorIndex, c.ToString());
}
_CursorIndex++;
_RepeatIndex = 0;
_Time = 0;
}
}
19
Source : DialogueManagerController.cs
with MIT License
from 0xbustos
with MIT License
from 0xbustos
public bool DisplayNextSentence()
{
foreach (LetterComponent letter in this.letters)
{
GameObject.Destroy( letter.gameObject );
}
this.currentSpeed = this.Model.WaitTime;
this.currentEffect = null;
this.effects.Clear();
this.speeds.Clear();
this.letters.Clear();
this.currentX = 0;
this.currentY = 0;
if (sentences.Count == 0)
{
EndDialogue();
return false;
}
this.Model.ImageText.sprite = sprites.Dequeue();
this.sentence = sentences.Dequeue();
this.audioQueue = voices.Dequeue();
this.Model.WaitTime = 0f;
string onlyWords = string.Empty;
for (int i = 0; i < this.sentence.Length; i++)
{
if (this.sentence[i] == '[')
{
i = this.changeSpeed( i );
}
else if (this.sentence[i] == '<')
{
i = this.changeEffect( i );
}
else
{
this.effects.Add( this.currentEffect );
if (this.sentence[i] != ' ')
{
this.speeds.Add( ( float )this.currentSpeed );
}
onlyWords += this.sentence[i];
}
}
string[] words = onlyWords.Split( ' ' );
int letterSpacing = ( int )( this.fontSize * 0.5 );
int currentIndexEffects = 0;
int currentIndexSpeeds = 0;
foreach (string word in words)
{
GameObject wordObject = new GameObject( word, typeof( RectTransform ) );
wordObject.transform.SetParent( this.Model.DialogueStartPoint );
int wordSize = word.Length * letterSpacing;
if (this.currentX + wordSize > this.boxSize)
{
this.currentX = 0;
this.currentY -= ( int )( this.fontSize * 0.9 );
}
wordObject.GetComponent<RectTransform>().localPosition = new Vector3( currentX, currentY, 0 );
for (int i = 0; i < word.Length; i++)
{
GameObject letterObject = new GameObject( word[i].ToString() );
letterObject.transform.SetParent( wordObject.transform );
Text myText = letterObject.AddComponent<Text>();
myText.text = word[i].ToString();
myText.alignment = TextAnchor.LowerCenter;
myText.fontSize = this.fontSize;
myText.font = this.Model.Font;
myText.material = this.Model.Material;
myText.GetComponent<RectTransform>().localPosition = new Vector3( i * letterSpacing, 0, 0 );
myText.color = new Color( 0.0f, 0.0f, 0.0f, 0.0f );
RectTransform rt = letterObject.GetComponentInParent<RectTransform>();
rt.sizeDelta = new Vector2( this.fontSize, this.fontSize );
rt.pivot = new Vector2( 0, 1 );
LetterComponent letterComponent = letterObject.AddComponent<LetterComponent>();
Letter newLetter = new Letter
{
Character = word[i],
Speed = this.speeds[currentIndexSpeeds],
isActive = false
};
if (this.effects[currentIndexEffects] != null)
{
newLetter.Effect = this.effects[currentIndexEffects].Build( letterObject );
}
letterComponent.Model = newLetter;
this.letters.Add( letterComponent );
currentIndexEffects++;
currentIndexSpeeds++;
}
currentX += wordSize + letterSpacing;
currentIndexEffects++;
}
return true;
}
19
Source : TextSeparator.cs
with MIT License
from 0xbustos
with MIT License
from 0xbustos
void Start()
{
for (int i = 0; i < text.Length; i++){
GameObject newGO = new GameObject(text[i].ToString());
newGO.transform.SetParent(this.transform);
Text myText = newGO.AddComponent<Text>();
RectTransform parentTransform = GetComponentInParent<RectTransform>();
myText.text = text[i].ToString();
myText.alignment = TextAnchor.LowerCenter;
myText.font = font;
myText.material = material;
//myText.GetComponent<RectTransform>().localPosition = new Vector3(parentTransform.localPosition.x + (i*17) , parentTransform.localPosition.y, myText.rectTransform.localPosition.z);
myText.GetComponent<RectTransform>().localPosition = new Vector3( i * 17 , 0, 0);
myText.fontSize = 40;
myText.color = new Color(1f, 0.0f, 0.0f,1.0f);
//newGO.AddComponent<ShakeText>();
newGO.AddComponent<WaveText>();
newGO.GetComponent<WaveText>().Offset = .15f * i;
}
}
19
Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen
public void SendText(String text)
{
foreach (var t in text)
{
var symbol = t.ToString();
keydata.SendKeys(keycode[symbol].length, ref keycode[symbol].bools[0], ref keycode[symbol].ints[0]);
Thread.Sleep(10);
}
}
19
Source : ExpressionActivator.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private string ResovleOperator(string text)
{
var operators = new string[] { "!", "*", "/", "%", "+", "-", "<", ">", "<=", ">=", "==", "!=", "&&", "||" };
for (int i = 0; i < text.Length - 1; i++)
{
var opt1 = text[i].ToString();
var opt2 = text.Substring(i, 2);
if (operators.Contains(opt2))
{
return opt2;
}
else if(operators.Contains(opt1))
{
return opt1;
}
}
throw new Exception("resolve operator eroor");
}
19
Source : DefaultVerifyCodeProvider.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
private byte[] DrawVerifyCode(string code)
{
using var img = new Image<Rgba32>(4 + 16 * code.Length, 40);
var font = new Font(SystemFonts.Families.First(), 16, FontStyle.Regular);
var codeStr = code;
img.Mutate(x =>
{
x.BackgroundColor(Color.WhiteSmoke);
var r = new Random();
//画噪线
for (var i = 0; i < 4; i++)
{
int x1 = r.Next(img.Width);
int y1 = r.Next(img.Height);
int x2 = r.Next(img.Width);
int y2 = r.Next(img.Height);
x.DrawLines(new Pen(_colors.RandomGet(), 1L), new PointF(x1, y1), new PointF(x2, y2));
}
//画验证码字符串
for (int i = 0; i < codeStr.Length; i++)
{
x.DrawText(codeStr[i].ToString(), font, _colors.RandomGet(), new PointF((float)i * 16 + 4, 8));
}
});
using var stream = new MemoryStream();
img.SaveAsPng(stream);
return stream.GetBuffer();
}
19
Source : ExpressionResolver.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
private static void ResolveInForGeneric(StringBuilder sqlBuilder, string columnName, Expression exp, Type valueType, bool notContainer = false)
{
var value = ResolveDynamicInvoke(exp);
var isValueType = false;
var list = new List<string>();
if (valueType.IsEnum)
{
isValueType = true;
var valueList = (IEnumerable)value;
if (valueList != null)
{
foreach (var c in valueList)
{
list.Add(Enum.Parse(valueType, c.ToString()!).ToInt().ToString());
}
}
}
else
{
var typeName = valueType.Name;
switch (typeName)
{
case "Guid":
if (value is IEnumerable<Guid> guidValues)
{
foreach (var c in guidValues)
{
list.Add(c.ToString());
}
}
break;
case "DateTime":
if (value is IEnumerable<DateTime> dateTimeValues)
{
foreach (var c in dateTimeValues)
{
list.Add(c.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
break;
case "Byte":
isValueType = true;
if (value is IEnumerable<byte> byteValues)
{
foreach (var c in byteValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Char":
if (value is IEnumerable<char> charValues)
{
foreach (var c in charValues)
{
list.Add(c.ToString());
}
}
break;
case "Int16":
isValueType = true;
if (value is IEnumerable<short> shortValues)
{
foreach (var c in shortValues)
{
list.Add(c.ToString());
}
}
break;
case "Int32":
isValueType = true;
if (value is IEnumerable<int> intValues)
{
foreach (var c in intValues)
{
list.Add(c.ToString());
}
}
break;
case "Int64":
isValueType = true;
if (value is IEnumerable<long> longValues)
{
foreach (var c in longValues)
{
list.Add(c.ToString());
}
}
break;
case "Double":
isValueType = true;
if (value is IEnumerable<double> doubleValues)
{
foreach (var c in doubleValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Single":
isValueType = true;
if (value is IEnumerable<float> floatValues)
{
foreach (var c in floatValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Decimal":
isValueType = true;
if (value is IEnumerable<decimal> decimalValues)
{
foreach (var c in decimalValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
}
}
if (list!.Count < 1)
return;
sqlBuilder.Append(columnName);
sqlBuilder.Append(notContainer ? " NOT IN (" : " IN (");
//值类型不带引号
if (isValueType)
{
for (var i = 0; i < list.Count; i++)
{
sqlBuilder.AppendFormat("{0}", list[i]);
if (i != list.Count - 1)
{
sqlBuilder.Append(",");
}
}
}
else
{
for (var i = 0; i < list.Count; i++)
{
sqlBuilder.AppendFormat("'{0}'", list[i].Replace("'", "''"));
if (i != list.Count - 1)
{
sqlBuilder.Append(",");
}
}
}
sqlBuilder.Append(")");
}
19
Source : StringExtensions.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public static string FirstCharToLower(this string s)
{
if (string.IsNullOrEmpty(s))
return s;
string str = s.First().ToString().ToLower() + s.Substring(1);
return str;
}
19
Source : StringExtensions.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public static string FirstCharToUpper(this string s)
{
if (string.IsNullOrEmpty(s))
return s;
string str = s.First().ToString().ToUpper() + s.Substring(1);
return str;
}
19
Source : DefaultCaptchaImageGenerator.cs
with MIT License
from 1992w
with MIT License
from 1992w
private void DrawCaptchaCode(Graphics graph, int width, int height, string captchaCode)
{
SolidBrush fontBrush = new SolidBrush(Color.Black);
int fontSize = GetFontSize(width, captchaCode.Length);
Font font = new Font(FontFamily.GenericSerif, fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
for (int i = 0; i < captchaCode.Length; i++)
{
fontBrush.Color = GetRandomDeepColor();
int shiftPx = fontSize / 6;
float x = i * fontSize + rand.Next(-shiftPx, shiftPx) + rand.Next(-shiftPx, shiftPx);
int maxY = height - fontSize;
if (maxY < 0) maxY = 0;
float y = rand.Next(0, maxY);
graph.DrawString(captchaCode[i].ToString(), font, fontBrush, x, y);
}
}
19
Source : IDictionaryResolverTest_KeyType.cs
with MIT License
from 1996v
with MIT License
from 1996v
[Fact]
public void MapKeyType_ValuesOfSameWidthTypeIsSame_IsThrow()
{
{
var val = new Dictionary<object, int>()
{
{(int)8, 1},
{(uint)8, 1}
};
VerifyHelper.Throws<BssomSerializationArgumentException>(
() => BssomSerializer.Serialize(val,
BssomSerializerOptions.Default.WithIDictionaryIsSerializeMap1Type(false)),
e => e.ErrorCode == BssomSerializationArgumentException.SerializationErrorCode.BssomMapKeySame);
}
{
var val = new Dictionary<object, int>()
{
{(char)8, 1},
{(short)8, 1}
};
VerifyHelper.Throws<BssomSerializationArgumentException>(
() => BssomSerializer.Serialize(val,
BssomSerializerOptions.Default.WithIDictionaryIsSerializeMap1Type(false)),
e => e.ErrorCode == BssomSerializationArgumentException.SerializationErrorCode.BssomMapKeySame);
}
{
var val = new Dictionary<object, int>()
{
{ (char)8, 1},
{ ((char)8).ToString(), 1}
};
VerifyHelper.Throws<BssomSerializationArgumentException>(
() => BssomSerializer.Serialize(val,
BssomSerializerOptions.Default.WithIDictionaryIsSerializeMap1Type(false)),
e => e.ErrorCode == BssomSerializationArgumentException.SerializationErrorCode.BssomMapKeySame);
}
}
19
Source : GrblSettingsWindow.xaml.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
public void LineReceived(string line)
{
// Recieve GRBL Controller Version number and display - $i
// Recieved in format [VER: ... and [OPT:
if (!line.StartsWith("$") && !line.StartsWith("[VER:") && !line.StartsWith("[OPT:"))
return;
if (line.StartsWith("$"))
{
try
{
Match m = settingParser.Match(line);
int number = int.Parse(m.Groups[1].Value);
double value = double.Parse(m.Groups[2].Value, Util.Constants.DecimalParseFormat);
// Value = Setting Value, Number = Setting Code
if (!CurrentSettings.ContainsKey(number))
{
RowDefinition rowDef = new RowDefinition();
rowDef.Height = new GridLength(25);
gridMain.RowDefinitions.Add(rowDef);
TextBox valBox = new TextBox // Value of Setting Textbox
{
Text = value.ToString(Util.Constants.DecimalOutputFormat),
VerticalAlignment = VerticalAlignment.Center
};
// Define Mouseclick for textbox to open GRBLStepsCalcWindow for setting $100, $101, $102
if (number == 100) { valBox.Name = "Set100"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 101) { valBox.Name = "Set101"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 102) { valBox.Name = "Set102"; valBox.MouseDoubleClick += openStepsCalc; }
Grid.SetRow(valBox, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(valBox, 1);
gridMain.Children.Add(valBox);
TextBlock num = new TextBlock
{
Text = $"${number}=",
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(num, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(num, 0);
gridMain.Children.Add(num);
if (Util.GrblCodeTranslator.Settings.ContainsKey(number))
{
Tuple<string, string, string> labels = Util.GrblCodeTranslator.Settings[number];
TextBlock name = new TextBlock
{
Text = labels.Item1,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(name, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(name, 0);
gridMain.Children.Add(name);
TextBlock unit = new TextBlock
{
Text = labels.Item2,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(unit, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(unit, 2);
gridMain.Children.Add(unit);
valBox.ToolTip = $"{labels.Item1} ({labels.Item2}):\n{labels.Item3}";
}
CurrentSettings.Add(number, value);
SettingsBoxes.Add(number, valBox);
}
else
{
SettingsBoxes[number].Text = value.ToString(Util.Constants.DecimalOutputFormat);
CurrentSettings[number] = value;
}
}
catch { }
}
// If the line starts with [VER: then we know we are getting the version and options
else if (line.StartsWith("[VER:") || line.StartsWith("[OPT:"))
{
// Frist need to remove front [ and rear ]
string VerOptInput; // Input string
string[] VerOptTrimmed;
VerOptInput = line.Remove(0, 1); // Remove [ from the start
VerOptInput = VerOptInput.Remove(VerOptInput.Length - 1);
// Next, split the values in half at the : - we only want VER/OPT and then the values
VerOptTrimmed = VerOptInput.Split(':');
// Now we fill in the boxes depending on which one
switch (VerOptTrimmed[0])
{
case "VER":
controllerInfo += "Version: " + VerOptTrimmed[1];
break;
case "OPT":
// First we have to split commas
string[] optSplit;
optSplit = VerOptTrimmed[1].Split(','); // Splits Options into 3. 0=Options, 1=blockBufferSize, 2=rxBufferSize
var individualChar = optSplit[0].ToCharArray();// Now split optSplit[0] into each option character
controllerInfo += " | Options: " + VerOptTrimmed[1]; // Full Options Non-Decoded String
foreach (char c in individualChar)
{
// Lookup what each code is and display.... buildCodes Dictionary
if (Util.GrblCodeTranslator.BuildCodes.ContainsKey(c.ToString()))
{
// Now lets try and create and append to a string and then bind it to a ToolTip? or some other way
controllerInfo += Environment.NewLine + Util.GrblCodeTranslator.BuildCodes[c.ToString()];
}
}
controllerInfo += Environment.NewLine + "Block Buffer Size: " + optSplit[1];
controllerInfo += Environment.NewLine + "RX Buffer Size: " + optSplit[2];
GRBL_Controller_Info.Text = controllerInfo.ToString();
break;
}
}
}
19
Source : StringExtension.cs
with MIT License
from 3F
with MIT License
from 3F
public static string DirectoryPathFormat(this string path)
{
if(String.IsNullOrWhiteSpace(path)) {
return Path.DirectorySeparatorChar.ToString();
}
path = path.Trim();
if(!IsDirectoryPath(path)) {
path += Path.DirectorySeparatorChar;
}
return path;
}
19
Source : StringExtensionTest.cs
with MIT License
from 3F
with MIT License
from 3F
[Fact]
public void DirectoryPathFormatTest1()
{
string dir1 = @"D:\path\to\dir1";
replacedert.Equal($"{dir1}{Path.DirectorySeparatorChar}", dir1.DirectoryPathFormat());
string dir2 = @"D:\path\to\dir2\";
replacedert.Equal(dir2, dir2.DirectoryPathFormat());
string dir3 = null;
replacedert.Equal(Path.DirectorySeparatorChar.ToString(), dir3.DirectoryPathFormat());
replacedert.Equal(Path.DirectorySeparatorChar.ToString(), "".DirectoryPathFormat());
}
19
Source : CharObjectType.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public object Draw(Type memberType, string memberName, object value, object target)
{
string info = EditorGUILayout.TextField(memberName, ((char)value).ToString());
return info.Length > 0 ? info[0] : default;
}
19
Source : TrainRepository.cs
with MIT License
from 42skillz
with MIT License
from 42skillz
public Train GetTrain(string trainId)
{
lock (this.syncRoot)
{
if (!_trains.ContainsKey(trainId))
{
// First time, we create the train with default value
var train = new Train(trainId);
foreach (var c in "ABCDEFGHIJKL")
{
var coach = new Coach(c.ToString());
for (var i = 1; i < 42; i++)
{
var seat = new Seat(coach.Name, i.ToString(), string.Empty);
coach.Seats.Add(seat);
}
train.Add(coach);
}
_trains.Add(trainId, train);
}
}
lock (this.syncRoot)
{
return _trains[trainId];
}
}
19
Source : StringExtensions.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public static string FirstCharToUpper(this string word)
{
switch (word)
{
case null:
throw new ArgumentNullException(nameof(word));
case "":
throw new ArgumentException($"{nameof(word)} cannot be empty", nameof(word));
default:
return word.First().ToString().ToUpper() + word.Substring(1);
}
}
19
Source : Immutable.cs
with MIT License
from 71
with MIT License
from 71
public override ClreplacedDeclarationSyntax Apply(ClreplacedDeclarationSyntax node, INamedTypeSymbol symbol, CancellationToken cancellationToken)
{
var parameters = ImmutableArray.CreateBuilder<ParameterSyntax>();
var arguments = ImmutableArray.CreateBuilder<ArgumentSyntax>();
var ctorStmts = ImmutableArray.CreateBuilder<StatementSyntax>();
// Generate all parameters and statements
var members = symbol.GetMembers();
for (int i = 0; i < members.Length; i++)
{
IPropertySymbol member = members[i] as IPropertySymbol;
if (member == null || !member.IsReadOnly || !member.CanBeReferencedByName)
continue;
// Read-only prop, we good
string propName = member.Name;
string paramName = $"{char.ToLower(propName[0]).ToString()}{propName.Substring(1)}";
TypeSyntax paramType = ((PropertyDeclarationSyntax)member.DeclaringSyntaxReferences[0]
.GetSyntax(cancellationToken)).Type;
MemberAccessExpressionSyntax propAccess = F.MemberAccessExpression(
K.SimpleMemberAccessExpression,
F.ThisExpression(),
F.IdentifierName(propName)
);
// Make parameter & argument
parameters.Add(F.Parameter(F.Identifier(paramName)).WithType(paramType));
arguments.Add(F.Argument(propAccess));
// Make ctor stmt
ctorStmts.Add(F.ExpressionStatement(
F.replacedignmentExpression(K.SimplereplacedignmentExpression,
propAccess,
F.IdentifierName(paramName)
)
));
}
// The ctor is full, make all the 'with' methods
TypeSyntax returnType = F.IdentifierName(symbol.Name);
MemberDeclarationSyntax[] additionalMethods = new MemberDeclarationSyntax[parameters.Count + 1];
arguments.Capacity = arguments.Count;
ImmutableArray<ArgumentSyntax> args = arguments.MoveToImmutable();
for (int i = 0; i < parameters.Count; i++)
{
ParameterSyntax parameter = parameters[i];
string parameterName = parameter.Identifier.Text;
ArgumentSyntax name = F.Argument(F.IdentifierName(parameterName));
SeparatedSyntaxList<ArgumentSyntax> allArguments = F.SeparatedList(args.Replace(args[i], name));
StatementSyntax returnStmt = F.ReturnStatement(
F.ObjectCreationExpression(returnType).WithArgumentList(F.ArgumentList(allArguments))
);
additionalMethods[i] = F.MethodDeclaration(returnType, $"With{char.ToUpper(parameterName[0]).ToString()}{parameterName.Substring(1)}")
.AddModifiers(F.Token(K.PublicKeyword), F.Token(K.NewKeyword))
.AddParameterListParameters(parameter)
.AddBodyStatements(returnStmt);
}
// Add the private ctor
additionalMethods[parameters.Count] = F.ConstructorDeclaration(symbol.Name)
.AddModifiers(F.Token(K.PrivateKeyword))
.AddParameterListParameters(parameters.ToArray())
.AddBodyStatements(ctorStmts.ToArray());
return node.AddMembers(additionalMethods);
}
19
Source : Mana.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
private void Start()
{
string reqStr = ((ItemDef.ManaRequirement)item).Requires;
if (!string.IsNullOrEmpty(reqStr))
{
Dictionary<ManaType, int> r = new Dictionary<ManaType, int>();
try
{
for (int i = 0; i < reqStr.Length; i++)
{
char c = reqStr[i];
ManaType t = (ManaType)Enum.Parse(typeof(ManaType), c.ToString());
if (r.ContainsKey(t))
{
r[t]++;
}
else
{
r.Add(t, 1);
}
}
require = r;
}
catch (Exception e)
{
Logger.LogError("ManaRequire Parse Error");
Logger.LogError(e);
}
}
else
{
Logger.LogDebug("Not Set Requirement");
}
if (require == null)
{
require = new Dictionary<ManaType, int> { { ManaType.U, 2 }, { ManaType.G, 3 }, { ManaType.R, 1 }, { ManaType.C, 3 }, };
((ItemDef.ManaRequirement)item).Requires = "UUGGGRCCC";
}
UpdateRequire();
}
19
Source : ZUART.cs
with MIT License
from a2633063
with MIT License
from a2633063
private void txtShowData_KeyPress(object sender, KeyPressEventArgs e)
{
if (chkRecSend.Checked && ComDevice.IsOpen)
{
//if ((e.KeyChar >= ' ' && e.KeyChar <= '~') || e.KeyChar == '\r')//这是允许输入退格键允许输入0-9数字
//{
SendStr(e.KeyChar.ToString(), false);
//}
}
e.Handled = true;
}
19
Source : DocumentTextWriter.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public override void Write(char value)
{
doreplacedent.Insert(insertionOffset, value.ToString());
insertionOffset++;
}
19
Source : TextUtilities.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
static CharacterClreplaced GetCharacterClreplaced(char highSurrogate, char lowSurrogate)
{
if (char.IsSurrogatePair(highSurrogate, lowSurrogate)) {
return GetCharacterClreplaced(char.GetUnicodeCategory(highSurrogate.ToString() + lowSurrogate.ToString(), 0));
} else {
// malformed surrogate pair
return CharacterClreplaced.Other;
}
}
19
Source : V1Loader.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
static string ImportRegex(string expr, bool singleWord, bool? startOfLine)
{
StringBuilder b = new StringBuilder();
if (startOfLine != null) {
if (startOfLine.Value) {
b.Append(@"(?<=(^\s*))");
} else {
b.Append(@"(?<!(^\s*))");
}
} else {
if (singleWord)
b.Append(@"\b");
}
for (int i = 0; i < expr.Length; i++) {
char c = expr[i];
if (c == '@') {
++i;
if (i == expr.Length)
throw new HighlightingDefinitionInvalidException("Unexpected end of @ sequence, use @@ to look for a single @.");
switch (expr[i]) {
case 'C': // match whitespace or punctuation
b.Append(@"[^\w\d_]");
break;
case '!': // negative lookahead
{
StringBuilder whatmatch = new StringBuilder();
++i;
while (i < expr.Length && expr[i] != '@') {
whatmatch.Append(expr[i++]);
}
b.Append("(?!(");
b.Append(Regex.Escape(whatmatch.ToString()));
b.Append("))");
}
break;
case '-': // negative lookbehind
{
StringBuilder whatmatch = new StringBuilder();
++i;
while (i < expr.Length && expr[i] != '@') {
whatmatch.Append(expr[i++]);
}
b.Append("(?<!(");
b.Append(Regex.Escape(whatmatch.ToString()));
b.Append("))");
}
break;
case '@':
b.Append("@");
break;
default:
throw new HighlightingDefinitionInvalidException("Unknown character in @ sequence.");
}
} else {
b.Append(Regex.Escape(c.ToString()));
}
}
if (singleWord)
b.Append(@"\b");
return b.ToString();
}
19
Source : XmlFoldingStrategy.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
static string GetAttributeFoldText(XmlReader reader)
{
StringBuilder text = new StringBuilder();
for (int i = 0; i < reader.AttributeCount; ++i) {
reader.MoveToAttribute(i);
text.Append(reader.Name);
text.Append("=");
text.Append(reader.QuoteChar.ToString());
text.Append(XmlEncodeAttributeValue(reader.Value, reader.QuoteChar));
text.Append(reader.QuoteChar.ToString());
// Append a space if this is not the
// last attribute.
if (i < reader.AttributeCount - 1) {
text.Append(" ");
}
}
return text.ToString();
}
19
Source : V1Loader.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
XshdSpan ImportSpan(XmlElement element)
{
XshdSpan span = new XshdSpan();
if (element.HasAttribute("rule")) {
span.RuleSetReference = new XshdReference<XshdRuleSet>(null, element.GetAttribute("rule"));
}
char escapeCharacter = ruleSetEscapeCharacter;
if (element.HasAttribute("escapecharacter")) {
escapeCharacter = element.GetAttribute("escapecharacter")[0];
}
span.Multiline = !(element.GetBoolAttribute("stopateol") ?? false);
span.SpanColorReference = GetColorReference(element);
span.BeginRegexType = XshdRegexType.IgnorePatternWhitespace;
span.BeginRegex = ImportRegex(element["Begin"].InnerText,
element["Begin"].GetBoolAttribute("singleword") ?? false,
element["Begin"].GetBoolAttribute("startofline"));
span.BeginColorReference = GetColorReference(element["Begin"]);
string endElementText = string.Empty;
if (element["End"] != null) {
span.EndRegexType = XshdRegexType.IgnorePatternWhitespace;
endElementText = element["End"].InnerText;
span.EndRegex = ImportRegex(endElementText,
element["End"].GetBoolAttribute("singleword") ?? false,
null);
span.EndColorReference = GetColorReference(element["End"]);
}
if (escapeCharacter != '\0') {
XshdRuleSet ruleSet = new XshdRuleSet();
if (endElementText.Length == 1 && endElementText[0] == escapeCharacter) {
// ""-style escape
ruleSet.Elements.Add(new XshdSpan {
BeginRegex = Regex.Escape(endElementText + endElementText),
EndRegex = ""
});
} else {
// \"-style escape
ruleSet.Elements.Add(new XshdSpan {
BeginRegex = Regex.Escape(escapeCharacter.ToString()),
EndRegex = "."
});
}
if (span.RuleSetReference.ReferencedElement != null) {
ruleSet.Elements.Add(new XshdImport { RuleSetReference = span.RuleSetReference });
}
span.RuleSetReference = new XshdReference<XshdRuleSet>(ruleSet);
}
return span;
}
19
Source : HtmlRichTextWriter.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
void WriteChar(char c)
{
bool isWhitespace = char.IsWhiteSpace(c);
FlushSpace(isWhitespace);
switch (c) {
case ' ':
if (spaceNeedsEscaping)
htmlWriter.Write(" ");
else
hreplacedpace = true;
break;
case '\t':
for (int i = 0; i < options.TabSize; i++) {
htmlWriter.Write(" ");
}
break;
case '\r':
break; // ignore; we'll write the <br/> with the following \n
case '\n':
htmlWriter.Write("<br/>");
needIndentation = true;
break;
default:
WebUtility.HtmlEncode(c.ToString(), htmlWriter);
break;
}
// If we just handled a space by setting hreplacedpace = true,
// we mustn't set spaceNeedsEscaping as doing so would affect our own space,
// not just the following spaces.
if (c != ' ') {
// Following spaces must be escaped if c was a newline/tab;
// and they don't need escaping if c was a normal character.
spaceNeedsEscaping = isWhitespace;
}
}
19
Source : SearchStrategyFactory.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
static string ConvertWildcardsToRegex(string searchPattern)
{
if (string.IsNullOrEmpty(searchPattern))
return "";
StringBuilder builder = new StringBuilder();
foreach (char ch in searchPattern) {
switch (ch) {
case '?':
builder.Append(".");
break;
case '*':
builder.Append(".*");
break;
default:
builder.Append(Regex.Escape(ch.ToString()));
break;
}
}
return builder.ToString();
}
19
Source : StringToImageConverter.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var firstLetter = value.ToString().First().ToString();
var temp = new DrawingVisual();
var c = temp.RenderOpen();
var typeface = new Typeface(new FontFamily("Microsoft YaHei"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
c.DrawRectangle(Brushes.BlueViolet, null, new Rect(new Size(32, 32)));
c.DrawText(new FormattedText(firstLetter, culture, FlowDirection.LeftToRight, typeface, 16, Brushes.White), new Point(8, 5));
c.Close();
var image = new DrawingImage(temp.Drawing);
return image;
}
19
Source : Handler.cs
with MIT License
from actions
with MIT License
from actions
protected void AddPrependPathToEnvironment()
{
// Validate args.
Trace.Entering();
ArgUtil.NotNull(ExecutionContext.Global.PrependPath, nameof(ExecutionContext.Global.PrependPath));
if (ExecutionContext.Global.PrependPath.Count == 0)
{
return;
}
// Prepend path.
string prepend = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
var containerStepHost = StepHost as ContainerStepHost;
if (containerStepHost != null)
{
containerStepHost.PrependPath = prepend;
}
else
{
string taskEnvPATH;
Environment.TryGetValue(Constants.PathVariable, out taskEnvPATH);
string originalPath = RuntimeVariables.Get(Constants.PathVariable) ?? // Prefer a job variable.
taskEnvPATH ?? // Then a task-environment variable.
System.Environment.GetEnvironmentVariable(Constants.PathVariable) ?? // Then an environment variable.
string.Empty;
string newPath = PathUtil.PrependPath(prepend, originalPath);
AddEnvironmentVariable(Constants.PathVariable, newPath);
}
}
19
Source : ScriptHandler.cs
with MIT License
from actions
with MIT License
from actions
public override void PrintActionDetails(ActionRunStage stage)
{
if (stage == ActionRunStage.Post)
{
throw new NotSupportedException("Script action should not have 'Post' job action.");
}
Inputs.TryGetValue("script", out string contents);
contents = contents ?? string.Empty;
if (Action.Type == Pipelines.ActionSourceType.Script)
{
var firstLine = contents.TrimStart(' ', '\t', '\r', '\n');
var firstNewLine = firstLine.IndexOfAny(new[] { '\r', '\n' });
if (firstNewLine >= 0)
{
firstLine = firstLine.Substring(0, firstNewLine);
}
ExecutionContext.Output($"##[group]Run {firstLine}");
}
else
{
throw new InvalidOperationException($"Invalid action type {Action.Type} for {nameof(ScriptHandler)}");
}
var multiLines = contents.Replace("\r\n", "\n").TrimEnd('\n').Split('\n');
foreach (var line in multiLines)
{
// Bright Cyan color
ExecutionContext.Output($"\x1b[36;1m{line}\x1b[0m");
}
string argFormat;
string shellCommand;
string shellCommandPath = null;
bool validateShellOnHost = !(StepHost is ContainerStepHost);
string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
string shell = null;
if (!Inputs.TryGetValue("shell", out shell) || string.IsNullOrEmpty(shell))
{
// TODO: figure out how defaults interact with template later
// for now, we won't check job.defaults if we are inside a template.
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{
runDefaults.TryGetValue("shell", out shell);
}
}
if (string.IsNullOrEmpty(shell))
{
#if OS_WINDOWS
shellCommand = "pwsh";
if (validateShellOnHost)
{
shellCommandPath = WhichUtil.Which(shellCommand, require: false, Trace, prependPath);
if (string.IsNullOrEmpty(shellCommandPath))
{
shellCommand = "powershell";
Trace.Info($"Defaulting to {shellCommand}");
shellCommandPath = WhichUtil.Which(shellCommand, require: true, Trace, prependPath);
}
}
#else
shellCommand = "sh";
if (validateShellOnHost)
{
shellCommandPath = WhichUtil.Which("bash", false, Trace, prependPath) ?? WhichUtil.Which("sh", true, Trace, prependPath);
}
#endif
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
else
{
var parsed = ScriptHandlerHelpers.ParseShellOptionString(shell);
shellCommand = parsed.shellCommand;
if (validateShellOnHost)
{
shellCommandPath = WhichUtil.Which(parsed.shellCommand, true, Trace, prependPath);
}
argFormat = $"{parsed.shellArgs}".TrimStart();
if (string.IsNullOrEmpty(argFormat))
{
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
}
if (!string.IsNullOrEmpty(shellCommandPath))
{
ExecutionContext.Output($"shell: {shellCommandPath} {argFormat}");
}
else
{
ExecutionContext.Output($"shell: {shellCommand} {argFormat}");
}
if (this.Environment?.Count > 0)
{
ExecutionContext.Output("env:");
foreach (var env in this.Environment)
{
ExecutionContext.Output($" {env.Key}: {env.Value}");
}
}
ExecutionContext.Output("##[endgroup]");
}
19
Source : ScriptHandler.cs
with MIT License
from actions
with MIT License
from actions
public async Task RunAsync(ActionRunStage stage)
{
if (stage == ActionRunStage.Post)
{
throw new NotSupportedException("Script action should not have 'Post' job action.");
}
// Validate args
Trace.Entering();
ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
ArgUtil.NotNull(Inputs, nameof(Inputs));
var githubContext = ExecutionContext.ExpressionValues["github"] as GitHubContext;
ArgUtil.NotNull(githubContext, nameof(githubContext));
// Add Telemetry to JobContext to send with JobCompleteMessage
if (stage == ActionRunStage.Main)
{
var telemetry = new ActionsStepTelemetry
{
IsEmbedded = ExecutionContext.IsEmbedded,
Type = "run",
};
ExecutionContext.Root.ActionsStepsTelemetry.Add(telemetry);
}
var tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp);
Inputs.TryGetValue("script", out var contents);
contents = contents ?? string.Empty;
string workingDirectory = null;
if (!Inputs.TryGetValue("workingDirectory", out workingDirectory))
{
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{
if (runDefaults.TryGetValue("working-directory", out workingDirectory))
{
ExecutionContext.Debug("Overwrite 'working-directory' base on job defaults.");
}
}
}
var workspaceDir = githubContext["workspace"] as StringContextData;
workingDirectory = Path.Combine(workspaceDir, workingDirectory ?? string.Empty);
string shell = null;
if (!Inputs.TryGetValue("shell", out shell) || string.IsNullOrEmpty(shell))
{
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{
if (runDefaults.TryGetValue("shell", out shell))
{
ExecutionContext.Debug("Overwrite 'shell' base on job defaults.");
}
}
}
var isContainerStepHost = StepHost is ContainerStepHost;
string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
string commandPath, argFormat, shellCommand;
// Set up default command and arguments
if (string.IsNullOrEmpty(shell))
{
#if OS_WINDOWS
shellCommand = "pwsh";
commandPath = WhichUtil.Which(shellCommand, require: false, Trace, prependPath);
if (string.IsNullOrEmpty(commandPath))
{
shellCommand = "powershell";
Trace.Info($"Defaulting to {shellCommand}");
commandPath = WhichUtil.Which(shellCommand, require: true, Trace, prependPath);
}
ArgUtil.NotNullOrEmpty(commandPath, "Default Shell");
#else
shellCommand = "sh";
commandPath = WhichUtil.Which("bash", false, Trace, prependPath) ?? WhichUtil.Which("sh", true, Trace, prependPath);
#endif
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
else
{
var parsed = ScriptHandlerHelpers.ParseShellOptionString(shell);
shellCommand = parsed.shellCommand;
// For non-ContainerStepHost, the command must be located on the host by Which
commandPath = WhichUtil.Which(parsed.shellCommand, !isContainerStepHost, Trace, prependPath);
argFormat = $"{parsed.shellArgs}".TrimStart();
if (string.IsNullOrEmpty(argFormat))
{
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
}
// No arg format was given, shell must be a built-in
if (string.IsNullOrEmpty(argFormat) || !argFormat.Contains("{0}"))
{
throw new ArgumentException("Invalid shell option. Shell must be a valid built-in (bash, sh, cmd, powershell, pwsh) or a format string containing '{0}'");
}
// We do not not the full path until we know what shell is being used, so that we can determine the file extension
var scriptFilePath = Path.Combine(tempDirectory, $"{Guid.NewGuid()}{ScriptHandlerHelpers.GetScriptFileExtension(shellCommand)}");
var resolvedScriptPath = $"{StepHost.ResolvePathForStepHost(scriptFilePath).Replace("\"", "\\\"")}";
// Format arg string with script path
var arguments = string.Format(argFormat, resolvedScriptPath);
// Fix up and write the script
contents = ScriptHandlerHelpers.FixUpScriptContents(shellCommand, contents);
#if OS_WINDOWS
// Normalize Windows line endings
contents = contents.Replace("\r\n", "\n").Replace("\n", "\r\n");
var encoding = ExecutionContext.Global.Variables.Retain_Default_Encoding && Console.InputEncoding.CodePage != 65001
? Console.InputEncoding
: new UTF8Encoding(false);
#else
// Don't add a BOM. It causes the script to fail on some operating systems (e.g. on Ubuntu 14).
var encoding = new UTF8Encoding(false);
#endif
// Script is written to local path (ie host) but executed relative to the StepHost, which may be a container
File.WriteAllText(scriptFilePath, contents, encoding);
// Prepend PATH
AddPrependPathToEnvironment();
// expose context to environment
foreach (var context in ExecutionContext.ExpressionValues)
{
if (context.Value is IEnvironmentContextData runtimeContext && runtimeContext != null)
{
foreach (var env in runtimeContext.GetRuntimeEnvironmentVariables())
{
Environment[env.Key] = env.Value;
}
}
}
// dump out the command
var fileName = isContainerStepHost ? shellCommand : commandPath;
#if OS_OSX
if (Environment.ContainsKey("DYLD_INSERT_LIBRARIES")) // We don't check `isContainerStepHost` because we don't support container on macOS
{
// launch `node macOSRunInvoker.js shell args` instead of `shell args` to avoid macOS SIP remove `DYLD_INSERT_LIBRARIES` when launch process
string node12 = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), "node12", "bin", $"node{IOUtil.ExeExtension}");
string macOSRunInvoker = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), "macos-run-invoker.js");
arguments = $"\"{macOSRunInvoker.Replace("\"", "\\\"")}\" \"{fileName.Replace("\"", "\\\"")}\" {arguments}";
fileName = node12;
}
#endif
var systemConnection = ExecutionContext.Global.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
if (systemConnection.Data.TryGetValue("GenerateIdTokenUrl", out var generateIdTokenUrl) && !string.IsNullOrEmpty(generateIdTokenUrl))
{
Environment["ACTIONS_ID_TOKEN_REQUEST_URL"] = generateIdTokenUrl;
Environment["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken];
}
ExecutionContext.Debug($"{fileName} {arguments}");
using (var stdoutManager = new OutputManager(ExecutionContext, ActionCommandManager))
using (var stderrManager = new OutputManager(ExecutionContext, ActionCommandManager))
{
StepHost.OutputDataReceived += stdoutManager.OnDataReceived;
StepHost.ErrorDataReceived += stderrManager.OnDataReceived;
// Execute
int exitCode = await StepHost.ExecuteAsync(workingDirectory: StepHost.ResolvePathForStepHost(workingDirectory),
fileName: fileName,
arguments: arguments,
environment: Environment,
requireExitCodeZero: false,
outputEncoding: null,
killProcessOnCancel: false,
inheritConsoleHandler: !ExecutionContext.Global.Variables.Retain_Default_Encoding,
cancellationToken: ExecutionContext.CancellationToken);
// Error
if (exitCode != 0)
{
ExecutionContext.Error($"Process completed with exit code {exitCode}.");
ExecutionContext.Result = TaskResult.Failed;
}
}
}
19
Source : LexicalAnalyzer.cs
with MIT License
from actions
with MIT License
from actions
private Token CreateToken(
TokenKind kind,
Char rawValue,
Int32 index,
Object parsedValue = null)
{
return CreateToken(kind, rawValue.ToString(), index, parsedValue);
}
19
Source : PathUtility.cs
with MIT License
from actions
with MIT License
from actions
public static String Combine(String path1, String path2)
{
if (String.IsNullOrEmpty(path1))
{
return path2;
}
if (String.IsNullOrEmpty(path2))
{
return path1;
}
Char separator = path1.Contains("/") ? '/' : '\\';
Char[] trimChars = new Char[] { '\\', '/' };
return path1.TrimEnd(trimChars) + separator.ToString() + path2.TrimStart(trimChars);
}
19
Source : BankIdLoginOptionsSerializer.cs
with MIT License
from ActiveLogin
with MIT License
from ActiveLogin
public byte[] Serialize(BankIdLoginOptions model)
{
using var memory = new MemoryStream();
using var writer = new BinaryWriter(memory);
writer.Write(FormatVersion);
writer.Write(string.Join(CertificatePoliciesSeparator.ToString(), model.CertificatePolicies ?? new List<string>()));
writer.Write(model.PersonalIdenreplacedyNumber?.To12DigitString() ?? string.Empty);
writer.Write(model.AllowChangingPersonalIdenreplacedyNumber);
writer.Write(model.SameDevice);
writer.Write(model.AllowBiometric);
writer.Write(model.UseQrCode);
writer.Write(model.CancelReturnUrl ?? string.Empty);
writer.Flush();
return memory.ToArray();
}
19
Source : StringExtensions.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public static string ToPascalCase(this string s)
{
if (s.IsNullOrWhiteSpace() || char.IsUpper(s[0]))
return s;
return s.Length > 1
? char.ToUpperInvariant(s[0]).ToString() + s.Substring(1)
: char.ToUpperInvariant(s[0]).ToString();
}
19
Source : ParamsHelper.cs
with MIT License
from ad313
with MIT License
from ad313
public static string FillValue(this string source, Dictionary<string, object> paramDictionary)
{
if (string.IsNullOrWhiteSpace(source) || paramDictionary == null || paramDictionary.Count <= 0)
return source;
source = source.Replace(":", Separator.ToString());
//key中的参数
var keys = GetKeyParamters(source);
//处理参数 填充值
return FillParamValues(source, keys, paramDictionary);
}
19
Source : StringExtensions.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
public static string ToAltCase(this string value) =>
#pragma warning disable CA1308 // Normalize strings to uppercase
#if NET5_0_OR_GREATER
new(value.Select((c, i) => i % 2 == 0 ? c.ToString().ToLowerInvariant()[0] : c.ToString().ToUpperInvariant()[0]).ToArray());
#else
new string(value.Select((c, i) => i % 2 == 0 ? c.ToString().ToLowerInvariant()[0] : c.ToString().ToUpperInvariant()[0]).ToArray());
19
Source : MemoryFileProvider.cs
with MIT License
from adams85
with MIT License
from adams85
internal static string NormalizePath(string path)
{
path = Regex.Replace(path, @"/|\\", Path.DirectorySeparatorChar.ToString(), RegexOptions.CultureInvariant);
if (path.Length > 0 && path[0] == Path.DirectorySeparatorChar)
path.Substring(1);
return path;
}
19
Source : BigDecimal.cs
with MIT License
from AdamWhiteHat
with MIT License
from AdamWhiteHat
private int GetSign()
{
if (!CheckIsValidObject(this))
{
return 0;
}
Normalize();
if (Mantissa.IsZero)
{
return 0;
}
else if (Mantissa.Sign == -1)
{
if (Exponent < 0)
{
string mant = Mantissa.ToString();
int length = mant.Length + Exponent;
if (length == 0)
{
int tenthsPlace = 0;
int.TryParse(mant[0].ToString(), out tenthsPlace);
return (tenthsPlace < 5) ? 0 : 1;
}
else
{
return (length > 0) ? 1 : 0;
}
}
else
{
return -1;
}
}
else
{
return 1;
}
}
19
Source : StringFunctions.cs
with MIT License
from adamped
with MIT License
from adamped
public static string ChangeCharacter(string sourceString, int charIndex, char newChar)
{
return (charIndex > 0 ? sourceString.Substring(0, charIndex) : "")
+ newChar.ToString() + (charIndex < sourceString.Length - 1 ? sourceString.Substring(charIndex + 1) : "");
}
19
Source : SettingsTest.cs
with MIT License
from adams85
with MIT License
from adams85
[Fact]
public void ParsingOptions()
{
var configJson =
$@"{{
""{nameof(FileLoggerOptions.RootPath)}"": ""{Path.DirectorySeparatorChar.ToString().Replace(@"\", @"\\")}"",
""{nameof(FileLoggerOptions.BasePath)}"": ""Logs"",
""{nameof(FileLoggerOptions.FileAccessMode)}"": ""{LogFileAccessMode.OpenTemporarily}"",
""{nameof(FileLoggerOptions.FileEncodingName)}"": ""utf-8"",
""{nameof(FileLoggerOptions.Files)}"": [
{{
""{nameof(LogFileOptions.Path)}"": ""logger.log"",
""{nameof(LogFileOptions.MinLevel)}"": {{
""Karambolo.Extensions.Logging.File"": ""{LogLevel.Warning}"",
""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.None}"",
}},
}},
{{
""{nameof(LogFileOptions.Path)}"": ""test.log"",
""{nameof(LogFileOptions.MinLevel)}"": {{
""Karambolo.Extensions.Logging.File.Test"": ""{LogLevel.Debug}"",
""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.None}"",
}},
}}],
""{nameof(FileLoggerOptions.DateFormat)}"": ""yyyyMMdd"",
""{nameof(FileLoggerOptions.CounterFormat)}"": ""000"",
""{nameof(FileLoggerOptions.MaxFileSize)}"": 10,
""{nameof(FileLoggerOptions.TextBuilderType)}"": ""{typeof(CustomLogEntryTextBuilder).replacedemblyQualifiedName}"",
""{nameof(FileLoggerOptions.IncludeScopes)}"": true,
""{nameof(FileLoggerOptions.MaxQueueSize)}"": 100,
}}";
var fileProvider = new MemoryFileProvider();
fileProvider.CreateFile("config.json", configJson);
var cb = new ConfigurationBuilder();
cb.AddJsonFile(fileProvider, "config.json", optional: false, reloadOnChange: false);
IConfigurationRoot config = cb.Build();
var services = new ServiceCollection();
services.AddOptions();
services.Configure<FileLoggerOptions>(config);
ServiceProvider serviceProvider = services.BuildServiceProvider();
IFileLoggerSettings settings = serviceProvider.GetService<IOptions<FileLoggerOptions>>().Value;
replacedert.True(settings.FileAppender is PhysicalFileAppender);
replacedert.Equal(Path.GetPathRoot(Environment.CurrentDirectory), ((PhysicalFileAppender)settings.FileAppender).FileProvider.Root);
replacedert.Equal("Logs", settings.BasePath);
replacedert.Equal(LogFileAccessMode.OpenTemporarily, settings.FileAccessMode);
replacedert.Equal(Encoding.UTF8, settings.FileEncoding);
replacedert.Equal(2, settings.Files.Length);
ILogFileSettings fileSettings = Array.Find(settings.Files, f => f.Path == "logger.log");
replacedert.NotNull(fileSettings);
replacedert.Equal(LogLevel.None, fileSettings.GetMinLevel(typeof(string).ToString()));
replacedert.Equal(LogLevel.Warning, fileSettings.GetMinLevel(typeof(FileLogger).ToString()));
replacedert.Equal(LogLevel.Warning, fileSettings.GetMinLevel(typeof(SettingsTest).ToString()));
fileSettings = Array.Find(settings.Files, f => f.Path == "test.log");
replacedert.NotNull(fileSettings);
replacedert.Equal(LogLevel.None, fileSettings.GetMinLevel(typeof(string).ToString()));
replacedert.Equal(LogLevel.None, fileSettings.GetMinLevel(typeof(FileLogger).ToString()));
replacedert.Equal(LogLevel.Debug, fileSettings.GetMinLevel(typeof(SettingsTest).ToString()));
replacedert.Equal("yyyyMMdd", settings.DateFormat);
replacedert.Equal("000", settings.CounterFormat);
replacedert.Equal(10, settings.MaxFileSize);
replacedert.Equal(typeof(CustomLogEntryTextBuilder), settings.TextBuilder.GetType());
replacedert.True(settings.IncludeScopes);
replacedert.Equal(100, settings.MaxQueueSize);
}
19
Source : BigDecimal.cs
with MIT License
from AdamWhiteHat
with MIT License
from AdamWhiteHat
private static String ToString(BigInteger mantissa, int exponent, IFormatProvider provider)
{
if (provider == null) throw new ArgumentNullException();
if (mantissa == null || BigDecimalNumberFormatInfo == null) { return NullString; }
NumberFormatInfo formatProvider = NumberFormatInfo.GetInstance(provider);
bool negativeValue = (mantissa.Sign == -1);
bool negativeExponent = (Math.Sign(exponent) == -1);
string result = BigInteger.Abs(mantissa).ToString();
int absExp = Math.Abs(exponent);
if (negativeExponent)
{
if (absExp > result.Length)
{
int zerosToAdd = Math.Abs(absExp - result.Length);
string zeroString = string.Join(string.Empty, Enumerable.Repeat(formatProvider.NativeDigits[0], zerosToAdd));
result = zeroString + result;
result = result.Insert(0, formatProvider.NumberDecimalSeparator);
result = result.Insert(0, formatProvider.NativeDigits[0]);
}
else
{
int indexOfRadixPoint = Math.Abs(absExp - result.Length);
result = result.Insert(indexOfRadixPoint, formatProvider.NumberDecimalSeparator);
if (indexOfRadixPoint == 0)
{
result = result.Insert(0, formatProvider.NativeDigits[0]);
}
}
result = result.TrimEnd(new char[] { '0' });
if (result.Last().ToString() == formatProvider.NumberDecimalSeparator)
{
result = result.Substring(0, result.Length - 1);
}
}
else
{
string zeroString = string.Join(string.Empty, Enumerable.Repeat(formatProvider.NativeDigits[0], absExp));
result += zeroString;
}
if (negativeExponent) // Prefix "0."
{
}
if (negativeValue) // Prefix "-"
{
result = result.Insert(0, formatProvider.NegativeSign);
}
return result;
}
19
Source : Program.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
static async Task Main(string[] args)
{
Console.WriteLine("Freshy EdgeUpdate Bot!");
Console.WriteLine("Release version: " + TelegramBotSettings.BOT_VERSION);
Console.WriteLine("\nInitializing Directories...");
InitializeDirectory();
Console.WriteLine("\nInitializing Database...");
Db = new DBEngine();
Console.WriteLine("\nInitializing TDLIB engine...");
TDLibHost tdHost = new TDLibHost();
Console.WriteLine("\nTDLIB engine ready!");
Task.Factory.StartNew(o => SearchAutomation.PreExecute(), null, TaskCreationOptions.LongRunning);
string cmd = "";
do
{
cmd = Console.ReadKey().KeyChar.ToString().ToLower();
} while (cmd != "q");
}
19
Source : Program.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
static void Main(string[] args)
{
manager = new NowPlayingSessionManager();
manager.SessionListChanged += SessionListChanged;
SessionListChanged(null, null);
char letter;
do
{
var key = Console.ReadKey(true);
letter = key.KeyChar.ToString().ToLower()[0];
if (letter == 'p' || key.Key == ConsoleKey.Spacebar)
src.SendMediaPlaybackCommand(MediaPlaybackCommands.PlayPauseToggle); //MediaPlaybackCommands.Play or MediaPlaybackCommands.Pause
if (letter == 'd' || key.Key == ConsoleKey.RightArrow)
src.SendMediaPlaybackCommand(MediaPlaybackCommands.Next);
if (letter == 'a' || key.Key == ConsoleKey.LeftArrow)
src.SendMediaPlaybackCommand(MediaPlaybackCommands.Previous);
if (letter == 'r' && session != null)
src.SendMediaPlaybackCommand(MediaPlaybackCommands.Rewind);
if (letter == 'f' && session != null)
src.SendMediaPlaybackCommand(MediaPlaybackCommands.FastForward);
} while (letter != 'q');
}
19
Source : CharComponent.xaml.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public void SetValueData(byte[] dataRaw)
{
var tmp = MethodHelpers.SplitDataRaw(dataRaw);
_timestamp = GetDateTimeOffset(tmp.Key);
_char = GetChar(tmp.Value);
charBox.Text = _char.ToString();
numberBox.Text = ((ushort)_char).ToString();
}
19
Source : PortalRouteHandler.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static string FormatPath(string rawPath)
{
var forwardSlash = System.IO.Path.AltDirectorySeparatorChar.ToString();
return !string.IsNullOrWhiteSpace(rawPath) ? rawPath.StartsWith(forwardSlash) ? rawPath : forwardSlash + rawPath : forwardSlash;
}
19
Source : Expression.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static Expression RenderExpression(StringReader reader, Func<string, string, object> parseValue)
{
var operands = new List<Expression>();
var name = new StringBuilder();
string op = null;
var union = false;
var unionAnd = false;
var unionOperandCount = 0;
while (true)
{
// pop the next character
var value = reader.Read();
// reached end of string?
if (value == -1) break;
var current = Convert.ToChar(value);
if (current == '\\')
{
// may be trying to escape a special character
var next = Convert.ToChar(reader.Peek());
if (@"*()\@".Contains(next.ToString()))
{
// read the next character as a literal value
reader.Read();
name.Append(current);
name.Append(next);
}
else
{
// not a special character, continue normally
name.Append(current);
}
}
else if (current == '(')
{
// start a recursive call to handle sub-expression
Expression operand = RenderExpression(reader, parseValue);
operands.Add(operand);
union = false;
unionOperandCount++;
}
else if (current == ')')
{
// reached end of sub-expression
if (union)
{
if (operands.Count <= unionOperandCount)
{
var operand = GetExpression(op, name.ToString(), operands, parseValue);
operands.Add(operand);
}
return unionAnd ? GetExpression("&", "&", operands, parseValue) : GetExpression("|", "|", operands, parseValue);
}
return GetExpression(op, name.ToString(), operands, parseValue);
}
else if ("&|!=<>~".Contains(current.ToString()))
{
if ((op != null | operands.Count > 0) && (current.ToString() == "&" | current.ToString() == "|"))
{
if (op != null)
{
var operand = GetExpression(op, name.ToString(), operands, parseValue);
operands.Add(operand);
unionOperandCount++;
name.Clear();
}
op = current.ToString();
if (union && unionAnd && current.ToString() == "|")
{
var unionOperand = GetExpression("&", "&", operands, parseValue);
operands.Clear();
operands.Add(unionOperand);
unionOperandCount = 1;
}
if (union && !unionAnd && current.ToString() == "&")
{
var unionOperand = GetExpression("|", "|", operands, parseValue);
operands.Clear();
operands.Add(unionOperand);
unionOperandCount = 1;
}
union = true;
unionAnd = current.ToString() == "&";
}
else
{
// encountered an operator
op = current.ToString();
name.Append(current);
// check if this is a 2 character operator
if (reader.Peek() > -1)
{
var next = Convert.ToChar(reader.Peek());
if ("=".Contains(next.ToString()))
{
// read the second character
reader.Read();
op += next;
name.Append(next);
}
}
}
}
else
{
// this is a character in a literal value
name.Append(current);
}
}
if (union)
{
if (operands.Count <= unionOperandCount)
{
var operand = GetExpression(op, name.ToString(), operands, parseValue);
operands.Add(operand);
}
return unionAnd ? GetExpression("&", "&", operands, parseValue) : GetExpression("|", "|", operands, parseValue);
}
// reached end of expression
return GetExpression(op, name.ToString(), operands, parseValue);
}
19
Source : Project.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void ParsePath(string path)
{
//Unity's Application functions return the replacedets path in the Editor.
projectPath = path;
//pop off the last part of the path for the project name, keep the rest for the root path
List<string> pathArray = projectPath.Split(separator).ToList<string>();
name = pathArray.Last();
pathArray.RemoveAt(pathArray.Count() - 1);
rootPath = string.Join(separator[0].ToString(), pathArray.ToArray());
replacedetPath = projectPath + "/replacedets";
projectSettingsPath = projectPath + "/ProjectSettings";
libraryPath = projectPath + "/Library";
packagesPath = projectPath + "/Packages";
autoBuildPath = projectPath + "/AutoBuild";
localPackages = projectPath + "/LocalPackages";
}
19
Source : StringUtilities.cs
with MIT License
from AdrianWilczynski
with MIT License
from AdrianWilczynski
public static string ToCamelCase(this string text)
=> !string.IsNullOrEmpty(text) ?
Regex.Replace(text, "^[A-Z]", char.ToLowerInvariant(text[0]).ToString())
: text;
See More Examples