Here are the examples of the csharp api System.Collections.Generic.IEnumerable.All(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3345 Examples
19
Source : ConsulServiceDiscovery.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task NodeMonitor(CancellationToken cancellationToken)
{
Logger.LogTrace("Start refresh service status,waiting for locking...");
using (await AsyncLock.LockAsync(cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
return;
foreach (var service in ServiceNodes)
{
Logger.LogTrace($"Service {service.Key} refreshing...");
try
{
var healthNodes = await QueryServiceAsync(service.Key, cancellationToken);
if (cancellationToken.IsCancellationRequested)
break;
var leavedNodes = service.Value.Where(p => healthNodes.All(a => a.ServiceId != p.ServiceId))
.Select(p => p.ServiceId).ToArray();
if (leavedNodes.Any())
{
//RemoveNode(service.Key, leavedNodes);
if (!ServiceNodes.TryGetValue(service.Key, out var services)) return;
services.RemoveAll(p => leavedNodes.Any(n => n == p.ServiceId));
OnNodeLeave?.Invoke(service.Key, leavedNodes);
Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
}
var addedNodes = healthNodes.Where(p =>
service.Value.All(e => e.ServiceId != p.ServiceId)).Select(p =>
new ServiceNodeInfo(p.ServiceId, p.Address, p.Port, p.Weight, p.EnableTls, p.Meta))
.ToList();
if (addedNodes.Any())
{
//AddNode(service.Key, addedNodes);
if (ServiceNodes.TryGetValue(service.Key, out var services))
services.AddRange(addedNodes);
else
ServiceNodes.TryAdd(service.Key, addedNodes);
OnNodeJoin?.Invoke(service.Key, addedNodes);
Logger.LogTrace(
$"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
}
}
catch
{
// ignored
}
}
Logger.LogTrace("Complete refresh.");
}
}
19
Source : ZooKeeperServiceDiscovery.cs
with MIT License
from 1100100
with MIT License
from 1100100
private void RefreshNodes(string serviceName, List<ServiceNodeInfo> currentNodes)
{
if (ServiceNodes.TryGetValue(serviceName, out var nodes))
{
if (!currentNodes.Any())
nodes.Clear();
var leavedNodes = nodes.Where(p => currentNodes.All(c => c.ServiceId != p.ServiceId)).Select(p => p.ServiceId).ToList();
if (leavedNodes.Any())
{
Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
OnNodeLeave?.Invoke(serviceName, leavedNodes);
nodes.RemoveAll(p => currentNodes.All(c => c.ServiceId != p.ServiceId));
}
var addedNodes = currentNodes.FindAll(p => nodes.All(c => c.ServiceId != p.ServiceId));
if (addedNodes.Any())
{
nodes.AddRange(addedNodes);
Logger.LogTrace(
$"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
OnNodeJoin?.Invoke(serviceName, addedNodes);
}
}
else
{
if (!currentNodes.Any())
ServiceNodes.TryAdd(serviceName, currentNodes);
}
}
19
Source : EntityDescriptor.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
private void SetColumns()
{
//加载属性列表
var properties = new List<PropertyInfo>();
foreach (var p in EnreplacedyType.GetProperties())
{
var type = p.PropertyType;
if (type == typeof(TimeSpan) || (!type.IsGenericType || type.IsNullable()) && (type.IsGuid() || type.IsNullable() || Type.GetTypeCode(type) != TypeCode.Object)
&& Attribute.GetCustomAttributes(p).All(attr => attr.GetType() != typeof(NotMappingColumnAttribute)))
{
properties.Add(p);
}
}
foreach (var p in properties)
{
var column = new ColumnDescriptor(p, DbContext.Adapter);
if (column.IsPrimaryKey)
{
PrimaryKey = new PrimaryKeyDescriptor(p);
Columns.Insert(0, column);
}
else
{
Columns.Add(column);
}
}
//如果主键为null,则需要指定为没有主键
if (PrimaryKey == null)
{
PrimaryKey = new PrimaryKeyDescriptor();
}
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static bool IsIPZero(byte[] ip)
{
return ip.All(t => t == 0);
}
19
Source : OnOffConstraint.cs
with MIT License
from 5argon
with MIT License
from 5argon
protected override ConstraintResult replacedert()
{
if (FindResult == false)
{
return new ConstraintResult(this, null, isSuccess: false);
}
if (lookingForOn)
{
var allOn = GetOnOffs().All(x => x.IsOn);
return new ConstraintResult(this, FoundBeacon, isSuccess: FindResult && allOn);
}
else
{
var anyOff = GetOnOffs().Any(x => x.IsOn == false);
return new ConstraintResult(this, FoundBeacon, isSuccess: FindResult && anyOff);
}
}
19
Source : CompilationProcessor.cs
with MIT License
from 71
with MIT License
from 71
public static CompilationProcessor Create(
Func<CSharpCompilation, object> moduleBuilderGetter,
Action<Diagnostic> addDiagnostic,
Func<IEnumerable<Diagnostic>> getDiagnostics,
params CompilationEditor[] editors)
{
Debug.replacedert(editors != null);
Debug.replacedert(editors.All(x => x != null));
return new CompilationProcessor(moduleBuilderGetter, addDiagnostic, getDiagnostics, editors);
}
19
Source : ExternalCommunicator.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public void giveBrainInfo(Brain brain)
{
string brainName = brain.gameObject.name;
current_agents[brainName] = new List<int>(brain.agents.Keys);
List<float> concatenatedStates = new List<float>();
List<float> concatenatedRewards = new List<float>();
List<float> concatenatedMemories = new List<float>();
List<bool> concatenatedDones = new List<bool>();
List<float> concatenatedActions = new List<float>();
Dictionary<int, List<Camera>> collectedObservations = brain.CollectObservations();
Dictionary<int, List<float>> collectedStates = brain.CollectStates();
Dictionary<int, float> collectedRewards = brain.CollectRewards();
Dictionary<int, float[]> collectedMemories = brain.CollectMemories();
Dictionary<int, bool> collectedDones = brain.CollectDones();
Dictionary<int, float[]> collectedActions = brain.CollectActions();
foreach (int id in current_agents[brainName])
{
concatenatedStates = concatenatedStates.Concat(collectedStates[id]).ToList();
concatenatedRewards.Add(collectedRewards[id]);
concatenatedMemories = concatenatedMemories.Concat(collectedMemories[id].ToList()).ToList();
concatenatedDones.Add(collectedDones[id]);
concatenatedActions = concatenatedActions.Concat(collectedActions[id].ToList()).ToList();
}
StepMessage message = new StepMessage()
{
brain_name = brainName,
agents = current_agents[brainName],
states = concatenatedStates,
rewards = concatenatedRewards,
actions = concatenatedActions,
memories = concatenatedMemories,
dones = concatenatedDones
};
string envMessage = JsonConvert.SerializeObject(message, Formatting.Indented);
sender.Send(AppendLength(Encoding.ASCII.GetBytes(envMessage)));
Receive();
int i = 0;
foreach (resolution res in brain.brainParameters.cameraResolutions)
{
foreach (int id in current_agents[brainName])
{
sender.Send(AppendLength(TexToByteArray(brain.ObservationToTex(collectedObservations[id][i], res.width, res.height))));
Receive();
}
i++;
}
hreplacedentState[brainName] = true;
if (hreplacedentState.Values.All(x => x))
{
// if all the brains listed have sent their state
sender.Send(Encoding.ASCII.GetBytes((academy.done ? "True" : "False")));
List<string> brainNames = hreplacedentState.Keys.ToList();
foreach (string k in brainNames)
{
hreplacedentState[k] = false;
}
}
}
19
Source : EnumCache.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
public static bool CanHandle(IEnumerable<EnumItem> enumItems)
=> enumItems.All(i => i.Value < 32);
19
Source : SignUpView.vm.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
private bool SignUpCommandCanExecute(PreplacedwordBox preplacedwordBox) => new[]
{
EmailAddress,
Username,
preplacedwordBox.Preplacedword,
}.All(field => !string.IsNullOrEmpty(field));
19
Source : IOExtensions.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static bool CreateHardLinkTo(this string @this, string targetPath)
{
if (File.Exists(targetPath) || Directory.Exists(targetPath)) throw new IOException("Cannot create an existing file or directory. ");
if (File.Exists(@this))
{
return CreateHardLink(targetPath, @this, IntPtr.Zero);
}
if (Directory.Exists(@this))
{
var entries = Directory.GetFileSystemEntries(@this);
Directory.CreateDirectory(targetPath);
// Recursion
return entries.All(item => item.CreateHardLinkTo(Path.Combine(targetPath, Path.GetFileName(item))));
}
throw new FileNotFoundException();
}
19
Source : ConstantRemotePathProvider.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public virtual Task<string> GetAsync()
{
if (RemotePaths.Values.All(item => item < 0))
throw new RemotePathExhaustedException(this);
return Task.FromResult(
RemotePaths.Aggregate((acc, item) => acc.Value < item.Value ? item : acc).Key);
}
19
Source : MessageBuffer.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void AddFragment(ClientPacketFragment fragment)
{
lock (fragments)
{
if (!Complete && fragments.All(x => x.Header.Index != fragment.Header.Index))
{
fragments.Add(fragment);
}
}
}
19
Source : ExpressionUtility.cs
with MIT License
from actions
with MIT License
from actions
internal static Double ParseNumber(String str)
{
// Trim
str = str?.Trim() ?? String.Empty;
// Empty
if (String.IsNullOrEmpty(str))
{
return 0d;
}
// Try parse
else if (Double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var value))
{
return value;
}
// Check for 0x[0-9a-fA-F]+
else if (str[0] == '0' &&
str.Length > 2 &&
str[1] == 'x' &&
str.Skip(2).All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')))
{
// Try parse
if (Int32.TryParse(str.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var integer))
{
return (Double)integer;
}
// Otherwise exceeds range
}
// Check for 0o[0-9]+
else if (str[0] == '0' &&
str.Length > 2 &&
str[1] == 'o' &&
str.Skip(2).All(x => x >= '0' && x <= '7'))
{
// Try parse
var integer = default(Int32?);
try
{
integer = Convert.ToInt32(str.Substring(2), 8);
}
// Otherwise exceeds range
catch (Exception)
{
}
// Success
if (integer != null)
{
return (Double)integer.Value;
}
}
// Infinity
else if (String.Equals(str, ExpressionConstants.Infinity, StringComparison.Ordinal))
{
return Double.PositiveInfinity;
}
// -Infinity
else if (String.Equals(str, ExpressionConstants.NegativeInfinity, StringComparison.Ordinal))
{
return Double.NegativeInfinity;
}
// Otherwise NaN
return Double.NaN;
}
19
Source : DacSemanticModel.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public bool IsFullyUnbound() =>
DacProperties.All(p => p.EffectiveBoundType != BoundType.DbBound && p.EffectiveBoundType != BoundType.Unknown);
19
Source : PsuedoToken.cs
with MIT License
from adamant
with MIT License
from adamant
public override bool Equals(object? obj)
{
if (obj is PsuedoToken token &&
(TokenType == token.TokenType
|| TokenType.IsreplacedignableFrom(token.TokenType)
|| token.TokenType.IsreplacedignableFrom(TokenType)) &&
Text == token.Text)
{
if (Value is IReadOnlyList<Diagnostic> diagnostics
&& token.Value is IReadOnlyList<Diagnostic> otherDiagnostics)
{
// TODO this zip looks wrong, shouldn't it be comparing something rather than always returning false?
return diagnostics.Zip(otherDiagnostics, (d1, d2) => false).All(i => i);
}
return EqualityComparer<object>.Default.Equals(Value, token.Value);
}
return false;
}
19
Source : DmnDecisionTable.cs
with MIT License
from adamecr
with MIT License
from adamecr
private static bool MatchRuleOutputs(IEnumerable<DmnDecisionTableRule> positiveRules, DmnDecisionTableRuleExecutionResults results)
{
var array = positiveRules.ToArray();
if (array.Length < 2) return true;
var firsreplacedem = results.GetResultsHashCode(array[0]);
var allEqual = array.Skip(1).All(i => Equals(firsreplacedem, results.GetResultsHashCode(i)));
return allEqual;
}
19
Source : ConformanceTests.cs
with MIT License
from adamant
with MIT License
from adamant
private List<Diagnostic> CheckErrorsExpected(
TestCase testCase,
CodeFile codeFile,
string code,
FixedList<Diagnostic> diagnostics)
{
// Check for compiler errors
var expectCompileErrors = ExpectCompileErrors(code);
var expectedCompileErrorLines = ExpectedCompileErrorLines(codeFile, code);
if (diagnostics.Any())
{
testOutput.WriteLine("Compiler Errors:");
foreach (var diagnostic in diagnostics)
{
testOutput.WriteLine(
$"{testCase.RelativeCodePath}:{diagnostic.StartPosition.Line}:{diagnostic.StartPosition.Column} {diagnostic.Level} {diagnostic.ErrorCode}");
testOutput.WriteLine(diagnostic.Message);
}
testOutput.WriteLine("");
}
var errorDiagnostics = diagnostics
.Where(d => d.Level >= DiagnosticLevel.CompilationError).ToList();
if (expectedCompileErrorLines.Any())
{
foreach (var expectedCompileErrorLine in expectedCompileErrorLines)
{
// replacedert a single error on the given line
var errorsOnLine = errorDiagnostics.Count(e =>
e.StartPosition.Line == expectedCompileErrorLine);
replacedert.True(errorsOnLine == 1,
$"Expected one error on line {expectedCompileErrorLine}, found {errorsOnLine}");
}
}
if (expectCompileErrors)
replacedert.True(errorDiagnostics.Any(), "Expected compilation errors and there were none");
else
foreach (var error in errorDiagnostics)
{
var errorLine = error.StartPosition.Line;
if (expectedCompileErrorLines.All(line => line != errorLine))
replacedert.True(false, $"Unexpected error on line {error.StartPosition.Line}");
}
return errorDiagnostics;
}
19
Source : SettingsTest.cs
with MIT License
from adams85
with MIT License
from adams85
[Fact]
public async Task ReloadOptionsSettings()
{
var configJson =
$@"{{
""{FileLoggerProvider.Alias}"": {{
""{nameof(FileLoggerOptions.IncludeScopes)}"" : true,
""{nameof(FileLoggerOptions.Files)}"": [
{{
""{nameof(LogFileOptions.Path)}"": ""test.log"",
}}],
""{nameof(LoggerFilterRule.LogLevel)}"": {{
""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.Trace}""
}}
}}
}}";
var fileProvider = new MemoryFileProvider();
fileProvider.CreateFile("config.json", configJson, Encoding.UTF8);
var cb = new ConfigurationBuilder();
cb.AddJsonFile(fileProvider, "config.json", optional: false, reloadOnChange: true);
IConfigurationRoot config = cb.Build();
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 services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b =>
{
b.AddConfiguration(config);
b.AddFile(context);
});
var fileAppender = new MemoryFileAppender(fileProvider);
services.Configure<FileLoggerOptions>(o => o.FileAppender ??= fileAppender);
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
var resetTasks = new List<Task>();
foreach (FileLoggerProvider provider in providers)
provider.Reset += (s, e) => resetTasks.Add(e);
ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>();
ILogger<SettingsTest> logger1 = loggerFactory.CreateLogger<SettingsTest>();
using (logger1.BeginScope("SCOPE"))
{
logger1.LogTrace("This is a nice logger.");
using (logger1.BeginScope("NESTED SCOPE"))
{
logger1.LogInformation("This is a smart logger.");
// changing switch and scopes inclusion
configJson =
$@"{{
""{FileLoggerProvider.Alias}"": {{
""{nameof(FileLoggerOptions.Files)}"": [
{{
""{nameof(LogFileOptions.Path)}"": ""test.log"",
}}],
""{nameof(LoggerFilterRule.LogLevel)}"": {{
""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.Information}""
}}
}}
}}";
replacedert.Equal(0, resetTasks.Count);
fileProvider.WriteContent("config.json", configJson);
// reload is triggered twice due to a bug in the framework (https://github.com/aspnet/Logging/issues/874)
replacedert.Equal(1 * 2, resetTasks.Count);
// ensuring that reset has been finished and the new settings are effective
await Task.WhenAll(resetTasks);
logger1 = loggerFactory.CreateLogger<SettingsTest>();
logger1.LogInformation("This one shouldn't include scopes.");
logger1.LogTrace("This one shouldn't be included at all.");
}
}
completeCts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
var logFile = (MemoryFileInfo)fileProvider.GetFileInfo("test.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[]
{
$"trce: {typeof(SettingsTest).FullName}[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" => SCOPE",
$" This is a nice logger.",
$"info: {typeof(SettingsTest).FullName}[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" => SCOPE => NESTED SCOPE",
$" This is a smart logger.",
$"info: {typeof(SettingsTest).FullName}[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This one shouldn't include scopes.",
""
}, lines);
}
19
Source : SettingsTest.cs
with MIT License
from adams85
with MIT License
from adams85
[Fact]
public async Task ReloadOptionsSettingsMultipleProviders()
{
var fileProvider = new MemoryFileProvider();
var fileAppender = new MemoryFileAppender(fileProvider);
dynamic settings = new JObject();
dynamic globalFilters = settings[nameof(LoggerFilterRule.LogLevel)] = new JObject();
globalFilters[LogFileOptions.DefaultCategoryName] = LogLevel.None.ToString();
settings[FileLoggerProvider.Alias] = new JObject();
dynamic fileFilters = settings[FileLoggerProvider.Alias][nameof(LoggerFilterRule.LogLevel)] = new JObject();
fileFilters[LogFileOptions.DefaultCategoryName] = LogLevel.Warning.ToString();
dynamic oneFile = new JObject();
oneFile.Path = "one.log";
settings[FileLoggerProvider.Alias][nameof(FileLoggerOptions.Files)] = new JArray(oneFile);
settings[OtherFileLoggerProvider.Alias] = new JObject();
dynamic otherFileFilters = settings[OtherFileLoggerProvider.Alias][nameof(LoggerFilterRule.LogLevel)] = new JObject();
otherFileFilters[LogFileOptions.DefaultCategoryName] = LogLevel.Information.ToString();
dynamic otherFile = new JObject();
otherFile.Path = "other.log";
settings[OtherFileLoggerProvider.Alias][nameof(FileLoggerOptions.Files)] = new JArray(otherFile);
var configJson = ((JObject)settings).ToString();
fileProvider.CreateFile("config.json", configJson);
IConfigurationRoot config = new ConfigurationBuilder()
.AddJsonFile(fileProvider, "config.json", optional: false, reloadOnChange: true)
.Build();
var context = new TestFileLoggerContext(default, completionTimeout: Timeout.InfiniteTimeSpan);
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(lb =>
{
lb.AddConfiguration(config);
lb.AddFile(context, o => o.FileAppender ??= fileAppender);
lb.AddFile<OtherFileLoggerProvider>(context, o => o.FileAppender ??= fileAppender);
});
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(2, providers.Length);
var resetTasks = new List<Task>();
foreach (FileLoggerProvider provider in providers)
provider.Reset += (s, e) => resetTasks.Add(e);
ILoggerFactory loggerFactory = sp.GetRequiredService<ILoggerFactory>();
ILogger logger = loggerFactory.CreateLogger("X");
logger.LogInformation("This is an info.");
logger.LogWarning("This is a warning.");
fileFilters[LogFileOptions.DefaultCategoryName] = LogLevel.Information.ToString();
otherFileFilters[LogFileOptions.DefaultCategoryName] = LogLevel.Warning.ToString();
configJson = ((JObject)settings).ToString();
replacedert.Equal(0, resetTasks.Count);
fileProvider.WriteContent("config.json", configJson);
// reload is triggered twice due to a bug in the framework (https://github.com/aspnet/Logging/issues/874)
replacedert.Equal(2 * 2, resetTasks.Count);
// ensuring that reset has been finished and the new settings are effective
await Task.WhenAll(resetTasks);
logger.LogInformation("This is another info.");
logger.LogWarning("This is another warning.");
}
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
var logFile = (MemoryFileInfo)fileProvider.GetFileInfo((string)oneFile.Path);
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[]
{
$"warn: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a warning.",
$"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is another info.",
$"warn: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is another warning.",
""
}, lines);
logFile = (MemoryFileInfo)fileProvider.GetFileInfo((string)otherFile.Path);
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[]
{
$"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is an info.",
$"warn: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a warning.",
$"warn: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is another warning.",
""
}, lines);
}
19
Source : LoggingTest.cs
with MIT License
from adams85
with MIT License
from 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
Source : LoggingTest.cs
with MIT License
from adams85
with MIT License
from adams85
[Fact]
public async Task LoggingToPhysicalUsingDIAndExpectingDiagnosticEvents()
{
var logsDirName = Guid.NewGuid().ToString("D");
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 diagnosticEvents = new List<IFileLoggerDiagnosticEvent>();
context.DiagnosticEvent += diagnosticEvents.Add;
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context, o =>
{
o.FileAppender = new PhysicalFileAppender(fileProvider);
o.BasePath = logsDirName;
o.FileAccessMode = LogFileAccessMode.KeepOpen;
o.Files = new[]
{
new LogFileOptions
{
Path = "<invalid_filename>.log"
}
};
}));
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
try
{
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.");
logger1.LogWarning(1, "This is a smart logger.");
cts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
replacedert.NotEmpty(diagnosticEvents);
replacedert.All(diagnosticEvents, e =>
{
replacedert.IsType<FileLoggerDiagnosticEvent.LogEntryWriteFailed>(e);
replacedert.IsType<FileLoggerProcessor>(e.Source);
replacedert.NotNull(e.FormattableMessage);
replacedert.NotNull(e.Exception);
});
}
finally
{
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
}
}
19
Source : LoggingTest.cs
with MIT License
from adams85
with MIT License
from adams85
[Fact]
public async Task LoggingToMemoryUsingCustomPathPlaceholderResolver()
{
const string appName = "myapp";
const string logsDirName = "Logs";
var fileProvider = new MemoryFileProvider();
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 services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context, o =>
{
o.FileAppender = new MemoryFileAppender(fileProvider);
o.BasePath = logsDirName;
o.Files = new[]
{
new LogFileOptions
{
Path = "<appname>-<counter:000>.log"
}
};
o.PathPlaceholderResolver = (placeholderName, inlineFormat, context) => placeholderName == "appname" ? appName : null;
}));
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.");
logger1.LogWarning(1, "This is a smart logger.");
cts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
var logFile = (MemoryFileInfo)fileProvider.GetFileInfo($"{logsDirName}/{appName}-000.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
}
19
Source : Validate.cs
with MIT License
from adospace
with MIT License
from adospace
public static void All(bool[] arrayOfValidations, [NotNull] string parameterName,
[CanBeNull] string field = null)
{
if (!arrayOfValidations.All(_ => _))
throw new ArgumentException("Parameter is not valid",
parameterName + (field == null ? string.Empty : "." + field));
}
19
Source : CrmPasswordValidator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override Task<IdenreplacedyResult> ValidateAsync(string item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(item) || item.Length < RequiredLength)
{
errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordTooShort(RequiredLength)));
}
var failsRequireNonLetterOrDigit = item.All(IsLetterOrDigit);
if (RequireNonLetterOrDigit && failsRequireNonLetterOrDigit)
{
errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresNonLetterAndDigit()));
}
var failsRequireDigit = item.All(c => !IsDigit(c));
if (RequireDigit && failsRequireDigit)
{
errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresDigit()));
}
var failsRequireLowercase = item.All(c => !IsLower(c));
if (RequireLowercase && failsRequireLowercase)
{
errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresLower()));
}
var failsRequireUppercase = item.All(c => !IsUpper(c));
if (RequireUppercase && failsRequireUppercase)
{
errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresUpper()));
}
var preplacedes = new[] { !failsRequireNonLetterOrDigit, !failsRequireDigit, !failsRequireLowercase, !failsRequireUppercase };
var preplacedCount = preplacedes.Count(preplaced => preplaced);
if (EnforcePreplacedwordPolicy && preplacedCount < 3)
{
errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresThreeClreplacedes()));
}
if (errors.Count == 0)
{
return Task.FromResult(IdenreplacedyResult.Success);
}
return Task.FromResult(IdenreplacedyResult.Failed(string.Join(" ", errors)));
}
19
Source : ContentMapProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<EnreplacedyReference> RetrieveDisreplacedociatedIntersectEnreplacedies(CrmDbContext context, ContentMap map, EnreplacedyReference target, Relationship relationship, IEnumerable<EnreplacedyReference> relatedEnreplacedies)
{
var solution = map.Solution;
// retrieve the intersect enreplacedy definition
ManyRelationshipDefinition mrd;
EnreplacedyDefinition ed;
if (solution.ManyRelationships != null
&& solution.ManyRelationships.TryGetValue(relationship.SchemaName, out mrd)
&& solution.Enreplacedies.TryGetValue(mrd.IntersectEnreplacedyname, out ed))
{
// retrieve the target node
EnreplacedyNode targetNode;
if (map.TryGetValue(target, out targetNode))
{
// retrieve the set of existing relationships for validation purposes
var enreplacedies = RetrieveIntersectEnreplacedies(context, map, target, relationship, relatedEnreplacedies).Select(e => e.ToEnreplacedyReference()).ToList();
// reflexive N:N relationships are not supported
var targetRelationship = ed.Relationships.Single(r => r.ForeignEnreplacedyLogicalname == target.LogicalName && r.ToMany != null);
// retrieve the intersect nodes that point to the target
var intersects = targetRelationship.ToMany(targetNode).ToList();
foreach (var related in relatedEnreplacedies)
{
EnreplacedyNode relatedNode;
if (map.TryGetValue(related, out relatedNode))
{
var relatedRelationship = ed.Relationships.Single(r => r.ForeignEnreplacedyLogicalname == related.LogicalName && r.ToOne != null);
// filter the intersect nodes that point to the related node (as well as the target)
// ensure that the intersect does not exist in the collection of retrieved intersects
var intersectsToRemove = intersects
.Where(i => Equals(relatedRelationship.ToOne(i), relatedNode))
.Select(i => i.ToEnreplacedyReference())
.Where(i => enreplacedies.All(e => !Equals(e, i)));
foreach (var intersect in intersectsToRemove)
{
yield return intersect;
}
}
}
}
}
}
19
Source : CmsIndexHelper.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<Guid> SelectAllDescendantWebpagesWithPredicates(Guid enreplacedyId, ContentMap contentMap, IEnumerable<Predicate<WebPageNode>> predicates)
{
EnreplacedyNode enreplacedy;
if (!contentMap.TryGetValue(new EnreplacedyReference("adx_webpage", enreplacedyId), out enreplacedy))
{
return Enumerable.Empty<Guid>();
}
var rootWebpage = enreplacedy as WebPageNode;
if (rootWebpage == null)
{
return Enumerable.Empty<Guid>();
}
// if it's a content page, we want to start at it's root page so we can navigate down the web page hierarchy
if (rootWebpage.IsRoot == false)
{
if (rootWebpage.RootWebPage == null)
{
// just return this web page, can't reach any others
return new List<Guid>() { rootWebpage.Id };
}
rootWebpage = rootWebpage.RootWebPage;
}
var unprocessedNodes = new Queue<WebPageNode>();
var webPageGuids = new List<Guid>();
unprocessedNodes.Enqueue(rootWebpage);
while (unprocessedNodes.Count > 0)
{
WebPageNode currWebPage = unprocessedNodes.Dequeue();
foreach (var childWebPage in currWebPage.WebPages)
{
unprocessedNodes.Enqueue(childWebPage);
}
if (currWebPage.LanguageContentPages != null)
{
foreach (var contentPage in currWebPage.LanguageContentPages)
{
unprocessedNodes.Enqueue(contentPage);
}
}
if (predicates.All(predicate => predicate(currWebPage)))
{
webPageGuids.Add(currWebPage.Id);
}
}
return webPageGuids;
}
19
Source : ScopedIndexSearcher.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected override Query CreateQuery(ICrmEnreplacedyQuery query)
{
var scopeQuery = new BooleanQuery();
foreach (var scope in _scopes)
{
if (scope == null)
{
continue;
}
scopeQuery.Add(new TermQuery(new Term(Index.ScopeFieldName, scope)), Occur.SHOULD);
}
if (_scopes.All(x => x != Index.ScopeDefaultValue))
{
scopeQuery.Add(new TermQuery(new Term(Index.ScopeFieldName, Index.ScopeDefaultValue)), Occur.SHOULD);
}
var baseQuery = base.CreateQuery(query);
var compositeQuery = new BooleanQuery
{
{ baseQuery, Occur.MUST },
{ scopeQuery, Occur.MUST }
};
return compositeQuery;
}
19
Source : EnhancedTextBox.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
override protected void OnPreRender(EventArgs e)
{
// Ensure default work takes place
base.OnPreRender(e);
// Configure TextArea support
if ((TextMode == TextBoxMode.MultiLine) && (MaxLength > 0))
{
// If we haven't already, include the supporting
// script that limits the content of textareas.
foreach (var script in ScriptIncludes)
{
var scriptManager = ScriptManager.GetCurrent(Page);
if (scriptManager == null)
{
continue;
}
var absolutePath = VirtualPathUtility.ToAbsolute(script);
scriptManager.Scripts.Add(new ScriptReference(absolutePath));
}
// Add an expando attribute to the rendered control which sets its maximum length (using the MaxLength Attribute)
/* Where there is a ScriptManager on the parent page, use it to register the attribute -
* to ensure the control works in partial updates (like an AJAX UpdatePanel)*/
var current = ScriptManager.GetCurrent(Page);
if (current != null && (current.GetRegisteredExpandoAttributes().All(rea => rea.ControlId != ClientID)))
{
ScriptManager.RegisterExpandoAttribute(this, ClientID, _maxLengthAttributeName,
MaxLength.ToString(CultureInfo.InvariantCulture), true);
}
else
{
try
{
Page.ClientScript.RegisterExpandoAttribute(ClientID, _maxLengthAttributeName,
MaxLength.ToString(CultureInfo.InvariantCulture));
}
catch (ArgumentException)
{
// This occurs if a script with this key has already been registered. The response should be to do nothing.
}
}
// Now bind the onkeydown, oninput and onpaste events to script to inject in parent page.
Attributes.Add("onkeydown", "javascript:return LimitInput(this, event);");
Attributes.Add("oninput", "javascript:return LimitInput(this, event);");
Attributes.Add("onpaste", "javascript:return LimitPaste(this, event);");
}
}
19
Source : CrmEntitySecurityProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public virtual bool Tryreplacedert(OrganizationServiceContext context, IEnumerable<Enreplacedy> enreplacedies, CrmEnreplacedyRight right)
{
return enreplacedies.All(enreplacedy => Tryreplacedert(context, enreplacedy, right));
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static bool Detach(this OrganizationServiceContext context, IEnumerable<Enreplacedy> enreplacedies)
{
enreplacedies.ThrowOnNull("enreplacedies");
var results = enreplacedies.Select(context.Detach);
return results.All(result => result);
}
19
Source : CompositeCrmSiteMapNodeValidator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public bool Validate(OrganizationServiceContext context, CrmSiteMapNode node)
{
return _validators.All(validator => validator.Validate(context, node));
}
19
Source : ChatAuthController.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
[AllowAnonymous]
public ActionResult Authorize(string response_type, string client_id, string redirect_uri, string scope,
string state, string nonce)
{
if (string.IsNullOrEmpty(response_type) ||
response_type.Split(' ')
.All(s => string.Compare("token", s, StringComparison.InvariantCultureIgnoreCase) != 0))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (this.HttpContext.User.Idenreplacedy.IsAuthenticated)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Authenticated User, returning token");
var claims = this.GetUserClaims();
if (!string.IsNullOrEmpty(nonce))
{
claims.Add(new Claim("nonce", nonce));
}
var token = GetTokenString(claims);
var url = new UriBuilder(redirect_uri);
var qs = !string.IsNullOrEmpty(url.Query) && url.Query.Length > 1 ? url.Query.Substring(1) + "&" : string.Empty;
qs += "token=" + token; // token is already encoded
url.Query = qs;
return this.Redirect(url.ToString());
}
else
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Unauthenticated User, triggering authentication");
var urlState = EncodeState(Request.Url.AbsoluteUri);
var url = Url.Action("AuthForce", new { state = urlState });
return this.Redirect(url);
}
}
19
Source : EntityGridController.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<DisabledItemActionLink> AddActionLinkToDisabledActionLinksList(OrganizationServiceContext context, EnreplacedyMetadata enreplacedyMetadata, ViewActionLink link, EnreplacedyRecord[] records)
{
var disabledLinks = new List<DisabledItemActionLink>();
if (string.IsNullOrEmpty(link.FilterCriteria) || records == null || !records.Any())
{
return disabledLinks;
}
// Get Enreplacedy Record IDs for filter.
var ids = records.Select(record => record.Id).Cast<object>().ToList();
// The condition for the filter on primary key
var primaryAttributeCondition = new Condition
{
Attribute = enreplacedyMetadata.PrimaryIdAttribute,
Operator = ConditionOperator.In,
Values = ids
};
// Primary key filter
var primaryAttributeFilter = new Filter
{
Conditions = new[] { primaryAttributeCondition },
Type = LogicalOperator.And
};
Fetch fetch = null;
try
{
fetch = Fetch.Parse(link.FilterCriteria);
}
catch (Exception ex)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, ex.Message);
return disabledLinks;
}
if (fetch.Enreplacedy == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Fetch XML query is not valid. Enreplacedy can't be Null.");
return disabledLinks;
}
// Set number of fields to fetch to 0.
fetch.Enreplacedy.Attributes = FetchAttribute.None;
if (fetch.Enreplacedy.Filters == null)
{
fetch.Enreplacedy.Filters = new List<Filter>();
}
// Add primary key filter
fetch.Enreplacedy.Filters.Add(primaryAttributeFilter);
RetrieveMultipleResponse response;
try
{
response = (RetrieveMultipleResponse)context.Execute(new RetrieveMultipleRequest { Query = fetch.ToFetchExpression() });
}
catch (Exception ex)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, ex.Message);
return disabledLinks;
}
if (response == null)
{
return disabledLinks;
}
disabledLinks.AddRange(from record in records
where response.EnreplacedyCollection.Enreplacedies.All(enreplacedy => enreplacedy.Id != record.Id)
select new DisabledItemActionLink(record.Id, link.FilterCriteriaId));
return disabledLinks;
}
19
Source : EntityGridController.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static EnreplacedyRecord[] FilterWebsiteRelatedRecords(EnreplacedyRecord[] records, EnreplacedyReference website)
{
if (website == null || records.All(r => r.EnreplacedyName != "adx_portallanguage"))
{
return records;
}
return records
.Where(r => r.Attributes.Any(a => a.Name.Contains("adx_websiteid") && ((EnreplacedyReference)a.Value).Id == website.Id))
.ToArray();
}
19
Source : FieldDeclarationVisitor.cs
with MIT License
from adrianoc
with MIT License
from adrianoc
private string ProcessRequiredModifiers(MemberDeclarationSyntax member, IReadOnlyList<SyntaxToken> modifiers, string originalType)
{
if (modifiers.All(m => m.Kind() != SyntaxKind.VolatileKeyword))
return null;
var id = Context.Naming.RequiredModifier(member);
var mod_req = $"var {id} = new RequiredModifierType({ImportExpressionForType(typeof(IsVolatile))}, {originalType});";
AddCecilExpression(mod_req);
return id;
}
19
Source : AnarchyExtensions.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public static bool IsAny<T>(this IEnumerable<T> me, Func<T, bool> state) => me != null && me.All(state);
19
Source : AnarchyExtensions.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public static bool IsNullOrWhiteSpace(this string s) => string.IsNullOrEmpty(s) || s.All(c => c == ' ');
19
Source : TokenContract_Helper.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private void replacedertValidSymbolAndAmount(string symbol, long amount)
{
replacedert(!string.IsNullOrEmpty(symbol) && symbol.All(IsValidSymbolChar),
"Invalid symbol.");
replacedert(amount > 0, "Invalid amount.");
}
19
Source : TokenConverterContract.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private static bool IsValidSymbol(string symbol)
{
return symbol.Length > 0 &&
symbol.All(c => c >= 'A' && c <= 'Z');
}
19
Source : CrossChainCommunicationTestHelper.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public bool TryGetHeightByHash(Hash hash, out long height)
{
height = 0;
var dict = CreateDict();
if (dict.All(kv => kv.Value != hash)) return false;
height = dict.First(kv => kv.Value == hash).Key;
return true;
}
19
Source : PlatformManager.cs
with GNU General Public License v3.0
from affederaffe
with GNU General Public License v3.0
from affederaffe
private async Task LoadPlatformsAsync()
{
Stopwatch sw = Stopwatch.StartNew();
CancellationToken cancellationToken = _cancellationTokenSource.Token;
if (File.Exists(_cacheFilePath))
{
foreach (CustomPlatform platform in EnumeratePlatformDescriptorsFromFile())
AllPlatforms.AddSorted(1, AllPlatforms.Count - 1, platform);
}
// Load all remaining platforms, or all if no cache file is found
foreach (string path in Directory.EnumerateFiles(DirectoryPath, "*.plat").Where(x => AllPlatforms.All(y => y.fullPath != x)))
{
if (cancellationToken.IsCancellationRequested) return;
CustomPlatform? platform = await CreatePlatformAsync(path);
if (platform is null) continue;
AllPlatforms.AddSorted(1, AllPlatforms.Count - 1, platform);
}
sw.Stop();
_siraLog.Info($"Loaded {AllPlatforms.Count.ToString(NumberFormatInfo.InvariantInfo)} platforms in {sw.ElapsedMilliseconds.ToString(NumberFormatInfo.InvariantInfo)}ms");
}
19
Source : PredicateConvert.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private string Convert(MemberExpression expression)
{
if (expression.Expression is ParameterExpression)
{
if (this._columns.All(p => p != expression.Member.Name))
{
throw new ArgumentException(@"�ֶβ����������ݿ���", expression.Member.Name);
}
return string.Format("[{0}]", expression.Member.Name);
}
var par1 = expression.Expression as MemberExpression;
if (par1 != null && par1.Expression is ParameterExpression)
{
if (par1.Type == typeof(string))
{
switch (expression.Member.Name)
{
case "Length":
return string.Format("length([{0}])", par1.Member.Name);
}
}
if (par1.Type == typeof(DateTime))
{
switch (expression.Member.Name)
{
case "Now":
return string.Format("datetime('now')");
case "Today":
return string.Format("date('now')");
case "Date":
return string.Format("date([{0}])", par1.Member.Name);
case "TimeOfDay":
return string.Format("time([{0}])", par1.Member.Name);
case "Day":
return string.Format("strftime('%d',[{0}])", par1.Member.Name);
case "Month":
return string.Format("strftime('%m',[{0}])", par1.Member.Name);
case "Year":
return string.Format("strftime('%Y',[{0}])", par1.Member.Name);
case "Hour":
return string.Format("strftime('%H',[{0}])", par1.Member.Name);
case "Minute":
return string.Format("strftime('%M',[{0}])", par1.Member.Name);
case "Second":
return string.Format("strftime('%S',[{0}])", par1.Member.Name);
case "Kind":
return string.Format("strftime('%s',[{0}])", par1.Member.Name);
}
}
throw new ArgumentException("��֧�ֵ���չ����");
}
var name = this.ConditionItem.AddParameter(GetValue(expression));
return string.Format("${0}", name);
}
19
Source : Context.cs
with MIT License
from AgathokakologicalBit
with MIT License
from AgathokakologicalBit
public bool DeepEquals(Context c, long visitId)
{
if (LastVisitedAt == visitId)
return true;
LastVisitedAt = visitId;
if (this == c)
return true;
if (Values.Count != c?.Values.Count)
return false;
return Values.All(v => c.Values.ContainsKey(v.Key) && v.Value.DeepEquals(c.Values[v.Key], visitId))
&& ((Parent == c.Parent) || (Parent?.DeepEquals(c.Parent, visitId) ?? false));
}
19
Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static void RegisterUpdateHandler(IDataTrigger handler)
{
lock (_generalTriggers)
{
if (_generalTriggers.All(p => p.GetType() != handler.GetType()))
_generalTriggers.Add(handler);
}
}
19
Source : DataUpdateHandler.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static void RegisterUpdateHandler(int enreplacedyId, IDataUpdateTrigger handler)
{
lock (Triggers)
{
if (Triggers == null)
Triggers = new Dictionary<int, List<IDataUpdateTrigger>>();
if (!Triggers.ContainsKey(enreplacedyId))
Triggers.Add(enreplacedyId, new List<IDataUpdateTrigger> {handler});
else
{
if (Triggers[enreplacedyId].All(p => p.GetType() != handler.GetType()))
Triggers[enreplacedyId].Add(handler);
}
}
}
19
Source : EnumExtend.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static bool Equals(this Enum source, params Enum[] values)
{
return values.All(source.Equals);
}
19
Source : EnumExtend.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static bool HasFlags(this Enum source, params Enum[] values)
{
return values.All(source.HasFlag);
}
19
Source : GrpcChannelManagerTest.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
[Test]
public void TestOnError()
{
var channelManager = new GrpcChannelManager(new string[] { "randomhost" }, TimeSpan.FromMilliseconds(10), maxRetry: 3);
var callInvoker = channelManager.GetCallInvoker();
var client = new SampleApi.SampleApiClient(callInvoker);
var attemptList = new List<int>();
var errorList = new List<Exception>();
channelManager.OnError += (obj, args) =>
{
attemptList.Add(args.AttemptCount);
errorList.Add(args.Error);
};
replacedert.Throws<RpcException>(() => client.SampleRpcMethod(new SampleRequest() { Payload = "" }));
replacedert.AreEqual(attemptList, new List<int>() { 1, 2, 3 });
replacedert.IsTrue(errorList.All(e => e is RpcException));
}
19
Source : GrpcChannelManagerTest.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
[Test]
public void TestOnErrorAsync()
{
var channelManager = new GrpcChannelManager(new string[] { "randomhost" }, TimeSpan.FromMilliseconds(10), maxRetry: 3);
var callInvoker = channelManager.GetCallInvoker();
var client = new SampleApi.SampleApiClient(callInvoker);
var attemptList = new List<int>();
var errorList = new List<Exception>();
channelManager.OnError += (obj, args) =>
{
attemptList.Add(args.AttemptCount);
errorList.Add(args.Error);
};
replacedert.ThrowsAsync<RpcException>(async () => await client.SampleRpcMethodAsync(new SampleRequest() { Payload = "" }));
replacedert.AreEqual(attemptList, new List<int>() { 1, 2, 3 });
replacedert.IsTrue(errorList.All(e => e is RpcException));
}
19
Source : ContainerAttributeUtils.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
private static bool IsRationalForRegistration(Type type)
{
return ExcludedreplacedemblyNamePrefixes.All(prefix => !type.replacedembly.FullName.StartsWith(prefix));
}
See More Examples