Here are the examples of the csharp api string.Split(string[], System.StringSplitOptions) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2330 Examples
19
View Source File : FileOrganization.cs
License : Apache License 2.0
Project Creator : 0xFireball
License : Apache License 2.0
Project Creator : 0xFireball
private static string[] GetPathSegments(string path)
{
return path.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
}
19
View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private Expression CreateExpression(ParameterExpression parameter, string expression)
{
var expressions1 = Factorization(expression);
var expressions2 = new Dictionary<string, Expression>();
foreach (var item in expressions1)
{
var subexpr = item.Value.Trim('(', ')');
var @opterator = ResovleOperator(item.Value);
var opt = GetExpressionType(@opterator);
if (opt == ExpressionType.Not)
{
Expression exp;
var text = subexpr.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
if (expressions2.ContainsKey(text))
{
exp = expressions2[text];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text))
{
var property = parameter.Type.GetProperty(text);
exp = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp = Expression.Constant(Convert.ToBoolean(text));
}
expressions2.Add(item.Key, Expression.MakeUnary(opt, exp, null));
}
else
{
var text1 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0]
.Trim();
var text2 = subexpr
.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[1]
.Trim();
string temp = null;
Expression exp1, exp2;
//永远将变量放在第一个操作数
if (parameter.Type.GetProperties().Any(a => a.Name == text2))
{
temp = text1;
text1 = text2;
text2 = temp;
}
//是否为上一次的分式
if (expressions2.ContainsKey(text1))
{
exp1 = expressions2[text1];
}
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
//是否为变量
var property = parameter.Type.GetProperty(text1);
exp1 = Expression.MakeMemberAccess(parameter, property);
}
else
{
exp1 = ResovleConstantExpression(text1);
}
//是否为上一次的分式
if (expressions2.ContainsKey(text2))
{
exp2 = expressions2[text2];
}
//如果第一个操作数是变量
else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
{
var constantType = parameter.Type.GetProperty(text1).PropertyType;
exp2 = ResovleConstantExpression(text2, constantType);
}
else
{
exp2 = ResovleConstantExpression(text1, (exp1 as ConstantExpression)?.Type);
}
expressions2.Add(item.Key, Expression.MakeBinary(opt, exp1, exp2));
}
}
return expressions2.Last().Value;
}
19
View Source File : JScriptGenerator.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string[] BinToBase64Lines(byte[] serialized_object)
{
int ofs = serialized_object.Length % 3;
if (ofs != 0)
{
int length = serialized_object.Length + (3 - ofs);
Array.Resize(ref serialized_object, length);
}
string base64 = Convert.ToBase64String(serialized_object, Base64FormattingOptions.InsertLineBreaks);
return base64.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Select(s => String.Format("\"{0}\"", s)).ToArray();
}
19
View Source File : GraphyManagerEditor.cs
License : MIT License
Project Creator : 1ZouLTReX1
License : MIT License
Project Creator : 1ZouLTReX1
private void LoadGuiStyles()
{
string path = GetMonoScriptFilePath(this);
path = path.Split(separator: new string[] { "replacedets" }, options: StringSplitOptions.None)[1]
.Split(separator: new string[] { "Tayx" }, options: StringSplitOptions.None)[0];
m_logoTexture = replacedetDatabase.LoadreplacedetAtPath<Texture2D>
(
"replacedets" +
path +
"Tayx/Graphy - Ultimate Stats Monitor/Textures/Manager_Logo_" +
(EditorGUIUtility.isProSkin ? "White.png" : "Dark.png")
);
m_skin = replacedetDatabase.LoadreplacedetAtPath<GUISkin>
(
"replacedets" +
path +
"Tayx/Graphy - Ultimate Stats Monitor/GUI/Graphy.guiskin"
);
if (m_skin != null)
{
m_headerStyle1 = m_skin.GetStyle("Header1");
m_headerStyle2 = m_skin.GetStyle("Header2");
SetGuiStyleFontColor
(
guiStyle: m_headerStyle2,
color: EditorGUIUtility.isProSkin ? Color.white : Color.black
);
}
else
{
m_headerStyle1 = EditorStyles.boldLabel;
m_headerStyle2 = EditorStyles.boldLabel;
}
}
19
View Source File : MessageUtils.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static List<Message> FormatMessage(List<Message> msgList, string message)
{
if (msgList == null)
{
msgList = new List<Message>();
}
Message msg = null;
if (message.IndexOf(T0m) == -1 && message.IndexOf(Tm) == -1 && message.IndexOf(TK) == -1)
{
msg = new Message();
msg.Text = message;
msgList.Add(msg);
}
else
{
message = message.Replace(TK, "");
message = message.Replace(Tm, T0m);
string[] arrs = message.Split(new string[] { T0m }, StringSplitOptions.None);
string str = null;
int index = -1;
foreach (string line in arrs)
{
str = line.Replace("\r\n", "\n");
if ((index = str.IndexOf(T0131)) != -1)
{
SplitMsg(msgList, str, index, T0131, Color.IndianRed, Color.Empty);
}
else if ((index = str.IndexOf(T0132)) != -1)
{
SplitMsg(msgList, str, index, T0132, Color.LawnGreen, Color.Empty);
}
else if ((index = str.IndexOf(T0134)) != -1)
{
SplitMsg(msgList, str, index, T0134, Color.RoyalBlue, Color.Empty);
}
else if ((index = str.IndexOf(T0136)) != -1)
{
SplitMsg(msgList, str, index, T0136, Color.PowderBlue, Color.Empty);
}
else if ((index = str.IndexOf(T3042)) != -1)
{
SplitMsg(msgList, str, index, T3042, Color.CadetBlue, Color.Green);
}
else
{
msg = new Message();
msg.Text = str;
msgList.Add(msg);
}
}
}
return msgList;
}
19
View Source File : ClusterAdapter.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static ClusterMoved ParseSimpleError(string simpleError)
{
if (string.IsNullOrWhiteSpace(simpleError)) return null;
var ret = new ClusterMoved
{
ismoved = simpleError.StartsWith("MOVED "), //永久定向
isask = simpleError.StartsWith("ASK ") //临时性一次定向
};
if (ret.ismoved == false && ret.isask == false) return null;
var parts = simpleError.Split(new string[] { "\r\n" }, StringSplitOptions.None).FirstOrDefault().Split(new[] { ' ' }, 3);
if (parts.Length != 3 ||
ushort.TryParse(parts[1], out ret.slot) == false) return null;
ret.endpoint = parts[2];
return ret;
}
19
View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static List<string> String2List(string str)
{
try
{
str = str.Replace(Environment.NewLine, "");
return new List<string>(str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
}
catch (Exception ex)
{
SaveLog(ex.Message, ex);
return new List<string>();
}
}
19
View Source File : ExtendableEnums.cs
License : MIT License
Project Creator : 7ark
License : MIT License
Project Creator : 7ark
static void AddNewEnum(string clreplacedFile, string path, string enumName, string newEnum)
{
string[] originalSplit = clreplacedFile.Split(new[] { "enum " + enumName }, System.StringSplitOptions.RemoveEmptyEntries);
string newHalf = originalSplit[1];
string enumSection = newHalf.Split('}')[0];
string[] commas = enumSection.Split(',');
if (commas.Length == 0 && enumSection.Split('{')[0].Trim().Length == 0) //They've left the enum empty... for some reason.
{
Debug.Log("Uhh idk yet");
newHalf = newHalf.Replace(enumSection, enumSection + newEnum);
}
else
{
bool commaAfter = commas[commas.Length - 1].Trim().Length == 0; //This should check if they added a comma after their last enum value.
if (commaAfter)
{
newHalf = newHalf.Replace(enumSection, enumSection + newEnum + ", ");
}
else
{
while (enumSection.Length > 0 && enumSection[enumSection.Length - 1] == ' ')
enumSection = enumSection.Substring(0, enumSection.Length - 1);
newHalf = newHalf.Replace(enumSection, enumSection + ", " + newEnum);
}
}
string result = clreplacedFile.Replace(originalSplit[1], newHalf);
using (var file = File.Open(path, FileMode.Create))
{
using (var writer = new StreamWriter(file))
{
writer.Write(result);
}
}
replacedetDatabase.Refresh();
}
19
View Source File : MicroVM.Assembler.cs
License : MIT License
Project Creator : a-downing
License : MIT License
Project Creator : a-downing
bool Preprocess(string code) {
var lines = code.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.None);
for(int i = 0; i < lines.Length; i++) {
lines[i] = code = Regex.Replace(lines[i].Trim() ,@"\s+"," ");
if(lines[i].Length > 0) {
if(lines[i][0] == '#') {
continue;
}
var args = lines[i].Split(' ');
if(args.Length > 0) {
statements.Add(new Statement {
lineNum = i,
line = args,
tokens = new Token[args.Length]
});
}
}
}
return true;
}
19
View Source File : AssetBundleIndex.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
static string GetTypeWithoutreplacedembly(string fullType)
{
var typeParts = fullType.Split(new string[1] { "." }, System.StringSplitOptions.None);
string typeWithoutreplacedembly = typeParts[typeParts.Length - 1];
return typeWithoutreplacedembly;
}
19
View Source File : pRaceData.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public Sprite GetThumbFor(string thumbToGet = "")
{
Sprite foundSprite = fullThumb != null ? fullThumb : null;
foreach(WardrobeSlotThumb wardrobeThumb in wardrobeSlotThumbs)
{
string[] thumbIsForArray = null;
wardrobeThumb.thumbIsFor.Replace(" ,", ",").Replace(", ", ",");
if (wardrobeThumb.thumbIsFor.IndexOf(",") == -1)
{
thumbIsForArray = new string[1] { wardrobeThumb.thumbIsFor };
}
else
{
thumbIsForArray = wardrobeThumb.thumbIsFor.Split(new string[1] { "," }, StringSplitOptions.RemoveEmptyEntries);
}
foreach(string thumbFor in thumbIsForArray)
{
if (thumbFor == thumbToGet)
{
foundSprite = wardrobeThumb.thumb;
break;
}
}
}
return foundSprite;
}
19
View Source File : Repository.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string CheckIsIntruder(ServiceContext context, string key, string login)
{
if (key == null
|| !key.Contains("@@@"))
{
context.PossiblyIntruder = true;
Loger.Log($"Is possibly intruder or not update {login} (empty key)");
return key;
}
else
{
context.IntruderKeys = "";
var keys = key.Split(new string[] { "@@@" }, StringSplitOptions.None);
for (int i = 1; i < keys.Length; i++)
{
if (string.IsNullOrEmpty(keys[i])) continue;
context.IntruderKeys += "@@@" + keys[i];
if (Repository.CheckIsIntruder(keys[i]))
{
Loger.Log($"Is intruder {login} key={keys[i]}");
context.Disconnect("intruder");
break;
}
}
Loger.Log($"Checked {login} key={key.Substring(key.IndexOf("@@@") + 3)}");
return keys[0];
}
}
19
View Source File : OVRADBTool.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public List<string> GetDevices()
{
string outputString;
string errorString;
RunCommand(new string[] { "devices" }, null, out outputString, out errorString);
string[] devices = outputString.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
List<string> deviceList = new List<string>(devices);
deviceList.RemoveAt(0);
for(int i = 0; i < deviceList.Count; i++)
{
string deviceName = deviceList[i];
int index = deviceName.IndexOf('\t');
if (index >= 0)
deviceList[i] = deviceName.Substring(0, index);
else
deviceList[i] = "";
}
return deviceList;
}
19
View Source File : ExampleSourceCodeFormattingConverter.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (MainWindowViewModel.SearchText.IsNullOrEmpty())
{
return string.Empty;
}
var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();
var codeFiles = (Dictionary<string, string>) value;
var uiCodeFiles = codeFiles.Where(x => x.Key.EndsWith(".xaml"));
var lines = new List<string>();
foreach (var file in uiCodeFiles)
{
lines.AddRange(file.Value.Split(new[] {"\r\n"}, StringSplitOptions.None));
}
var toHighlight = new HashSet<string>();
foreach (var term in terms)
{
var containsTerm = lines.Where(x => x != "" && x.ToLower().Contains(term));
containsTerm.Take(2).Select(x => x.Trim()).ForEachDo(x => toHighlight.Add(x));
}
string result;
if (toHighlight.Any())
{
lines = toHighlight.Take(2).Select(x => x.Trim().Replace('<', ' ').Replace('>', ' ') + '.').ToList();
result = HighlightText(lines, terms);
}
else
{
var sentences = lines.Take(2).Select(x => string.Format("... {0} ...", x.Trim().Replace('<', ' ').Replace('>', ' ').ToList()));
result = string.Join("\n", sentences);
}
return result;
}
19
View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static float[] ReadFloats(StreamReader file, string separator, float noDataValue)
{
string line = file.ReadLine();
float[] values = line.Split(new[] {separator}, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
float rawValue = float.Parse(x, NumberFormatInfo.InvariantInfo);
return rawValue.CompareTo(noDataValue) == 0 ? float.NaN : rawValue;
} ).ToArray();
return values;
}
19
View Source File : ExampleDescriptionFormattingConverter.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (MainWindowViewModel.SearchText.IsNullOrEmpty())
{
return string.Empty;
}
var description = (string)value;
var result = string.Empty;
var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();
var lines = description.Split(new[] { ". " }, StringSplitOptions.None).ToArray();
var sentences = new HashSet<string>();
foreach (var term in terms)
{
var containsTerm = lines.Where(x => x != "" && x.ToLower().Contains(term));
containsTerm.Take(2).ForEachDo(x => sentences.Add(x));
}
if (sentences.Any())
{
result = HighlightText(sentences.Select(x => x.Trim()).ToArray(), terms);
}
else
{
foreach (string sentence in lines.Take(2).Select(x => x.Trim()))
{
result = result + (sentence + ". ");
}
}
return result;
}
19
View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static float[] ReadFloats(StreamReader file, string separator, float noDataValue)
{
string line = file.ReadLine();
float[] values = line.Split(new[] {separator}, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
float rawValue = float.Parse(x, CultureInfo.InvariantCulture);
return rawValue.CompareTo(noDataValue) == 0 ? float.NaN : rawValue;
} ).ToArray();
return values;
}
19
View Source File : ParticleExplorer.xaml.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator
License : GNU General Public License v3.0
Project Creator : ACEmulator
private void Setups_OnClick(object sender, MouseButtonEventArgs e)
{
var selectedItem = ItemsControl.ContainerFromElement(sender as ListBox, e.OriginalSource as DependencyObject) as ListBoxItem;
if (selectedItem == null)
return;
var kvp = (string)selectedItem.Content;
var elements = kvp.Split(new string[] { " => " }, StringSplitOptions.None);
var setupID = Convert.ToUInt32(elements[0], 16);
var scriptID = Convert.ToUInt32(elements[1], 16);
ParticleViewer.Instance.InitEmitter(scriptID, 1.0f);
MainWindow.Status.WriteLine($"Playing particle effect {scriptID:X8}");
}
19
View Source File : Hatch.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public void Rotate(double angle)
{
string[] lines = definition.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
TryreplacedignFillGridsFromStrings(lines, 1, angle);
UpdatePatternDefinition();
}
19
View Source File : SpellCheckerOptionsViewModel.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public void Apply()
{
var collecton = new StringCollection();
string[] lines = ElementsToIgnore.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
foreach (var line in lines) {
if (!string.IsNullOrEmpty(line)) {
collecton.Add(line);
}
}
SpellCheckerSettings.Default.ElementIgnoreList = collecton;
SpellCheckerSettings.Default.Save();
}
19
View Source File : SheetFilter.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public Predicate<object> GetFilter()
{
string properyName = FilterPropertyName;
switch (FilterPropertyName)
{
case "Export Name":
var m = FirstDigitOfLastNumberInString(FilterValue);
if (m == null)
{
return null;
}
return item => m == FirstDigitOfLastNumberInString((item as ExportSheet).FullExportName);
case "Number":
var n = FirstDigitOfLastNumberInString(FilterValue);
if (n == null)
{
return null;
}
return item => n == FirstDigitOfLastNumberInString((item as ExportSheet).SheetNumber);
case "Name":
properyName = "SheetDescription";
var noNumbers = Regex.Replace(FilterValue, "[0-9-]", @" ");
string[] parts = noNumbers.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
return item => parts.Any(item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Contains);
case "Revision":
properyName = "SheetRevision";
break;
case "Revision Description":
properyName = "SheetRevisionDescription";
break;
case "Revision Date":
properyName = "SheetRevisionDate";
break;
case "Scale":
properyName = "Scale";
break;
case "North Point":
properyName = "NorthPointVisibilityString";
break;
default:
return null;
}
return item => item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Equals(FilterValue, StringComparison.InvariantCulture);
}
19
View Source File : SheetFilter.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
private static string FirstDigitOfLastNumberInString(string s)
{
var onlyNumbers = Regex.Replace(s, "[^0-9]", @" ");
string[] numberParts = onlyNumbers.Split(new[] { @" " }, StringSplitOptions.RemoveEmptyEntries);
var n = numberParts.Where(v => v.Length > 1);
if (n.Count() > 0) {
return n.Last().Substring(0, 1);
}
return null;
}
19
View Source File : Hatch.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public void Scale(double scale)
{
string[] lines = definition.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
TryreplacedignFillGridsFromStrings(lines, scale, 0);
UpdatePatternDefinition();
}
19
View Source File : TabularModelSerializer.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
private static JToken ConvertExpression(string expression)
{
var lines = (expression ?? "").Split(new[] { Environment.NewLine}, StringSplitOptions.None);
if (lines.Length == 1)
return new JValue(lines[0]);
return new JArray(lines);
}
19
View Source File : PatchOperation.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static IEnumerable<string> SplitPath(string path)
{
return path.Split(new[] { PathSeparator }, StringSplitOptions.None);
}
19
View Source File : CustomShellService.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
private IList<string> SplitCloudStorageParsingName(string parsingName) {
if (!IsCloudStorageParsingName(parsingName))
return new List<string>(0);
return new List<string>(parsingName.Split(new string[] { CloudStorageParsingNameSeparator }, StringSplitOptions.RemoveEmptyEntries));
}
19
View Source File : BqlFormatterTests.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private string Normalize(string text)
{
return String.Join(EndOfLine,
text
.Split(new[] { EndOfLine }, StringSplitOptions.None)
.Select(line => line.TrimEnd()));
}
19
View Source File : SfeelParser.cs
License : MIT License
Project Creator : adamecr
License : MIT License
Project Creator : adamecr
public static string ParseInput(string expr, string leftSide)
{
if (string.IsNullOrWhiteSpace(expr)) throw Logger.Error<DmnParserException>($"Missing expression");
if (string.IsNullOrWhiteSpace(leftSide)) throw Logger.Error<DmnParserException>($"Missing left side of expression");
if (Logger.IsTraceEnabled)
Logger.Trace($"Parsing input expression {expr} for left side {leftSide}...");
expr = expr.Trim();
//custom functions translations
foreach (var translation in CustomFunctionTranslations)
{
expr = expr.Replace(translation.Key, translation.Value);
}
//check not(expr)
var isNegated = false;
if (expr.StartsWith("not(") && expr.EndsWith(")"))
{
expr = expr.Substring(4, expr.Length - 5);
isNegated = true;
}
//split to parts
var exprParts = Regex.Split(expr, @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))");
var conditionParts = new List<string>();
foreach (var exprPart in exprParts)
{
var part = exprPart.Trim();
//<,<=,>=,>
if (part.StartsWith("<") || part.StartsWith(">"))
{
conditionParts.Add($"{leftSide}{part}");
continue;
}
//[xx..yy] (] )[
if ((part.StartsWith("[") || part.StartsWith("]") || part.StartsWith("(")) &&
(part.EndsWith("]") || part.EndsWith("[") || part.EndsWith(")")))
{
var partInner = part.Substring(1, part.Length - 2);
var partInnerSplit = partInner.Split(new[] { ".." }, StringSplitOptions.None);
// ReSharper disable once InvertIf
if (partInnerSplit.Length == 2)
{
var compLeft = part.StartsWith("[") ? ">=" : ">";
var compRight = part.EndsWith("]") ? "<=" : "<";
conditionParts.Add($"({leftSide}{compLeft}{partInnerSplit[0].Trim()} && {leftSide}{compRight}{partInnerSplit[1].Trim()})");
continue;
}
throw Logger.Error<DmnParserException>($"Wrong S-FEEL range {part}");
}
// string in "" "", number,variable name, .. - compare for eq
conditionParts.Add($"{leftSide}=={part}");
}
var condition = string.Join(" || ", conditionParts);
if (isNegated) condition = $"!({condition})";
if (Logger.IsTraceEnabled)
Logger.Trace($"Parsed input expression {expr} for variable {leftSide} - {condition}");
return condition;
}
19
View Source File : LoggingTest.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
private async Task LoggingToMemoryWithoutDICore(LogFileAccessMode accessMode)
{
const string logsDirName = "Logs";
var fileProvider = new MemoryFileProvider();
var filterOptions = new LoggerFilterOptions { MinLevel = LogLevel.Trace };
var options = new FileLoggerOptions
{
FileAppender = new MemoryFileAppender(fileProvider),
BasePath = logsDirName,
FileAccessMode = accessMode,
FileEncoding = Encoding.UTF8,
MaxQueueSize = 100,
DateFormat = "yyMMdd",
CounterFormat = "000",
MaxFileSize = 10,
Files = new[]
{
new LogFileOptions
{
Path = "<date>/<date:MM>/logger.log",
DateFormat = "yyyy",
MinLevel = new Dictionary<string, LogLevel>
{
["Karambolo.Extensions.Logging.File"] = LogLevel.None,
[LogFileOptions.DefaultCategoryName] = LogLevel.Information,
}
},
new LogFileOptions
{
Path = "test-<date>-<counter>.log",
MinLevel = new Dictionary<string, LogLevel>
{
["Karambolo.Extensions.Logging.File"] = LogLevel.Information,
[LogFileOptions.DefaultCategoryName] = LogLevel.None,
}
},
},
TextBuilder = new CustomLogEntryTextBuilder(),
IncludeScopes = true,
};
var completeCts = new CancellationTokenSource();
var context = new TestFileLoggerContext(completeCts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var diagnosticEventReceived = false;
context.DiagnosticEvent += _ => diagnosticEventReceived = true;
var ex = new Exception();
var provider = new FileLoggerProvider(context, Options.Create(options));
await using (provider)
using (var loggerFactory = new LoggerFactory(new[] { provider }, filterOptions))
{
ILogger<LoggingTest> logger1 = loggerFactory.CreateLogger<LoggingTest>();
logger1.LogInformation("This is a nice logger.");
using (logger1.BeginScope("SCOPE"))
{
logger1.LogWarning(1, "This is a smart logger.");
logger1.LogTrace("This won't make it.");
using (logger1.BeginScope("NESTED SCOPE"))
{
ILogger logger2 = loggerFactory.CreateLogger("X");
logger2.LogWarning("Some warning.");
logger2.LogError(0, ex, "Some failure!");
}
}
}
replacedert.True(provider.Completion.IsCompleted);
replacedert.False(diagnosticEventReceived);
var logFile = (MemoryFileInfo)fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}-000.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.UTF8, encoding);
replacedert.Equal(new[]
{
$"[info]: {typeof(LoggingTest)}[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a nice logger.",
""
}, lines);
logFile = (MemoryFileInfo)fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}-001.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.UTF8, encoding);
replacedert.Equal(new[]
{
$"[warn]: {typeof(LoggingTest)}[1] @ {context.GetTimestamp().ToLocalTime():o}",
$" => SCOPE",
$" This is a smart logger.",
""
}, lines);
logFile = (MemoryFileInfo)fileProvider.GetFileInfo(
$"{logsDirName}/{context.GetTimestamp().ToLocalTime():yyyy}/{context.GetTimestamp().ToLocalTime():MM}/logger.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.UTF8, encoding);
replacedert.Equal(new[]
{
$"[warn]: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" => SCOPE => NESTED SCOPE",
$" Some warning.",
$"[fail]: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" => SCOPE => NESTED SCOPE",
$" Some failure!",
}
.Concat(ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
.Append(""), lines);
}
19
View Source File : POGeneratorTest.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
private void Generate_LineBreak_Core(string id, params string[] lines)
{
var generator = new POGenerator(new POGeneratorSettings
{
IgnoreEncoding = true,
SkipInfoHeaders = true,
});
var catalog = new POCatalog { Encoding = "UTF-8" };
var entry = new POSingularEntry(new POKey(id));
catalog.Add(entry);
var sb = new StringBuilder();
generator.Generate(sb, catalog);
var expected = new List<string>();
expected.Add(@"msgid """"");
expected.AddRange(lines);
expected.Add(@"msgstr """"");
IEnumerable<string> actual = sb.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None).Skip(5).Take(lines.Length + 2);
replacedert.Equal(expected, actual);
}
19
View Source File : BigDecimal.cs
License : MIT License
Project Creator : AdamWhiteHat
License : MIT License
Project Creator : AdamWhiteHat
public BigInteger GetWholePart()
{
if (this == null)
{
throw new TypeInitializationException(nameof(BigDecimal), new NullReferenceException());
}
if (Mantissa == null) return BigInteger.Zero;
string resultString = string.Empty;
string decimalString = BigDecimal.ToString(Mantissa, Exponent, BigDecimalNumberFormatInfo);
string[] valueSplit = decimalString.Split(new string[] { BigDecimalNumberFormatInfo.NumberDecimalSeparator }, StringSplitOptions.RemoveEmptyEntries);
if (valueSplit.Length > 0)
{
resultString = valueSplit[0];
}
return BigInteger.Parse(resultString);
}
19
View Source File : LoggingTest.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
private async Task LoggingToPhysicalUsingDICore(LogFileAccessMode accessMode)
{
var logsDirName = Guid.NewGuid().ToString("D");
var configData = new Dictionary<string, string>
{
[$"{nameof(FileLoggerOptions.BasePath)}"] = logsDirName,
[$"{nameof(FileLoggerOptions.FileEncodingName)}"] = "UTF-16",
[$"{nameof(FileLoggerOptions.DateFormat)}"] = "yyMMdd",
[$"{nameof(FileLoggerOptions.FileAccessMode)}"] = accessMode.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.Path)}"] = "logger-<date>.log",
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File"] = LogLevel.None.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.Information.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.Path)}"] = "test-<date>.log",
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File.Test"] = LogLevel.Information.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.None.ToString(),
};
var cb = new ConfigurationBuilder();
cb.AddInMemoryCollection(configData);
IConfigurationRoot config = cb.Build();
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
var fileProvider = new PhysicalFileProvider(tempPath);
var cts = new CancellationTokenSource();
var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var diagnosticEventReceived = false;
context.DiagnosticEvent += _ => diagnosticEventReceived = true;
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context, o => o.FileAppender = new PhysicalFileAppender(fileProvider)));
services.Configure<FileLoggerOptions>(config);
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
try
{
var ex = new Exception();
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();
logger1.LogInformation("This is a nice logger.");
using (logger1.BeginScope("SCOPE"))
{
logger1.LogWarning(1, "This is a smart logger.");
logger1.LogTrace("This won't make it.");
using (logger1.BeginScope("NESTED SCOPE"))
{
ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>();
ILogger logger2 = loggerFactory.CreateLogger("X");
logger2.LogError(0, ex, "Some failure!");
}
}
cts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
replacedert.False(diagnosticEventReceived);
IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.Unicode, encoding);
replacedert.Equal(new[]
{
$"info: {typeof(LoggingTest)}[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a nice logger.",
$"warn: {typeof(LoggingTest)}[1] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a smart logger.",
""
}, lines);
logFile = fileProvider.GetFileInfo(
$"{logsDirName}/logger-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.Unicode, encoding);
replacedert.Equal(new[]
{
$"fail: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" Some failure!",
}
.Concat(ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
.Append(""), lines);
}
finally
{
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
}
}
19
View Source File : ArgumentsHelper.uwp.cs
License : MIT License
Project Creator : adenearnshaw
License : MIT License
Project Creator : adenearnshaw
internal static JumpListArguments DeserializeArguments(string json)
{
// Support for backwards compatibility from v0.5
if (json.Contains("||"))
{
var parts = json.Split(new[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
return new JumpListArguments(parts[0], parts[1]);
}
var args = new JumpListArguments();
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var ser = new DataContractJsonSerializer(args.GetType());
args = ser.ReadObject(ms) as JumpListArguments;
return args;
}
}
19
View Source File : SimpleHtmlFormatter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IHtmlString Format(string text)
{
if (text == null)
{
return null;
}
text = WebUtility.HtmlEncode(text);
text = LinkifyUrls ? ReplaceUrlsWithLinks(text) : text;
// Split text on blank lines.
var blocks = text.Split(new[] { "\r\n\r\n", "\n\n" }, StringSplitOptions.RemoveEmptyEntries);
var html = new StringBuilder();
foreach (var block in blocks)
{
// Replace line breaks with <br> tags.
var withLineBreaks = block
.Replace("\r\n", "<br />")
.Replace("\n", "<br />");
// Wrap the block in a paragraph.
html.AppendFormat(CultureInfo.InvariantCulture, "<p>{0}</p>", withLineBreaks);
}
return new HtmlString(html.ToString());
}
19
View Source File : AddressCompositeControlTemplate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override void InstantiateControlIn(Control container)
{
var contentId = Guid.NewGuid();
if (this.Metadata.ReadOnly)
{
this.isEditable = false;
}
var addressTextBox = new TextBox
{
ID = this.ControlID,
CssClreplaced = string.Join(" ", "trigger", this.CssClreplaced, this.Metadata.CssClreplaced, "addressCompositeControl"),
ToolTip = this.Metadata.ToolTip,
TextMode = TextBoxMode.MultiLine
};
addressTextBox.Attributes.Add("data-composite-control", string.Empty);
addressTextBox.Attributes.Add("data-content-id", contentId.ToString());
addressTextBox.Attributes.Add("data-editable", this.isEditable.ToString());
try
{
addressTextBox.Rows = checked((this.Metadata.RowSpan.GetValueOrDefault(2) * 3) - 2);
}
catch (OverflowException)
{
addressTextBox.Rows = 3;
}
container.Controls.Add(addressTextBox);
// Creating container for all popover elements
var divContainer = new HtmlGenericControl("div");
divContainer.Attributes["clreplaced"] = "content hide addressCompositeControlContainer";
divContainer.ID = contentId.ToString();
var addRangeControls =
new Action<IEnumerable<Control>>(controls => { controls.ForEach(x => divContainer.Controls.Add(x)); });
container.Controls.Add(divContainer);
switch (CultureInfo.CurrentUICulture.LCID)
{
case LocaleIds.replacedanese:
addressTextBox.Attributes.Add(
"data-content-template",
string.Format("{{{0}_postalcode}}{{BREAK}}{{{0}_country}} {{{0}_stateorprovince}} {{{0}_city}}{{BREAK}}{{{0}_line1}} {{{0}_line2}}", this.ControlID));
this.addressControlValue = new StringBuilder(addressTextBox.Attributes["data-content-template"]);
this.MakePostalCode(addRangeControls);
this.MakeCountry(addRangeControls);
this.MakeState(addRangeControls);
this.MakeCity(addRangeControls);
this.MakeAddressLine1(addRangeControls);
this.MakeAddressLine2(addRangeControls);
break;
case LocaleIds.ChineseSimplified:
case LocaleIds.ChineseHongKong:
case LocaleIds.ChineseTraditional:
case LocaleIds.Korean:
addressTextBox.Attributes.Add(
"data-content-template",
string.Format("{{{0}_postalcode}} {{{0}_country}}{{BREAK}}{{{0}_stateorprovince}} {{{0}_city}}{{BREAK}}{{{0}_line1}}", this.ControlID));
this.addressControlValue = new StringBuilder(addressTextBox.Attributes["data-content-template"]);
this.MakePostalCode(addRangeControls);
this.MakeCountry(addRangeControls);
this.MakeState(addRangeControls);
this.MakeCity(addRangeControls);
this.MakeAddressLine1(addRangeControls);
break;
default:
addressTextBox.Attributes.Add(
"data-content-template",
string.Format("{{{0}_line1}} {{{0}_line2}} {{{0}_line3}}{{BREAK}}{{{0}_city}} {{{0}_stateorprovince}} {{{0}_postalcode}}{{BREAK}}{{{0}_country}}", this.ControlID));
this.addressControlValue = new StringBuilder(addressTextBox.Attributes["data-content-template"]);
this.MakeAddressLine1(addRangeControls);
this.MakeAddressLine2(addRangeControls);
this.MakeAddressLine3(addRangeControls);
this.MakeCity(addRangeControls);
this.MakeState(addRangeControls);
this.MakePostalCode(addRangeControls);
this.MakeCountry(addRangeControls);
break;
}
var doneButton = new HtmlGenericControl("input");
doneButton.Attributes["clreplaced"] = "btn btn-primary btn-block";
doneButton.Attributes["role"] = "button";
doneButton.ID = "popoverUpdateButton_" + Guid.NewGuid().ToString().Trim();
doneButton.Attributes["readonly"] = "true";
doneButton.Attributes.Add("value", ResourceManager.GetString("Composite_Control_Done"));
addRangeControls(new[] { doneButton });
var ariaLabelPattern = "{0}. {1}";
if (this.Metadata.IsRequired || this.Metadata.WebFormForceFieldIsRequired)
{
addressTextBox.Attributes.Add("required", string.Empty);
ariaLabelPattern = "{0}*. {1}";
}
if (this.isEditable)
{
addressTextBox.Attributes.Add("aria-label", string.Format(ariaLabelPattern, this.Metadata.Label, ResourceManager.GetString("Narrator_Label_For_Composite_Controls")));
}
else
{
addressTextBox.CssClreplaced += " readonly ";
}
this.Bindings[this.ControlID] = new CellBinding
{
Get = () =>
{
var str = addressTextBox.Text;
return str ?? string.Empty;
},
Set = obj =>
{
Enreplacedy enreplacedy = obj as Enreplacedy;
foreach (var bindAction in this.bindControlValue)
{
bindAction(enreplacedy);
}
var textBoxValue = string.Join("\r\n",
this.addressControlValue.ToString()
.Split(new[] { "{BREAK}" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim()));
addressTextBox.Text = textBoxValue;
}
};
}
19
View Source File : LiquidServerControl.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void AddTemplate(string html)
{
var regex = new Regex(@"\<!--\[% (\w+) id:([A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12})? %\]--\>",
RegexOptions.IgnoreCase);
Control container = this;
if (regex.IsMatch(html))
{
container = ServerForm(container);
}
while (regex.IsMatch(html))
{
var match = regex.Match(html);
var control = match.Groups[1].Value;
var id = match.Groups[2].Value;
Guid guid;
if (Guid.TryParse(id, out guid))
{
var splits = html.Split(new[] { match.Value }, StringSplitOptions.RemoveEmptyEntries);
var preSplit = new LiteralControl(splits[0]);
container.Controls.Add(preSplit);
switch (control)
{
case "enreplacedyform":
var enreplacedyForm = InitEnreplacedyForm(guid);
container.Controls.Add(enreplacedyForm);
break;
case "webform":
var webForm = InitWebForm(guid);
container.Controls.Add(webForm);
break;
}
html = string.Join(match.Value, splits.Skip(1));
}
}
var close = new LiteralControl(html);
container.Controls.Add(close);
}
19
View Source File : EmbeddedResourceAssemblyAttribute.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static void AddResource(EmbeddedResourceNode resources, IDictionary<string, EmbeddedResourceNode> lookup, string path, string resourceName)
{
var parts = path.Split(_directoryDelimiters, StringSplitOptions.RemoveEmptyEntries);
AddResource(resources, lookup, parts, resourceName);
}
19
View Source File : EmbeddedResourceAssemblyAttribute.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private string ConvertVirtualPathToResourceName(string virtualPath)
{
// converting an entire path
// for all parts: prepend an '_' if the name starts with a numeric character
// replace all '/' or '\\' with '.'
// prepend the default namespace
// besides a leading underscore, filenames remain unchanged
var parts = virtualPath.Split(_directoryDelimiters, StringSplitOptions.RemoveEmptyEntries);
if (parts.Any())
{
var partsWithUnderscores = parts.Select(p => Regex.IsMatch(p, @"^\d") ? "_" + p : p);
var directories = partsWithUnderscores.Take(parts.Length - 1).Select(ConvertDirectoryToResourceName);
var head = directories.Aggregate(Namespace, (h, d) => "{0}.{1}".FormatWith(h, d)).Replace('-', '_');
var tail = partsWithUnderscores.Last();
return "{0}.{1}".FormatWith(head, tail);
}
return null;
}
19
View Source File : AbstractLogger.cs
License : MIT License
Project Creator : adrianmteo
License : MIT License
Project Creator : adrianmteo
public void Log(LogLevel level, string format, params object[] args)
{
if (level >= MinimumLevel && level <= MaximumLevel)
{
string date = DateTime.Now.ToString(DateFormat);
string log = string.Format(format, args);
string[] lines = log.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string message = MessageFormat
.Replace(LogMessageToken.Date, date)
.Replace(LogMessageToken.Level, level.ToString().ToUpper())
.Replace(LogMessageToken.Message, line)
.Replace(LogMessageToken.Tag, Tag);
WriteMessage(message);
}
}
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : aguang-xyz
License : MIT License
Project Creator : aguang-xyz
public static IEnumerable<string> AsLines(this string content)
{
return content.Split(new[] { "\r", "\n", "\r\n" }, StringSplitOptions.None);
}
19
View Source File : ScrollBar.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public void ScrollBarManagedProperties()
{
if (ManagedProperties.Count > 0)
{
foreach (ClManagedProperty ClManagedProperty1 in ManagedProperties.Base_obj)
{
object obj1 = ClManagedProperty1.ManagedObject;
string prop1 = "";
float ratio1 = 1.0f;
if (ClManagedProperty1.Ratio == null)
{
}
else
{
ratio1 = Convert.ToSingle(ClManagedProperty1.Ratio.AsNumber());
}
System.Reflection.PropertyInfo[] myPropertyInfo;
myPropertyInfo = obj1.GetType().GetProperties();
for (int i = 0; i < myPropertyInfo.Length; i++)
{
System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributeData1 =
myPropertyInfo[i].CustomAttributes;
foreach (System.Reflection.CustomAttributeData CustomAttribute1 in CustomAttributeData1)
{
string quote = "\"";
string text = CustomAttribute1.ToString();
if (text.Contains("[ScriptEngine.Machine.Contexts.ContextPropertyAttribute(" + quote))
{
text = text.Replace("[ScriptEngine.Machine.Contexts.ContextPropertyAttribute(" + quote, "");
text = text.Replace(quote + ", " + quote, " ");
text = text.Replace(quote + ")]", "");
string[] stringSeparators = new string[] { };
string[] result = text.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
if (ClManagedProperty1.ManagedProperty == result[0])
{
prop1 = result[1];
break;
}
}
}
}
System.Type Type1 = obj1.GetType();
float _Value = Convert.ToSingle(v_h_ScrollBar.Value);
int res = Convert.ToInt32(ratio1 * _Value);
if (Type1.GetProperty(prop1).PropertyType.ToString() != "System.String")
{
Type1.GetProperty(prop1).SetValue(obj1, res);
}
else
{
Type1.GetProperty(prop1).SetValue(obj1, res.ToString());
}
}
}
}
19
View Source File : DebugConsole.cs
License : MIT License
Project Creator : akihiro0105
License : MIT License
Project Creator : akihiro0105
private void logMessageReceived(string condition, string stackTrace, LogType type)
{
// ログメッセージ通知
if (DebugConsoleEvent != null) DebugConsoleEvent(condition, stackTrace, type);
// ログメッセージをUIに表示
var conditions = condition.Split(new string[] { System.Environment.NewLine }, System.StringSplitOptions.None);
foreach (var t in conditions) logQueue.Enqueue(t);
for (var i = 0; i < logQueue.Count - maxQueue; i++) logQueue.Dequeue();
if (logText != null)
{
logText.text = "";
foreach (var t in logQueue.ToArray()) logText.text += t + System.Environment.NewLine;
}
}
19
View Source File : EnumsCheckComboBox.xaml.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
private void UpdateFromText()
{
List<string> selectedValues = null;
if (!string.IsNullOrEmpty(Text))
{
selectedValues = Text.Replace(" ", string.Empty).Split(new string[1]
{
Delimiter
}, StringSplitOptions.RemoveEmptyEntries).ToList();
}
_updateList.Invoke(this, new object[] { selectedValues, new Func<object, object>(GetEnumDisplayValue) });
}
19
View Source File : AssetDanshariUtility.cs
License : MIT License
Project Creator : akof1314
License : MIT License
Project Creator : akof1314
public static string[] PathStrToArray(string paths)
{
paths = paths.Trim('\"');
return paths.Split(new[] { "\" || \"" }, StringSplitOptions.RemoveEmptyEntries);
}
19
View Source File : ExtensionMethods.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static List<string> WrapText(this string text, double pixels, string fontFamily, float emSize, out double actualHeight)
{
string[] originalLines = text.Split(new string[] { " " },
StringSplitOptions.None);
List<string> wrappedLines = new List<string>();
StringBuilder actualLine = new StringBuilder();
double actualWidth = 0;
actualHeight = 0;
foreach (var item in originalLines)
{
System.Windows.Media.FormattedText formatted = new System.Windows.Media.FormattedText(item,
CultureInfo.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new System.Windows.Media.Typeface(fontFamily), emSize, System.Windows.Media.Brushes.Black);
actualWidth += formatted.Width;
actualHeight = formatted.Height;
if (actualWidth > pixels)
{
wrappedLines.Add(actualLine.ToString());
actualLine.Clear();
actualWidth = 0;
actualLine.Append(item + " ");
actualWidth += formatted.Width;
}
else if (item == Environment.NewLine || item=="\n")
{
wrappedLines.Add(actualLine.ToString());
actualLine.Clear();
actualWidth = 0;
}
else
{
actualLine.Append(item + " ");
}
}
if (actualLine.Length > 0)
wrappedLines.Add(actualLine.ToString());
return wrappedLines;
}
19
View Source File : GeometryExtrusionOptionsDrawer.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
private void DrawPropertyName(SerializedProperty property, Rect position, string selectedLayerName)
{
var parsedString = "No property selected";
var descriptionString = "No description available";
if (string.IsNullOrEmpty(selectedLayerName) || tileJsonData == null || !tileJsonData.PropertyDisplayNames.ContainsKey(selectedLayerName))
{
DrawWarningMessage(position);
}
else
{
var propertyDisplayNames = tileJsonData.PropertyDisplayNames[selectedLayerName];
_propertyNamesList = new List<string>(propertyDisplayNames);
//check if the selection is valid
var propertyString = property.FindPropertyRelative("propertyName").stringValue;
if (_propertyNamesList.Contains(propertyString))
{
//if the layer contains the current layerstring, set it's index to match
_propertyIndex = propertyDisplayNames.FindIndex(s => s.Equals(propertyString));
//create guicontent for a valid layer
_propertyNameContent = new GUIContent[_propertyNamesList.Count];
for (int extIdx = 0; extIdx < _propertyNamesList.Count; extIdx++)
{
var parsedPropertyString = _propertyNamesList[extIdx].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
_propertyNameContent[extIdx] = new GUIContent
{
text = _propertyNamesList[extIdx],
tooltip = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedPropertyString]
};
}
//display popup
var propertyNameLabel = new GUIContent { text = "Property Name", tooltip = "The name of the property in the selected Mapbox layer that will be used for extrusion" };
EditorGUI.BeginChangeCheck();
_propertyIndex = EditorGUILayout.Popup(propertyNameLabel, _propertyIndex, _propertyNameContent);
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(property);
}
//set new string values based on selection
parsedString = _propertyNamesList[_propertyIndex].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
descriptionString = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedString];
}
else
{
//if the selected layer isn't in the source, add a placeholder entry
_propertyIndex = 0;
_propertyNamesList.Insert(0, propertyString);
//create guicontent for an invalid layer
_propertyNameContent = new GUIContent[_propertyNamesList.Count];
//first property gets a unique tooltip
_propertyNameContent[0] = new GUIContent
{
text = _propertyNamesList[0],
tooltip = "Unavialable in Selected Layer"
};
for (int extIdx = 1; extIdx < _propertyNamesList.Count; extIdx++)
{
var parsedPropertyString = _propertyNamesList[extIdx].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
_propertyNameContent[extIdx] = new GUIContent
{
text = _propertyNamesList[extIdx],
tooltip = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedPropertyString]
};
}
//display popup
var propertyNameLabel = new GUIContent { text = "Property Name", tooltip = "The name of the property in the selected Mapbox layer that will be used for extrusion" };
EditorGUI.BeginChangeCheck();
_propertyIndex = EditorGUILayout.Popup(propertyNameLabel, _propertyIndex, _propertyNameContent);
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(property);
}
//set new string values based on the offset
parsedString = _propertyNamesList[_propertyIndex].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
descriptionString = "Unavailable in Selected Layer.";
}
property.FindPropertyRelative("propertyName").stringValue = parsedString;
property.FindPropertyRelative("propertyDescription").stringValue = descriptionString;
}
descriptionString = string.IsNullOrEmpty(descriptionString) ? "No description available" : descriptionString;
var propertyDescriptionPrefixLabel = new GUIContent { text = "Property Description", tooltip = "Factual information about the selected property" };
EditorGUILayout.LabelField(propertyDescriptionPrefixLabel, new GUIContent(descriptionString), (GUIStyle)"wordWrappedLabel");
}
19
View Source File : FeaturesSubLayerPropertiesDrawer.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public void DrawLayerName(SerializedProperty property, List<string> layerDisplayNames)
{
var layerNameLabel = new GUIContent
{
text = "Data Layer",
tooltip = "The layer name from the Mapbox tileset that would be used for visualizing a feature"
};
//disable the selection if there is no layer
if (layerDisplayNames.Count == 0)
{
EditorGUILayout.LabelField(layerNameLabel, new GUIContent("No layers found: Invalid TilesetId / No Internet."), (GUIStyle)"minipopUp");
return;
}
//check the string value at the current _layerIndex to verify that the stored index matches the property string.
var layerString = property.FindPropertyRelative("layerName").stringValue;
if (layerDisplayNames.Contains(layerString))
{
//if the layer contains the current layerstring, set it's index to match
_layerIndex = layerDisplayNames.FindIndex(s => s.Equals(layerString));
}
else
{
//if the selected layer isn't in the source, add a placeholder entry
_layerIndex = 0;
layerDisplayNames.Insert(0, layerString);
if (!tileJsonData.LayerPropertyDescriptionDictionary.ContainsKey(layerString))
{
tileJsonData.LayerPropertyDescriptionDictionary.Add(layerString, new Dictionary<string, string>());
}
}
//create the display name guicontent array with an additional entry for the currently selected item
_layerTypeContent = new GUIContent[layerDisplayNames.Count];
for (int extIdx = 0; extIdx < layerDisplayNames.Count; extIdx++)
{
_layerTypeContent[extIdx] = new GUIContent
{
text = layerDisplayNames[extIdx],
};
}
//draw the layer selection popup
_layerIndex = EditorGUILayout.Popup(layerNameLabel, _layerIndex, _layerTypeContent);
var parsedString = layerDisplayNames.ToArray()[_layerIndex].Split(new string[] { tileJsonData.commonLayersKey }, System.StringSplitOptions.None)[0].Trim();
property.FindPropertyRelative("layerName").stringValue = parsedString;
}
19
View Source File : VectorFilterOptionsDrawer.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
private void DrawPropertyDropDown(SerializedProperty originalProperty, SerializedProperty filterProperty)
{
var selectedLayerName = originalProperty.FindPropertyRelative("_selectedLayerName").stringValue;
AbstractMap mapObject = (AbstractMap)originalProperty.serializedObject.targetObject;
TileJsonData tileJsonData = mapObject.VectorData.GetTileJsonData();
if (string.IsNullOrEmpty(selectedLayerName) || !tileJsonData.PropertyDisplayNames.ContainsKey(selectedLayerName))
{
DrawWarningMessage();
return;
}
var parsedString = "no property selected";
var descriptionString = "no description available";
var propertyDisplayNames = tileJsonData.PropertyDisplayNames[selectedLayerName];
_propertyNamesList = new List<string>(propertyDisplayNames);
var propertyString = filterProperty.FindPropertyRelative("Key").stringValue;
//check if the selection is valid
if (_propertyNamesList.Contains(propertyString))
{
//if the layer contains the current layerstring, set it's index to match
_propertyIndex = propertyDisplayNames.FindIndex(s => s.Equals(propertyString));
//create guicontent for a valid layer
_propertyNameContent = new GUIContent[_propertyNamesList.Count];
for (int extIdx = 0; extIdx < _propertyNamesList.Count; extIdx++)
{
var parsedPropertyString = _propertyNamesList[extIdx].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
_propertyNameContent[extIdx] = new GUIContent
{
text = _propertyNamesList[extIdx],
tooltip = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedPropertyString]
};
}
//display popup
EditorGUI.BeginChangeCheck();
_propertyIndex = EditorGUILayout.Popup(_propertyIndex, _propertyNameContent, GUILayout.MaxWidth(150));
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(filterProperty);
}
//set new string values based on selection
parsedString = _propertyNamesList[_propertyIndex].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
descriptionString = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedString];
}
else
{
//if the selected layer isn't in the source, add a placeholder entry
_propertyIndex = 0;
_propertyNamesList.Insert(0, propertyString);
//create guicontent for an invalid layer
_propertyNameContent = new GUIContent[_propertyNamesList.Count];
//first property gets a unique tooltip
_propertyNameContent[0] = new GUIContent
{
text = _propertyNamesList[0],
tooltip = "Unavialable in Selected Layer"
};
for (int extIdx = 1; extIdx < _propertyNamesList.Count; extIdx++)
{
var parsedPropertyString = _propertyNamesList[extIdx].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
_propertyNameContent[extIdx] = new GUIContent
{
text = _propertyNamesList[extIdx],
tooltip = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedPropertyString]
};
}
//display popup
EditorGUI.BeginChangeCheck();
_propertyIndex = EditorGUILayout.Popup(_propertyIndex, _propertyNameContent, GUILayout.MaxWidth(150));
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(filterProperty);
}
//set new string values based on the offset
parsedString = _propertyNamesList[_propertyIndex].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
descriptionString = "Unavailable in Selected Layer.";
}
EditorGUI.BeginChangeCheck();
filterProperty.FindPropertyRelative("Key").stringValue = parsedString;
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(filterProperty);
}
filterProperty.FindPropertyRelative("KeyDescription").stringValue = descriptionString;
}
19
View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
internal void CleanDecoder(string replaceWith)
{
if (!EndWithDecoder())
sb.Append(replaceWith);
else
{
MatchCollection matches = null;
var result = new string[0];
while ((matches = DataEncodeExp.Matches(sb.ToString())).Count > 0)
{
var m = matches[0];
result = m.Value.Replace("</DataEncode>", "").TrimEnd(']').Substring(@"<DataEncode>\[".Length - 1).Split('|'); // get the key
sb = sb.Remove(m.Index, m.Value.Length);
if (replaceWith.Contains("String["))
{
var spt = replaceWith.Split(new string[] { "]," }, StringSplitOptions.None).Where(x => !string.IsNullOrEmpty(x));
var i = 0;
var value = "";
foreach (var str in spt)
{
i++;
var xValue = str.Trim().Replace("String[", "").TrimEnd("]");
var rValue = xValue.TrimStart('%').TrimEnd("%");
var codedValue = new DataCipher(result.First(), result.Last().ConvertValue<int>().ConvertValue<DataCipherKeySize>()).Encrypt(rValue);
if (xValue.StartsWith("%"))
codedValue = "%" + codedValue;
if (xValue.EndsWith("%"))
codedValue += "%";
value += $"String[{codedValue}]{(i == spt.Count() ? "" : ",")}";
}
sb.Insert(m.Index, value);
}
else if (replaceWith.Contains("Date["))
{
var spt = replaceWith.Split(new string[] { "]," }, StringSplitOptions.None).Where(x => !string.IsNullOrEmpty(x));
var i = 0;
var value = "";
foreach (var str in spt)
{
i++;
var xValue = str.Trim().Replace("Date[", "").TrimEnd("]");
var rValue = xValue.TrimStart('%').TrimEnd("%");
var codedValue = new DataCipher(result.First(), result.Last().ConvertValue<int>().ConvertValue<DataCipherKeySize>()).Encrypt(rValue);
if (xValue.StartsWith("%"))
codedValue = "%" + codedValue;
if (xValue.EndsWith("%"))
codedValue += "%";
value += $"Date[{codedValue}]{(i == spt.Count() ? "" : ",")}";
}
sb.Insert(m.Index, value);
}
else
sb = sb.Insert(m.Index, new DataCipher(result.First(), result.Last().ConvertValue<int>().ConvertValue<DataCipherKeySize>()).Encrypt(replaceWith));
}
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : alexanderdna
License : MIT License
Project Creator : alexanderdna
private static void runMainLoop(CLOptions options)
{
switch (options.LogMode)
{
case "console":
_logger = App.ConsoleLogger;
break;
case "both":
_logger = App.FileAndConsoleLogger;
break;
case "file":
default:
_logger = App.FileLogger;
options.LogMode = LogMode.File;
break;
}
_app = new App(App.DefaultPathsProvider, _logger);
_options = options;
if (options.ListeningPort > 0)
{
_app.Listen(options.ListeningPort);
}
_app.ConnectToPeers();
if (_app.IsInIbd)
{
ensureLogToConsole(App.LogLevel.Info, "Initial block download is running...");
Console.Out.Flush();
while (_app.IsInIbd)
{
Thread.Sleep(100);
}
if (_app.Daemon.CurrentIbdPhase == InitialBlockDownload.Phase.Succeeded)
{
ensureLogToConsole(App.LogLevel.Info, "Initial block download is finished.");
ensureLogToConsole(App.LogLevel.Info, $"Current height: {_app.ChainManager.Height}");
}
else
{
ensureLogToConsole(App.LogLevel.Info, "Initial block download failed. Exitting...");
return;
}
}
Console.CancelKeyPress += onSigInt;
var token = _app.CancellationTokenSource.Token;
if (options.IsNode)
{
while (!token.IsCancellationRequested)
{
Thread.Sleep(500);
}
}
else
{
Console.WriteLine("Welcome to ameow-cli. Enter `help` to show help message.");
Console.WriteLine();
var inputSeparator = new string[] { " " };
while (!token.IsCancellationRequested)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(">>> ");
string input = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Gray;
if (input == null)
{
Thread.Sleep(100);
if (token.IsCancellationRequested)
break;
}
string[] args = input.Split(inputSeparator, StringSplitOptions.RemoveEmptyEntries);
if (args.Length == 0) continue;
string cmdName = args[0];
Command cmd = commands.Find(c => c.Name == cmdName);
if (cmd != null)
cmd.Handler(args);
else
cmd_help(args);
}
}
try
{
_app.Shutdown();
}
catch (Exception ex)
{
_app.Logger.Log(App.LogLevel.Error, string.Format("Cannot shutdown properly: {0}", ex.Message));
}
}
See More Examples