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 : DefaultSelectedValueComponentShould.cs
with GNU General Public License v3.0
from agolaszewski
with GNU General Public License v3.0
from agolaszewski
[Fact]
public void Has_Default_Value()
{
_fixture.Default.HasDefault.ShouldBeTrue();
_fixture.Colors.Where(x => x.Item == ConsoleColor.Red).First().IsSelected.ShouldBeTrue();
_fixture.Colors.Where(x => x.Item == ConsoleColor.Yellow).First().IsSelected.ShouldBeTrue();
_fixture.Colors.Where(x => x.Item != ConsoleColor.Red || x.Item != ConsoleColor.Yellow).All(x => x.IsSelected == false);
_fixture.Colors.Where(x => x.IsSelected).Count().ShouldEqual(2);
}
19
Source : UniqueValidator.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public override bool IsValid(ValidationContext<T> context, string value)
{
var editedItem = context.InstanceToValidate;
var propertyName = context.PropertyName;
propertyName = propertyName.Substring(propertyName.LastIndexOf('.') + 1);
var property = typeof(T).GetTypeInfo().GetProperty(propertyName);
return _items.All(item =>
item.Equals(editedItem) || property.GetValue(item) as string != value);
}
19
Source : ExternalLogins.cshtml.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
CurrentLogins = await _userManager.GetLoginsAsync(user);
OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
.Where(auth => CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
.ToList();
ShowRemoveButton = user.PreplacedwordHash != null || CurrentLogins.Count > 1;
return Page();
}
19
Source : AuthManager.cs
with MIT License
from ahmet-cetinkaya
with MIT License
from ahmet-cetinkaya
[SecuredOperation("user")]
public IResult IsAuthenticated(string userMail, List<string> requiredRoles)
{
if (requiredRoles != null)
{
var user = _userService.GetByMail(userMail).Data;
var userClaims = _userService.GetClaims(user).Data;
var doesUserHaveRequiredRoles =
requiredRoles.All(role => userClaims.Select(userClaim => userClaim.Name).Contains(role));
if (!doesUserHaveRequiredRoles) return new ErrorResult(Messages.AuthorizationDenied);
}
return new SuccessResult();
}
19
Source : Wallet.cs
with Apache License 2.0
from ajuna-network
with Apache License 2.0
from ajuna-network
public bool IsValidWalletName(string walletName)
{
return walletName.Length > 4 && walletName.Length < 21 &&
walletName.All(c => char.IsLetterOrDigit(c) || c.Equals('_'));
}
19
Source : JsonSerializerInternalReader.cs
with MIT License
from akaskela
with MIT License
from akaskela
private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor<object> creator, string id)
{
ValidationUtils.ArgumentNotNull(creator, nameof(creator));
// only need to keep a track of properies presence if they are required or a value should be defaulted if missing
bool trackPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate));
Type objectType = contract.UnderlyingType;
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
string parameters = string.Join(", ", contract.CreatorParameters.Select(p => p.PropertyName).ToArray());
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using creator with parameters: {1}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType, parameters)), null);
}
List<CreatorPropertyContext> propertyContexts = ResolvePropertyAndCreatorValues(contract, containerProperty, reader, objectType);
if (trackPresence)
{
foreach (JsonProperty property in contract.Properties)
{
if (propertyContexts.All(p => p.Property != property))
{
propertyContexts.Add(new CreatorPropertyContext
{
Property = property,
Name = property.PropertyName,
Presence = PropertyPresence.None
});
}
}
}
object[] creatorParameterValues = new object[contract.CreatorParameters.Count];
foreach (CreatorPropertyContext context in propertyContexts)
{
// set presence of read values
if (trackPresence)
{
if (context.Property != null && context.Presence == null)
{
object v = context.Value;
PropertyPresence propertyPresence;
if (v == null)
{
propertyPresence = PropertyPresence.Null;
}
else if (v is string)
{
propertyPresence = CoerceEmptyStringToNull(context.Property.PropertyType, context.Property.PropertyContract, (string)v)
? PropertyPresence.Null
: PropertyPresence.Value;
}
else
{
propertyPresence = PropertyPresence.Value;
}
context.Presence = propertyPresence;
}
}
JsonProperty constructorProperty = context.ConstructorProperty;
if (constructorProperty == null && context.Property != null)
{
constructorProperty = contract.CreatorParameters.ForgivingCaseSensitiveFind(p => p.PropertyName, context.Property.UnderlyingName);
}
if (constructorProperty != null && !constructorProperty.Ignored)
{
// handle giving default values to creator parameters
// this needs to happen before the call to creator
if (trackPresence)
{
if (context.Presence == PropertyPresence.None || context.Presence == PropertyPresence.Null)
{
if (constructorProperty.PropertyContract == null)
{
constructorProperty.PropertyContract = GetContractSafe(constructorProperty.PropertyType);
}
if (HasFlag(constructorProperty.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate))
{
context.Value = EnsureType(
reader,
constructorProperty.GetResolvedDefaultValue(),
CultureInfo.InvariantCulture,
constructorProperty.PropertyContract,
constructorProperty.PropertyType);
}
}
}
int i = contract.CreatorParameters.IndexOf(constructorProperty);
creatorParameterValues[i] = context.Value;
context.Used = true;
}
}
object createdObject = creator(creatorParameterValues);
if (id != null)
{
AddReference(reader, id, createdObject);
}
OnDeserializing(reader, contract, createdObject);
// go through unused values and set the newly created object's properties
foreach (CreatorPropertyContext context in propertyContexts)
{
if (context.Used ||
context.Property == null ||
context.Property.Ignored ||
context.Presence == PropertyPresence.None)
{
continue;
}
JsonProperty property = context.Property;
object value = context.Value;
if (ShouldSetPropertyValue(property, value))
{
property.ValueProvider.SetValue(createdObject, value);
context.Used = true;
}
else if (!property.Writable && value != null)
{
// handle readonly collection/dictionary properties
JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
if (propertyContract.ContractType == JsonContractType.Array)
{
JsonArrayContract propertyArrayContract = (JsonArrayContract)propertyContract;
object createdObjectCollection = property.ValueProvider.GetValue(createdObject);
if (createdObjectCollection != null)
{
IWrappedCollection createdObjectCollectionWrapper = propertyArrayContract.CreateWrapper(createdObjectCollection);
IWrappedCollection newValues = propertyArrayContract.CreateWrapper(value);
foreach (object newValue in newValues)
{
createdObjectCollectionWrapper.Add(newValue);
}
}
}
else if (propertyContract.ContractType == JsonContractType.Dictionary)
{
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)propertyContract;
object createdObjectDictionary = property.ValueProvider.GetValue(createdObject);
if (createdObjectDictionary != null)
{
IDictionary targetDictionary = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(createdObjectDictionary) : (IDictionary)createdObjectDictionary;
IDictionary newValues = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(value) : (IDictionary)value;
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = newValues.GetEnumerator();
try
{
while (e.MoveNext())
{
DictionaryEntry entry = e.Entry;
targetDictionary.Add(entry.Key, entry.Value);
}
}
finally
{
(e as IDisposable)?.Dispose();
}
}
}
context.Used = true;
}
}
if (contract.ExtensionDataSetter != null)
{
foreach (CreatorPropertyContext propertyValue in propertyContexts)
{
if (!propertyValue.Used)
{
contract.ExtensionDataSetter(createdObject, propertyValue.Name, propertyValue.Value);
}
}
}
if (trackPresence)
{
foreach (CreatorPropertyContext context in propertyContexts)
{
if (context.Property == null)
{
continue;
}
EndProcessProperty(
createdObject,
reader,
contract,
reader.Depth,
context.Property,
context.Presence.GetValueOrDefault(),
!context.Used);
}
}
OnDeserialized(reader, contract, createdObject);
return createdObject;
}
19
Source : MainWindow.xaml.cs
with MIT License
from AkiniKites
with MIT License
from AkiniKites
private async Task btnPatch_Click(object sender, EventArgs e)
{
using var _ = new ControlLock(btnPatch);
IoC.Notif.ShowStatus("Generating patch...");
IoC.Notif.ShowUnknownProgress();
if (Plugins.Any() && !Plugins.All(x => x.ValidateChanges()))
{
IoC.Notif.HideProgress();
IoC.Notif.ShowStatus("Pack install aborted");
return;
}
var sw = new Stopwatch(); sw.Start();
var success = await Async.Run(CreatePatch);
Settings.UpdatePatchStatus();
IoC.Notif.HideProgress();
if (success)
IoC.Notif.ShowStatus($"Patch installed ({sw.Elapsed.TotalMilliseconds:n0} ms)");
}
19
Source : Uncapsulator.cs
with MIT License
from albahari
with MIT License
from albahari
public override bool TryGetIndex (GetIndexBinder binder, object[] indexes, out object result)
{
if (WrapsNullInstance) ThrowNullException ($"invoke an indexer");
if (WrapsType) ThrowTargetException ($"invoke an indexer");
UnwrapArgs (indexes);
string newParent = _path + "[" + string.Join (",", indexes) + "]";
try
{
if (_type.IsArray && indexes.All (x => x is int))
result = new Uncapsulator (newParent, _options, ((Array)Value).GetValue (indexes.Select (x => (int)x).ToArray ()));
else
{
var indexer = SelectIndexer (indexes);
var returnValue = indexer.GetValue (Value, _instanceFlags, null, indexes, null);
result = new Uncapsulator (newParent, _options, returnValue, callSiteType: indexer.PropertyType);
}
}
catch (Exception ex)
{
throw new MemberAccessException ($"Unable to invoke get-indexer on type '{_type}' - {ex.Message}", ex).Wrap ();
}
return true;
}
19
Source : Uncapsulator.cs
with MIT License
from albahari
with MIT License
from albahari
public override bool TrySetIndex (SetIndexBinder binder, object[] indexes, object value)
{
if (WrapsNullInstance) ThrowNullException ($"invoke an indexer");
if (WrapsType) ThrowTargetException ($"invoke an indexer");
UnwrapArgs (indexes);
try
{
if (_type.IsArray && indexes.All (x => x is int))
((Array)Value).SetValue (value, indexes.Select (x => (int)x).ToArray ());
else
SelectIndexer (indexes, value?.GetType ()).SetValue (Value, value, _instanceFlags, null, indexes, null);
}
catch (Exception ex)
{
throw new MemberAccessException ($"Unable to invoke set-indexer on type '{_type}' - {ex.Message}", ex).Wrap ();
}
return true;
}
19
Source : Uncapsulator.cs
with MIT License
from albahari
with MIT License
from albahari
PropertyInfo SelectIndexer (object[] indexValues, Type returnType = null)
{
// Try first with interface type if present.
var match = _callSiteInterfaceType == null ? default : SelectIndexer (_callSiteInterfaceType, false);
if (match != null) return match;
return SelectIndexer (_type, true);
PropertyInfo SelectIndexer (Type type, bool throwIfNotFound)
{
var props = GetDefaultMembers (type)
.OfType<PropertyInfo> ()
.Where (p => p.GetIndexParameters ().Length == indexValues.Length)
.ToArray ();
if (props.Length == 0)
if (throwIfNotFound)
throw new MissingMemberException ($"There are no indexers on type {type}.").Wrap ();
else
return null;
if (indexValues.Any (x => x == null))
{
var eligibleProps = props.Where (i => i.GetIndexParameters ().All (p => !p.ParameterType.IsValueType)).ToArray ();
if (eligibleProps.Length == 1) return eligibleProps[0];
if (eligibleProps.Length > 1)
throw new AmbiguousMatchException ($"Call to indexer on '{_path}' is ambiguous because one or more arguments is null.").Wrap ();
else if (throwIfNotFound)
throw new MissingMemberException ($"Cannot find a compatible indexer on type '{type}'.").Wrap ();
else
return null;
}
var result = Type.DefaultBinder.SelectProperty (_defaultBindingFlags, props, returnType, indexValues.Select (i => i.GetType ()).ToArray (), null);
if (result == null && throwIfNotFound) throw new MissingMemberException ($"Cannot find a compatible indexer on type '{type}'.").Wrap ();
return result;
}
}
19
Source : UpdateChecker.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
private static bool IsUpdateNodeValid(XElement root)
{
return new string[] { "Name", "FileID", "DownloadLink", "Path" }.All(s => root.Elements().Select(x => x.Name.ToString()).Contains(s)) && root.Elements().All(s => !string.IsNullOrWhiteSpace(s.Value));
}
19
Source : SortInfo.cs
with MIT License
from albyho
with MIT License
from albyho
public static bool IsValid(this IEnumerable<SortInfo> sortInfos)
{
return sortInfos != null && sortInfos.All(m => m.IsValid());
}
19
Source : ToolbarView.cs
with MIT License
from alelievr
with MIT License
from alelievr
protected void HideButton(string name)
{
leftButtonDatas.Concat(rightButtonDatas).All(b => {
if (b?.content?.text == name)
b.visible = false;
return true;
});
}
19
Source : ToolbarView.cs
with MIT License
from alelievr
with MIT License
from alelievr
protected void ShowButton(string name)
{
leftButtonDatas.Concat(rightButtonDatas).All(b => {
if (b?.content?.text == name)
b.visible = true;
return true;
});
}
19
Source : BiomeSwitchGraph.cs
with MIT License
from alelievr
with MIT License
from alelievr
bool CheckValid()
{
var checkedCells = new List< BiomeSwitchCell >();
var currentCells = new Stack< BiomeSwitchCell >();
if (rootCell == null)
return false;
currentCells.Push(rootCell);
while (currentCells.Count > 0)
{
var currentCell = currentCells.Pop();
if (!checkedCells.Contains(currentCell))
checkedCells.Add(currentCell);
foreach (var link in currentCell.links)
if (!checkedCells.Contains(link))
currentCells.Push(link);
}
//if all graph cells are contained in the checkedCell list then it's good
if (cells.All(cell => checkedCells.Contains(cell)))
return true;
return false;
}
19
Source : GraphBuilderTests.cs
with MIT License
from alelievr
with MIT License
from alelievr
static bool ScrambledEqual(IEnumerable< Anchor > anchorList1, IEnumerable< Anchor > anchorList2)
{
return anchorList1.All(a1 => anchorList2.Contains(a1));
}
19
Source : AnchorField.cs
with MIT License
from alelievr
with MIT License
from alelievr
public void UpdateAnchors()
{
//if this anchor field is a multiple input, check if all our anchors are linked
// and if so, add a new one
if (multiple && anchorType == AnchorType.Input)
{
if (anchors.All(a => a.linkCount > 0))
CreateNewAnchor();
//if there are more than 1 unlinked anchor, delete the others:
if (anchors.Count(a => a.linkCount == 0) > 1)
RemoveDuplicatedUnlinkedAnchors();
}
}
19
Source : BiomeSurfaceGraph.cs
with MIT License
from alelievr
with MIT License
from alelievr
bool CheckValid()
{
List< BiomeSurfaceCell > checkedCells = new List< BiomeSurfaceCell >();
Stack< BiomeSurfaceCell > currentCells = new Stack< BiomeSurfaceCell >();
currentCells.Push(rootCell);
while (currentCells.Count > 0)
{
var currentCell = currentCells.Pop();
if (!checkedCells.Contains(currentCell))
checkedCells.Add(currentCell);
foreach (var link in currentCell.links)
if (!checkedCells.Contains(link.toCell))
currentCells.Push(link.toCell);
}
//if all graph cells are contained in the checkedCell list then it's good
if (cells.All(cell => checkedCells.Contains(cell)))
return true;
return false;
}
19
Source : TypeFilter.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
public bool Try(VectorFeatureUnity feature)
{
switch (Type)
{
case LayerFilterCombinerOperationType.Any:
return Filters.Any(m => m.Try(feature));
case LayerFilterCombinerOperationType.All:
return Filters.All(m => m.Try(feature));
case LayerFilterCombinerOperationType.None:
return !Filters.Any(m => m.Try(feature));
default:
return false;
}
}
19
Source : DbSchema.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public CodeToDataBaseMergeCollection GetDatabase_Diff(Type tableType, CodeToDataBaseMergeCollection str = null, List<Type> createdTables = null)
{
str = str ?? new CodeToDataBaseMergeCollection(_repository);
if (tableType.GetCustomAttribute<ExcludeFromAbstract>() != null || _alreadyControlled.Any(x => x == tableType))
return str;
_repository.CreateSchema(tableType);
tableType = tableType.GetActualType();
_alreadyControlled.Add(tableType);
createdTables = createdTables ?? new List<Type>();
if (createdTables.Any(x => x == tableType) || tableType.GetPrimaryKey() == null)
return str;
if (CodeToDataBaseMergeCollection.ExecutedData.ContainsKey(tableType.FullName + _repository.DataBaseTypes.ToString()))
return str;
createdTables.Add(tableType);
var table = _repository.GetColumnSchema(tableType);
var tableName = tableType.TableName();
var props = DeepCloner.GetFastDeepClonerProperties(tableType).Where(x => x.CanRead && !x.ContainAttribute<ExcludeFromAbstract>());
var codeToDataBaseMerge = new CodeToDataBaseMerge() { Object_Type = tableType };
var isPrimaryKey = "";
if (!IsValidName(tableName.Name))
throw new EnreplacedyException(tableName.Name + " is not a valid Name for the current provider " + _repository.DataBaseTypes);
if (!table.Values.Any())
{
codeToDataBaseMerge.Sql = new StringBuilder($"CREATE TABLE {tableName.GetName(_repository.DataBaseTypes)} (");
foreach (var prop in props.Where(x => (x.GetDbTypeByType(_repository.DataBaseTypes) != null || !x.IsInternalType ||
x.ContainAttribute<JsonDoreplacedent>() || x.ContainAttribute<XmlDoreplacedent>()) &&
!x.ContainAttribute<ExcludeFromAbstract>()).GroupBy(x => x.Name).Select(x => x.First())
.OrderBy(x => x.ContainAttribute<PrimaryKey>() ? null : x.Name))
{
if (!prop.IsInternalType && !prop.ContainAttribute<JsonDoreplacedent>() && !prop.ContainAttribute<XmlDoreplacedent>())
{
if (!str.Any(x => x.Object_Type == prop.PropertyType.GetActualType()) && createdTables.All(x => x != prop.PropertyType.GetActualType()))
GetDatabase_Diff(prop.PropertyType, str, createdTables);
continue;
}
isPrimaryKey = prop.ContainAttribute<PrimaryKey>() ? prop.GetPropertyName() : isPrimaryKey;
var foreignKey = prop.GetCustomAttribute<ForeignKey>();
var dbType = prop.GetDbTypeByType(_repository.DataBaseTypes);
var propName = string.Format("[{0}]", prop.GetPropertyName());
codeToDataBaseMerge.Sql.Append(propName + " ");
if (!IsValidName(prop.GetPropertyName()))
throw new Exception(prop.GetPropertyName() + " is not a valid Name for the current provider " + _repository.DataBaseTypes);
if (!prop.ContainAttribute<PrimaryKey>() || _repository.DataBaseTypes == DataBaseTypes.Mssql)
codeToDataBaseMerge.Sql.Append(dbType + " ");
if (foreignKey != null && createdTables.All(x => x != foreignKey.Type))
GetDatabase_Diff(foreignKey.Type, str, createdTables);
if (prop.ContainAttribute<PrimaryKey>())
{
if (prop.PropertyType.IsNumeric() && prop.GetCustomAttribute<PrimaryKey>().AutoGenerate)
codeToDataBaseMerge.Sql.Append(_repository.DataBaseTypes == DataBaseTypes.Mssql ? "IDENreplacedY(1,1) NOT NULL," : (_repository.DataBaseTypes == DataBaseTypes.Sqllight ? " Integer PRIMARY KEY AUTOINCREMENT," : " BIGSERIAL PRIMARY KEY,"));
else codeToDataBaseMerge.Sql.Append(_repository.DataBaseTypes == DataBaseTypes.Mssql ? "NOT NULL," : " " + dbType + " PRIMARY KEY,");
continue;
}
if (foreignKey != null)
{
var key = propName + "-" + tableName.GetName(_repository.DataBaseTypes);
if (!str.Keys.ContainsKey(key))
str.Keys.Add(key, new Tuple<string, ForeignKey>(tableName.GetName(_repository.DataBaseTypes), foreignKey));
}
codeToDataBaseMerge.Sql.Append((Nullable.GetUnderlyingType(prop.PropertyType) != null || prop.PropertyType == typeof(string)) && !prop.ContainAttribute<NotNullable>() ? " NULL," : " NOT NULL,");
}
if (str.Keys.Any() && _repository.DataBaseTypes == DataBaseTypes.Sqllight)
{
while (str.Keys.Any(x => x.Value.Item1 == tableName.Name))
{
var key = str.Keys.FirstOrDefault(x => x.Value.Item1 == tableName.Name);
var type = key.Value.Item2.Type.GetActualType();
var keyPrimary = type.GetPrimaryKey().GetPropertyName();
var tb = type.TableName();
codeToDataBaseMerge.Sql.Append("FOREIGN KEY(" + key.Key.Split('-')[0] + ") REFERENCES " + tb.GetName(_repository.DataBaseTypes) + "(" + keyPrimary + "),");
str.Keys.Remove(key.Key);
}
}
if (!string.IsNullOrEmpty(isPrimaryKey) && _repository.DataBaseTypes == DataBaseTypes.Mssql)
{
codeToDataBaseMerge.Sql.Append(" CONSTRAINT [PK_" + tableName.Name + "] PRIMARY KEY CLUSTERED");
codeToDataBaseMerge.Sql.Append(" ([" + isPrimaryKey + "] ASC");
codeToDataBaseMerge.Sql.Append(")");
codeToDataBaseMerge.Sql.Append("WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]");
codeToDataBaseMerge.Sql.Append(") ON [PRIMARY]");
}
else
{
if (_repository.DataBaseTypes == DataBaseTypes.Sqllight)
codeToDataBaseMerge.Sql = new StringBuilder(codeToDataBaseMerge.Sql.ToString().TrimEnd(','));
codeToDataBaseMerge.Sql.Append(")");
}
str.Add(codeToDataBaseMerge);
}
else
{
foreach (var prop in props.Where(x => (x.GetDbTypeByType(_repository.DataBaseTypes) != null || !x.IsInternalType) && !x.ContainAttribute<ExcludeFromAbstract>()).GroupBy(x => x.Name).Select(x => x.First())
.OrderBy(x => x.ContainAttribute<PrimaryKey>() ? null : x.Name))
{
if (prop.ContainAttribute<ForeignKey>())
GetDatabase_Diff(prop.GetCustomAttribute<ForeignKey>().Type, str, createdTables);
var propType = prop.PropertyType;
if (prop.ContainAttribute<Stringify>() ||
prop.ContainAttribute<DataEncode>() ||
prop.ContainAttribute<ToBase64String>() ||
prop.ContainAttribute<JsonDoreplacedent>() ||
prop.ContainAttribute<XmlDoreplacedent>())
propType = typeof(string);
var modify = prop.IsInternalType || prop.ContainAttribute<JsonDoreplacedent>() || prop.ContainAttribute<XmlDoreplacedent>() ? (_repository.DataBaseTypes == DataBaseTypes.PostgreSql ? table.Get(prop.GetPropertyName().ToLower()) : table.Get(prop.GetPropertyName())) : null;
if (modify != null)
{
if (_repository.DataBaseTypes != DataBaseTypes.Sqllight && !(prop.GetDbTypeListByType(_repository.DataBaseTypes).Any(x => x.ToLower().Contains(modify.DataType.ToLower()))) && _repository.DataBaseTypes != DataBaseTypes.PostgreSql)
{
var constraine = Properties.Resources.DropContraine
.Replace("@tb", $"'{tableName.Name}'").Replace("@col", $"'{prop.GetPropertyName()}'")
.Replace("@schema", $"'{tableName.Schema ?? ""}'")
.Replace("@TableName", "@" + counter++)
.Replace("@ColumnName", "@" + counter++)
.Replace("@fullName", "@" + counter++)
.Replace("@DROP_COMMAND", "@" + counter++)
.Replace("@FOREIGN_KEY_NAME", "@" + counter++);
codeToDataBaseMerge.Sql.Append(constraine);
codeToDataBaseMerge.Sql.Append($"\nALTER TABLE {tableName.GetName(_repository.DataBaseTypes)} ALTER COLUMN [{prop.GetPropertyName()}] {prop.GetDbTypeByType(_repository.DataBaseTypes)} {((Nullable.GetUnderlyingType(propType) != null || propType == typeof(string)) && !prop.ContainAttribute<NotNullable>() ? " NULL" : " NOT NULL")}");
}
else
{
if (!(prop.GetDbTypeListByType(_repository.DataBaseTypes).Any(x => x.ToLower().Contains(modify.DataType.ToLower()))) && _repository.DataBaseTypes == DataBaseTypes.PostgreSql)
codeToDataBaseMerge.Sql.Append($"\nALTER TABLE {tableName.GetName(_repository.DataBaseTypes)} ALTER COLUMN [{prop.GetPropertyName()}] TYPE {prop.GetDbTypeByType(_repository.DataBaseTypes)}, ALTER COLUMN [{prop.GetPropertyName()}] SET DEFAULT {Querys.GetValueByTypeSTRING(MethodHelper.ConvertValue(null, propType), _repository.DataBaseTypes)};");
}
}
else if (!prop.IsInternalType && !prop.ContainAttribute<JsonDoreplacedent>() && !prop.ContainAttribute<XmlDoreplacedent>())
GetDatabase_Diff(prop.PropertyType, str, createdTables);
else
{
codeToDataBaseMerge.Sql.Append(string.Format("\nALTER TABLE {0} ADD " + (_repository.DataBaseTypes == DataBaseTypes.PostgreSql ? "COLUMN" : "") + " [{1}] {2} {3} DEFAULT {4};", tableName.GetName(_repository.DataBaseTypes), prop.GetPropertyName(), prop.GetDbTypeByType(_repository.DataBaseTypes),
(Nullable.GetUnderlyingType(propType) != null || propType == typeof(string)) && !prop.ContainAttribute<NotNullable>() ? " NULL" : " NOT NULL", Querys.GetValueByTypeSTRING(MethodHelper.ConvertValue(null, propType), _repository.DataBaseTypes)));
}
}
}
var colRemove = new CodeToDataBaseMerge() { Object_Type = tableType };
// Now lets clean the table and remove unused columns
foreach (var col in table.Values.Where(x =>
!props.Any(a => string.Equals(x.ColumnName, a.GetPropertyName(), StringComparison.CurrentCultureIgnoreCase) &&
(a.GetDbTypeByType(_repository.DataBaseTypes) != null || (!a.IsInternalType || a.ContainAttribute<JsonDoreplacedent>() || a.ContainAttribute<XmlDoreplacedent>())) &&
!a.ContainAttribute<ExcludeFromAbstract>())))
{
if (_repository.DataBaseTypes != DataBaseTypes.Sqllight)
{
if (_repository.DataBaseTypes == DataBaseTypes.Mssql)
{
var constraine = Properties.Resources.DropContraine
.Replace("@tb", $"'{tableName.Name}'")
.Replace("@col", $"'{col.ColumnName}'")
.Replace("@schema", $"'{tableName.Schema ?? ""}'")
.Replace("@TableName", "@" + counter++)
.Replace("@ColumnName", "@" + counter++)
.Replace("@fullName", "@" + counter++)
.Replace("@DROP_COMMAND", "@" + counter++)
.Replace("@FOREIGN_KEY_NAME", "@" + counter++);
colRemove.Sql.Append(constraine);
}
colRemove.Sql.Append(string.Format("\nALTER TABLE {0} DROP COLUMN IF EXISTS [{1}];", tableName.GetName(_repository.DataBaseTypes), col.ColumnName));
}
else
{
colRemove.Sql.Append(string.Format("DROP TABLE IF exists [{0}_temp];\nCREATE TABLE [{0}_temp] AS SELECT {1} FROM [{0}];", tableName.Name, string.Join(",", table.Values.ToList().FindAll(x =>
props.Any(a => string.Equals(x.ColumnName, a.GetPropertyName(), StringComparison.CurrentCultureIgnoreCase) &&
(a.GetDbTypeByType(_repository.DataBaseTypes) != null || !a.IsInternalType) &&
!a.ContainAttribute<ExcludeFromAbstract>())).Select(x => x.ColumnName))));
colRemove.Sql.Append(string.Format("DROP TABLE [{0}];\n", tableName.Name));
colRemove.Sql.Append(string.Format("ALTER TABLE [{0}_temp] RENAME TO [{0}]; ", tableName.Name));
}
colRemove.DataLoss = true;
}
str.Add(colRemove);
foreach (var prop in props.Where(x => !x.IsInternalType && !x.ContainAttribute<JsonDoreplacedent>() && !x.ContainAttribute<XmlDoreplacedent>() && !x.ContainAttribute<XmlDoreplacedent>() && !x.ContainAttribute<ExcludeFromAbstract>()).GroupBy(x => x.Name).Select(x => x.First()))
{
var type = prop.PropertyType.GetActualType();
if (type.GetPrimaryKey() != null)
GetDatabase_Diff(type, str, createdTables);
}
str.Add(codeToDataBaseMerge);
return str;
}
19
Source : DbSchema.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public T LoadChildren<T>(T item, bool onlyFirstLevel = false, List<string> clreplacedes = null, List<string> ignoreList = null, Dictionary<string, List<string>> pathLoaded = null, string parentProb = null, string id = null)
{
if (pathLoaded == null)
pathLoaded = new Dictionary<string, List<string>>();
if (item == null)
return default(T);
GlobalConfiguration.Log?.Info("Loading Children for " + item.GetType() + "", item);
switch (item)
{
case IList _:
foreach (var replacedem in (IList)item)
{
var enreplacedy = replacedem;
if (enreplacedy == null)
continue;
LoadChildren(enreplacedy, onlyFirstLevel, clreplacedes, ignoreList, pathLoaded, parentProb, enreplacedy.GetPrimaryKeyValue().ConvertValue<string>());
}
break;
default:
if ((item) == null)
return item;
var props = DeepCloner.GetFastDeepClonerProperties(item.GetType());
id = item.GetPrimaryKeyValue().ToString();
foreach (var prop in props.Where(x => x.CanRead && !x.IsInternalType && !x.ContainAttribute<ExcludeFromAbstract>() && !x.ContainAttribute<JsonDoreplacedent>() && !x.ContainAttribute<XmlDoreplacedent>()))
{
var path = string.Format("{0}.{1}", parentProb ?? "", prop.Name).TrimEnd('.').TrimStart('.');
var propCorrectPathName = path?.Split('.').Length >= 2 ? string.Join(".", path.Split('.').Reverse().Take(2).Reverse()) : path;
if (clreplacedes != null && clreplacedes.All(x => x != propCorrectPathName))
continue;
if (ignoreList != null && ignoreList.Any(x => x == propCorrectPathName))
continue;
var propValue = prop.GetValue(item);
if (propValue != null)
if (!(propValue is IList) || (propValue as IList).Any())
continue;
if (pathLoaded.ContainsKey(id) && pathLoaded[id].Any(x => x == path))
continue;
if (!pathLoaded.ContainsKey(id))
pathLoaded.Add(id, new List<string>() { path });
else if (pathLoaded[id].All(x => x != path)) pathLoaded[id].Add(path);
var propertyName = prop.Name;
if (path?.Split('.').Length >= 2)
propertyName = string.Join(".", path.Split('.').Reverse().Take(3).Reverse()) + "." + parentProb.Split('.').Last() + "." + propertyName;
var type = prop.PropertyType.GetActualType();
var key = props.FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == type && (string.IsNullOrEmpty(x.GetCustomAttribute<ForeignKey>().PropertyName) || x.GetCustomAttribute<ForeignKey>().PropertyName == prop.Name));
if (key == null)
{
var column = DeepCloner.GetFastDeepClonerProperties(type).FirstOrDefault(x => x.GetCustomAttribute<ForeignKey>()?.Type == item.GetType() && string.IsNullOrEmpty(x.GetCustomAttribute<ForeignKey>().PropertyName));
var primaryKey = item.GetType().GetPrimaryKey();
if (column == null || primaryKey == null)
continue;
var keyValue = primaryKey.GetValue(item);
if (keyValue.ObjectIsNew()) continue;
var result = GetByColumn(keyValue, column.Name, prop.PropertyType);
prop.SetValue(item, result);
if (result != null && !onlyFirstLevel)
LoadChildren(result, onlyFirstLevel, clreplacedes, ignoreList, pathLoaded, propertyName, id);
}
else
{
var isGeneric = prop.PropertyType.GetActualType() != prop.PropertyType;
var keyValue = key.GetValue(item);
if (keyValue.ObjectIsNew() && !isGeneric) continue;
object result = null;
if (isGeneric && key.GetCustomAttribute<ForeignKey>().Type == item.GetType()) // trying to load children
result = GetByColumn(item.GetPrimaryKeyValue(), key.GetPropertyName(), prop.PropertyType);
else
result = GetById(keyValue, prop.PropertyType);
prop.SetValue(item, result);
if (result != null && !onlyFirstLevel)
LoadChildren(result, onlyFirstLevel, clreplacedes, ignoreList, pathLoaded, propertyName, id);
}
}
break;
}
return item;
}
19
Source : Methods.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public static List<RegionInfo> GetCountriesByIso3166()
{
var countries = new List<RegionInfo>();
foreach (var culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
var country = new RegionInfo(culture.LCID);
if (countries.All(p => p.Name != country.Name))
countries.Add(country);
}
return countries.OrderBy(p => p.EnglishName).ToList();
}
19
Source : FormatExpressionBuilder.cs
with MIT License
from alethic
with MIT License
from alethic
static bool ValidateIdnHostname(string value)
{
return IdnHostnameRegex.IsMatch(value) && value.IndexOfAny(DisallowedIdnChars) == -1 && TryGetIdnAsciiString(value, out var idn) && idn.Split('.').All(i => i.Length <= 63);
}
19
Source : JsonExtensionsTest.cs
with Apache License 2.0
from AlexandreDaSilva
with Apache License 2.0
from AlexandreDaSilva
[Test]
public void test_query_with_vars_json()
{
var q = new StringBuilder()
.AppendLine("query accounts($terms: string)")
.AppendLine("{")
.AppendLine($"accounts(func: anyofterms(first, $terms))")
.AppendLine("{")
.AppendLine("first")
.AppendLine("last")
.AppendLine("age")
.AppendLine("}")
.AppendLine("}")
.ToString();
var vars = new Dictionary<string, string>
{
{ "$terms", string.Join(",", _firsts) }
};
var res = _client.NewTransaction().QueryWithVars<AccountQuery>(q, vars);
replacedert.IsTrue(_firsts.All(f => res.Accounts.Any(a => a.First == f)));
}
19
Source : JsonExtensionsTest.cs
with Apache License 2.0
from AlexandreDaSilva
with Apache License 2.0
from AlexandreDaSilva
[Test]
public void test_query_json()
{
var q = new StringBuilder()
.AppendLine("{")
.AppendLine($"accounts(func: anyofterms(first, \"{string.Join(",", _firsts)}\"))")
.AppendLine("{")
.AppendLine("first")
.AppendLine("last")
.AppendLine("age")
.AppendLine("}")
.AppendLine("}")
.ToString();
var res = _client.NewTransaction().Query<AccountQuery>(q);
replacedert.IsTrue(_firsts.All(f => res.Accounts.Any(a => a.First == f)));
}
19
Source : DependenciesHunter.cs
with MIT License
from AlexeyPerov
with MIT License
from AlexeyPerov
public static bool IsValidForOutput(string path, List<string> ignoreInOutputPatterns)
{
return ignoreInOutputPatterns.All(pattern
=> string.IsNullOrEmpty(pattern) || !Regex.Match(path, pattern).Success);
}
19
Source : XmlUtilitiesTest.cs
with MIT License
from alexleen
with MIT License
from alexleen
[Test]
public void FindAvailableAppenderRefLocations_ShouldNotLoadRoot_WhenNonexistent()
{
XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
xmlDoc.LoadXml("<log4net>\n" +
" <appender name=\"appender0\">\n" +
" <appender-ref ref=\"appender1\" />\n" +
" <appender-ref ref=\"appender2\" />\n" +
" </appender>\n" +
" <appender name=\"appender1\">\n" +
" <appender-ref ref=\"appender2\" />\n" +
" </appender>\n" +
" <appender name=\"appender2\">\n" +
" </appender>\n" +
" <appender name=\"appender3\">\n" +
" </appender>\n" +
" <appender name=\"asyncAppender\" type=\"Log4Net.Async.AsyncForwardingAppender,Log4Net.Async\">\n" +
" <appender-ref ref=\"appender0\" />\n" +
" </appender>\n" +
"</log4net>");
IEnumerable<IAcceptAppenderRef> refs = XmlUtilities.FindAvailableAppenderRefLocations(xmlDoc.FirstChild);
replacedert.AreEqual(1, refs.Count());
replacedert.IsTrue(refs.All(r => r.Node.Name != "root"));
}
19
Source : Zone.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
public Zone Sign(List<DnsKeyRecord> keys, DateTime inception, DateTime expiration, NSec3HashAlgorithm nsec3Algorithm = 0, int nsec3Iterations = 10, byte[] nsec3Salt = null, bool nsec3OptOut = false)
{
if ((keys == null) || (keys.Count == 0))
throw new Exception("No DNS Keys were provided");
if (!keys.All(x => x.IsZoneKey))
throw new Exception("No DNS key with Zone Key Flag were provided");
if (keys.Any(x => (x.PrivateKey == null) || (x.PrivateKey.Length == 0)))
throw new Exception("For at least one DNS key no Private Key was provided");
if (keys.Any(x => (x.Protocol != 3) || ((nsec3Algorithm != 0) ? !x.Algorithm.IsCompatibleWithNSec3() : !x.Algorithm.IsCompatibleWithNSec())))
throw new Exception("At least one invalid DNS key was provided");
List<DnsKeyRecord> keySigningKeys = keys.Where(x => x.IsSecureEntryPoint).ToList();
List<DnsKeyRecord> zoneSigningKeys = keys.Where(x => !x.IsSecureEntryPoint).ToList();
if (nsec3Algorithm == 0)
{
return SignWithNSec(inception, expiration, zoneSigningKeys, keySigningKeys);
}
else
{
return SignWithNSec3(inception, expiration, zoneSigningKeys, keySigningKeys, nsec3Algorithm, nsec3Iterations, nsec3Salt, nsec3OptOut);
}
}
19
Source : ClassWaitConditions.cs
with MIT License
from alfa-laboratory
with MIT License
from alfa-laboratory
public bool ToNotContainMatch(string regexPattern)
{
var regex = new Regex(regexPattern);
return WaitFor(() => GetClreplacedes().All(cn => !regex.Match(cn).Success), ClreplacedesString());
}
19
Source : ConstraintTool.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
private bool ConstraintTypeGUI( Constraint[] constraints, bool differentTypes )
{
var anyUnknownType = constraints.Any( c => c.Type == ConstraintType.Unknown );
// Reference type is set to unknown if we have multi-select and
// the types aren't the same. This is to detect if the user has
// selected some valid type, with the limitation that it's not
// possible to change to Unknown (that action will be ignored).
var refType = differentTypes ?
ConstraintType.Unknown :
constraints[ 0 ].Type;
EditorGUI.showMixedValue = differentTypes;
var newType = refType;
using ( new GUI.EnabledBlock( !EditorApplication.isPlayingOrWillChangePlaymode ) ) {
if ( refType == ConstraintType.Unknown )
newType = (ConstraintType)EditorGUILayout.EnumPopup( GUI.MakeLabel( "Choose type" ),
refType,
InspectorEditor.Skin.Popup );
else
newType = (ConstraintType)EditorGUILayout.EnumPopup( GUI.MakeLabel( "Type" ),
refType,
InspectorEditor.Skin.Popup,
GUILayout.Width( EditorGUIUtility.labelWidth +
2.0f * 76.0f ) );
}
EditorGUI.showMixedValue = false;
// Avoiding change to Unknown when it wasn't possible
// to handle undo/redo for that case.
if ( newType != refType && newType != ConstraintType.Unknown ) {
var performChange = constraints.All( c => c.Type == ConstraintType.Unknown ) ||
EditorUtility.DisplayDialog( "Change constraint type",
"Any changes to parameters (compliance, damping etc.) and/or states of " +
$"any controller will be lost when the type changes to {newType}.\n\n" +
"Do you want to continue?",
"Yes",
"Cancel" );
if ( performChange ) {
var undoIndex = Undo.GetCurrentGroup();
foreach ( var constraint in constraints ) {
if ( newType == constraint.Type )
continue;
constraint.ChangeType( newType,
createdObject =>
{
Undo.RegisterCreatedObjectUndo( createdObject, "ElementaryConstraint created." );
},
destroyObject =>
{
Undo.DestroyObjectImmediate( destroyObject );
} );
}
Undo.CollapseUndoOperations( undoIndex );
}
}
return !anyUnknownType;
}
19
Source : ConstraintAttachmentFrameTool.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
public override void OnPreTargetMembersGUI()
{
var isMultiSelect = AttachmentPairs.Length > 1;
Undo.RecordObjects( AttachmentPairs, "Constraint Attachment" );
var skin = InspectorEditor.Skin;
var guiWasEnabled = UnityEngine.GUI.enabled;
var connectedFrameSynchronized = AttachmentPairs.All( ap => ap.Synchronized );
EditorGUILayout.LabelField( GUI.MakeLabel( "Reference frame", true ), skin.Label );
InspectorGUI.HandleFrames( AttachmentPairs.Select( ap => ap.ReferenceFrame ).ToArray(), 1 );
GUILayout.Space( 4 );
var rect = EditorGUILayout.GetControlRect( false, EditorGUIUtility.singleLineHeight );
var orgWidth = rect.xMax;
UnityEngine.GUI.Label( EditorGUI.IndentedRect( rect ),
GUI.MakeLabel( "Connected frame", true ),
InspectorEditor.Skin.Label );
var buttonWidth = 1.1f * EditorGUIUtility.singleLineHeight;
var buttonHeightOffset = 1.0f;
rect.x = EditorGUIUtility.labelWidth + InspectorGUI.LayoutMagicNumber;
rect.y -= buttonHeightOffset;
rect.width = buttonWidth;
var toggleSynchronized = InspectorGUI.Button( rect,
connectedFrameSynchronized ?
MiscIcon.SynchEnabled :
MiscIcon.SynchDisabled,
true,
"Toggle synchronized with reference frame.",
1.17f );
rect.x += rect.width + 2.0f;
rect.width = orgWidth - rect.x;
rect.y += buttonHeightOffset;
UnityEngine.GUI.Label( rect,
GUI.MakeLabel( $"{( connectedFrameSynchronized ? "Synchronized" : "Free" )}" ),
InspectorEditor.Skin.Label );
if ( toggleSynchronized ) {
foreach ( var ap in AttachmentPairs )
ap.Synchronized = !connectedFrameSynchronized;
if ( !isMultiSelect && AttachmentPairs[ 0 ].Synchronized )
ConnectedFrameTool.TransformHandleActive = false;
}
UnityEngine.GUI.enabled = !connectedFrameSynchronized && !isMultiSelect;
InspectorGUI.HandleFrames( AttachmentPairs.Select( ap => ap.ConnectedFrame ).ToArray(), 1 );
UnityEngine.GUI.enabled = guiWasEnabled;
}
19
Source : ExternalAGXInitializer.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
private bool InitializeCheckout( string agxDir )
{
const int AGX_DEPENDENCIES = 0;
const int AGXTERRAIN_DEPENDENCIES = 1;
const int INSTALLED = 2;
Instance.AGX_DIR = agxDir;
var cmakeCache = new FileInfo( AGX_DIR + Path.DirectorySeparatorChar + "CMakeCache.txt" );
var binData = new BinDirData[]
{
new BinDirData()
{
CMakeKey = "CACHE_DEPENDENCY_DATE:STRING="
},
new BinDirData()
{
CMakeKey = "TERRAIN_DEPENDENCY_DATE:STRING="
},
new BinDirData()
{
CMakeKey = "CMAKE_INSTALL_PREFIX:PATH="
}
};
using ( var stream = cmakeCache.OpenText() ) {
var line = string.Empty;
while ( !binData.All( data => data.HasValue ) &&
( line = stream.ReadLine()?.Trim() ) != null ) {
if ( line.StartsWith( "//" ) )
continue;
binData.Any( data => data.StoreValue( line ) );
}
}
if ( !binData.All( data => data.HasValue ) ) {
foreach ( var data in binData )
if ( !data.HasValue )
Debug.LogError( $"{"ERROR".Color( Color.red )}: {data.CMakeKey}null" );
return false;
}
var dependenciesDir = new DirectoryInfo( AGX_DIR +
Path.DirectorySeparatorChar +
"dependencies" );
if ( !dependenciesDir.Exists ) {
Debug.LogError( $"{"ERROR".Color( Color.red )}: Dependencies directory {dependenciesDir.FullName} - doesn't exist." );
return false;
}
binData[ AGX_DEPENDENCIES ].Directory = dependenciesDir.GetDirectories( $"agx_dependencies_{binData[ AGX_DEPENDENCIES ].Value}*" ).FirstOrDefault();
binData[ AGXTERRAIN_DEPENDENCIES ].Directory = dependenciesDir.GetDirectories( $"agxTerrain_dependencies_{binData[ AGXTERRAIN_DEPENDENCIES ].Value}*" ).FirstOrDefault();
// Handle both absolute and relative CMAKE_INSTALL_PREFIX
var installPath = binData[ INSTALLED ].Value;
if ( Path.IsPathRooted( installPath ) )
binData[ INSTALLED ].Directory = new DirectoryInfo( installPath );
else
binData[ INSTALLED ].Directory = new DirectoryInfo( AGX_DIR +
Path.DirectorySeparatorChar +
installPath );
if ( binData.Any( data => data.Directory == null || !data.Directory.Exists ) ) {
foreach ( var data in binData )
if ( data.Directory == null || !data.Directory.Exists )
Debug.LogError( $"{"ERROR".Color( Color.red )}: Unable to find directory for key {data.CMakeKey}." );
return false;
}
AGX_BIN_PATH = ( from data in binData
select $"{data.Directory.FullName}{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}x64" ).ToArray();
AGX_PLUGIN_PATH = $"{AGX_BIN_PATH[ INSTALLED ]}{Path.DirectorySeparatorChar}plugins";
AGX_DATA_DIR = $"{binData[ INSTALLED ].Directory.FullName}{Path.DirectorySeparatorChar}data";
return true;
}
19
Source : SampleLauncher.cs
with MIT License
from AliakseiFutryn
with MIT License
from AliakseiFutryn
static void CheckSingletonInMulreplacedhreadingMode()
{
Thread[] threads = new Thread[ThreadsCount];
Meeting[] meetings = new Meeting[ThreadsCount];
EventWaitHandle threadsFinishedEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
using (Barrier startBarrier = new Barrier(ThreadsCount), finishBarrier = new Barrier(ThreadsCount, barrier => threadsFinishedEvent.Set()))
{
for (int index = 0; index < ThreadsCount; index++)
{
threads[index] = new Thread(threadIndex =>
{
// Synchronizes all threads before start.
startBarrier.SignalAndWait();
try
{
int currentIndex = (int)threadIndex;
meetings[currentIndex] = currentIndex >= ThreadsCount / 2 ? DoubleCheckedSingleton<Meeting>.Instance : LazySingleton<Meeting>.Instance;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Synhronizes all threads before finish.
finishBarrier.SignalAndWait();
}
});
threads[index].Start(index);
}
threadsFinishedEvent.WaitOne();
Meeting lazySingletonInstance = LazySingleton<Meeting>.Instance;
Meeting doubleCheckedSingletonInstance = DoubleCheckedSingleton<Meeting>.Instance;
// There is an operation which is responsible for increasing some value of nearly
// created instances and then it should be compared with all other instances which
// were created in different threads.
lazySingletonInstance.ParticipantsCount++;
doubleCheckedSingletonInstance.ParticipantsCount++;
Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Take(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Skip(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
}
}
19
Source : StringExtensions.cs
with MIT License
from allisterb
with MIT License
from allisterb
public static bool IsAlphaNumeric(this string value)
{
return value.All(c => Char.IsLetterOrDigit(c));
}
19
Source : ProcessRenamer.cs
with GNU Lesser General Public License v3.0
from Alois-xx
with GNU Lesser General Public License v3.0
from Alois-xx
public string Rename(string exeName, string cmdLine)
{
string lret = exeName;
if (ExeName.Equals(exeName, StringComparison.OrdinalIgnoreCase))
{
bool hasMatches = CmdLineSubstrings.All(substr => cmdLine.IndexOf(substr, StringComparison.OrdinalIgnoreCase) != -1);
// empty filter counts a no filter
if (CmdLineSubstrings.Count == 0)
{
hasMatches = true;
}
bool hasNotMatches = NotCmdLineSubstrings.Where(x=> !String.IsNullOrEmpty(x)).Any(substr => cmdLine.IndexOf(substr, StringComparison.OrdinalIgnoreCase) != -1);
if (hasMatches && !hasNotMatches)
{
lret = NewExeName;
}
}
return lret;
}
19
Source : Program.cs
with GNU General Public License v3.0
from aloopkin
with GNU General Public License v3.0
from aloopkin
public void WriteOptionsIntoConfiguration(IConfig config)
{
try
{
// write service URI into conf, or reads from it, if any
ServiceUri = config.WriteAndReadStringParameter("serviceUri", ServiceUri);
// write account email into conf, or reads from it, if any
Email = config.WriteAndReadStringParameter("accountEmail", Email);
// Should we work with the built-in web server
Standalone = config.WriteAndReadBooleanParameter("standalone", Standalone);
// do we have a webroot parameter to handle?
WebRoot = config.WriteAndReadStringParameter("webRoot", WebRoot);
// Should we bind to IIS? If yes, let's do some config
BindName = config.WriteAndReadStringParameter("bindName", BindName);
BindPort = config.WriteAndReadIntParameter("bindPort", BindPort, 0);
// Should we execute some PowerShell ? If yes, let's do some config
ScriptFile = config.WriteAndReadStringParameter("scriptFile", ScriptFile);
// Writing renewal delay to conf
RenewalDelay = config.WriteAndReadIntParameter("renewalDays", RenewalDelay, 30);
// Writing HTTP listening Port in conf
HttpPort = config.WriteAndReadIntParameter("httpPort", HttpPort, 80);
// Should we store certificate in the CSP?
noCsp = config.WriteAndReadBooleanParameter("noCsp", noCsp);
// Let's store the CSP name, if any
Csp = config.WriteAndReadStringParameter("CSP", Csp);
foreach (KeyValuePair<string, string> miscOpt in MiscOpts)
{
if (miscOpt.Value.All(char.IsDigit))
config.WriteIntParameter(miscOpt.Key, int.Parse(miscOpt.Value));
else
config.WriteStringParameter(miscOpt.Key, miscOpt.Value);
}
}
catch (Exception e)
{
_logger.Error($"Could not Read/Write command line parameters to configuration: {e.Message}");
}
}
19
Source : ContainerBuilderExtensions.cs
with MIT License
from alsami
with MIT License
from alsami
private static ContainerBuilder RegisterMediatRInternal(ContainerBuilder builder, IEnumerable<replacedembly> replacedemblies,
IEnumerable<Type> customBehaviorTypes = null)
{
var enumeratedreplacedemblies = replacedemblies as replacedembly[] ?? replacedemblies.ToArray();
if (enumeratedreplacedemblies == null || !enumeratedreplacedemblies.Any() || enumeratedreplacedemblies.All(x => x == null))
throw new ArgumentNullException(nameof(replacedemblies),
$"Must provide replacedemblies in order to request {nameof(Mediator)}");
var enumeratedCustomBehaviorTypes
= customBehaviorTypes as Type[] ?? customBehaviorTypes?.ToArray() ?? Array.Empty<Type>();
builder.RegisterModule(new MediatRModule(enumeratedreplacedemblies, enumeratedCustomBehaviorTypes));
return builder;
}
19
Source : CreditCardHelper.cs
with MIT License
from Altevir
with MIT License
from Altevir
public static bool IsValidCreditCardNumber(string number)
{
if (string.IsNullOrEmpty(number))
return false;
number = number.RemoveNonNumbers();
if (number.All(char.IsDigit) == false)
return false;
if (12 > number.Length || number.Length > 19)
return false;
return IsValidLuhnn(number);
}
19
Source : ValidationAppSI.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public async Task<List<ValidationIssue>> ValidateAndUpdateProcess(Instance instance, string taskId)
{
_logger.LogInformation($"Validation of {instance.Id}");
List<ValidationIssue> messages = new List<ValidationIssue>();
ModelStateDictionary validationResults = new ModelStateDictionary();
await _altinnApp.RunTaskValidation(instance, taskId, validationResults);
messages.AddRange(MapModelStateToIssueList(validationResults, instance));
Application application = _appResourcesService.GetApplication();
foreach (DataType dataType in application.DataTypes.Where(et => et.TaskId == taskId))
{
List<DataElement> elements = instance.Data.Where(d => d.DataType == dataType.Id).ToList();
if (dataType.MaxCount > 0 && dataType.MaxCount < elements.Count)
{
ValidationIssue message = new ValidationIssue
{
InstanceId = instance.Id,
Code = ValidationIssueCodes.InstanceCodes.TooManyDataElementsOfType,
Severity = ValidationIssueSeverity.Error,
Description = ValidationIssueCodes.InstanceCodes.TooManyDataElementsOfType,
Field = dataType.Id
};
messages.Add(message);
}
if (dataType.MinCount > 0 && dataType.MinCount > elements.Count)
{
ValidationIssue message = new ValidationIssue
{
InstanceId = instance.Id,
Code = ValidationIssueCodes.InstanceCodes.TooFewDataElementsOfType,
Severity = ValidationIssueSeverity.Error,
Description = ValidationIssueCodes.InstanceCodes.TooFewDataElementsOfType,
Field = dataType.Id
};
messages.Add(message);
}
foreach (DataElement dataElement in elements)
{
messages.AddRange(await ValidateDataElement(instance, dataType, dataElement));
}
}
instance.Process.CurrentTask.Validated = new ValidationStatus
{
// The condition for completion is met if there are no errors (or other weirdnesses).
CanCompleteTask = messages.Count == 0 ||
messages.All(m => m.Severity != ValidationIssueSeverity.Error && m.Severity != ValidationIssueSeverity.Unspecified),
Timestamp = DateTime.Now
};
await _instanceService.UpdateProcess(instance);
return messages;
}
19
Source : DelegationsController.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[HttpPost]
[Authorize(Policy = AuthzConstants.ALTINNII_AUTHORIZATION)]
[Route("authorization/api/v1/[controller]/AddRules")]
public async Task<ActionResult> Post([FromBody] List<Rule> rules)
{
if (rules == null || rules.Count < 1)
{
return BadRequest("Missing rules in body");
}
if (!ModelState.IsValid)
{
return BadRequest("Invalid model");
}
try
{
List<Rule> delegationResults = await _pap.TryWriteDelegationPolicyRules(rules);
if (delegationResults.All(r => r.CreatedSuccessfully))
{
return Created("Created", delegationResults);
}
if (delegationResults.Any(r => r.CreatedSuccessfully))
{
return StatusCode(206, delegationResults);
}
string rulesJson = JsonSerializer.Serialize(rules);
_logger.LogError("Delegation could not be completed. None of the rules could be processed, indicating invalid or incomplete input:\n{rulesJson}", rulesJson);
return StatusCode(400, $"Delegation could not be completed");
}
catch (Exception e)
{
_logger.LogError(e, "Delegation could not be completed. Unexpected exception.");
return StatusCode(500, $"Delegation could not be completed due to an unexpected exception.");
}
}
19
Source : PolicyAdministrationPointTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async Task TryWriteDelegationPolicyRules_Error_BlobStorageAqcuireLeaseLockException()
{
// Arrange
int delegatedByUserId = 20001336;
int offeredByPartyId = 50001337;
string coveredBy = "20001337";
string coveredByType = AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute;
List<Rule> unsortedRules = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "error", "error", "blobstoragegetleaselockfail"),
};
List<Rule> expected = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "error", "error", "blobstoragegetleaselockfail", createdSuccessfully: false),
};
// Act
List<Rule> actual = await _pap.TryWriteDelegationPolicyRules(unsortedRules);
// replacedert
replacedert.Equal(expected.Count, actual.Count);
replacedert.True(actual.All(r => string.IsNullOrEmpty(r.RuleId)));
replacedert.True(actual.All(r => !r.CreatedSuccessfully));
replacedertionUtil.replacedertEqual(expected, actual);
_logger.Verify(
x => x.Log(
LogLevel.Information,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((@object, @type) => @object.ToString() == "Could not acquire blob lease lock on delegation policy at path: error/blobstoragegetleaselockfail/50001337/20001337/delegationpolicy.xml" && @type.Name == "FormattedLogValues"),
It.IsAny<Exception>(),
(Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
Times.Once);
}
19
Source : PolicyAdministrationPointTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async Task TryWriteDelegationPolicyRules_Error_BlobStorageLeaseLockWriteException()
{
// Arrange
int delegatedByUserId = 20001336;
int offeredByPartyId = 50001337;
string coveredBy = "20001337";
string coveredByType = AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute;
List<Rule> unsortedRules = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "error", "error", "blobstorageleaselockwritefail"),
};
List<Rule> expected = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "error", "error", "blobstorageleaselockwritefail", createdSuccessfully: false),
};
// Act
List<Rule> actual = await _pap.TryWriteDelegationPolicyRules(unsortedRules);
// replacedert
replacedert.Equal(expected.Count, actual.Count);
replacedert.True(actual.All(r => string.IsNullOrEmpty(r.RuleId)));
replacedert.True(actual.All(r => !r.CreatedSuccessfully));
replacedertionUtil.replacedertEqual(expected, actual);
_logger.Verify(
x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((@object, @type) => @object.ToString() == "An exception occured while processing authorization rules for delegation on delegation policy path: error/blobstorageleaselockwritefail/50001337/20001337/delegationpolicy.xml" && @type.Name == "FormattedLogValues"),
It.IsAny<Exception>(),
(Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
Times.Once);
}
19
Source : PolicyAdministrationPointTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async Task TryWriteDelegationPolicyRules_Error_PostgreGetCurrentException()
{
// Arrange
int delegatedByUserId = 20001336;
int offeredByPartyId = 50001337;
string coveredBy = "20001337";
string coveredByType = AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute;
List<Rule> unsortedRules = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "error", "error", "postgregetcurrentfail"),
};
List<Rule> expected = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "error", "error", "postgregetcurrentfail", createdSuccessfully: false),
};
// Act
List<Rule> actual = await _pap.TryWriteDelegationPolicyRules(unsortedRules);
// replacedert
replacedert.Equal(expected.Count, actual.Count);
replacedert.True(actual.All(r => string.IsNullOrEmpty(r.RuleId)));
replacedert.True(actual.All(r => !r.CreatedSuccessfully));
replacedertionUtil.replacedertEqual(expected, actual);
_logger.Verify(
x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((@object, @type) => @object.ToString() == "An exception occured while processing authorization rules for delegation on delegation policy path: error/postgregetcurrentfail/50001337/20001337/delegationpolicy.xml" && @type.Name == "FormattedLogValues"),
It.IsAny<Exception>(),
(Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
Times.Once);
}
19
Source : PolicyAdministrationPointTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async Task TryWriteDelegationPolicyRules_Error_PostgreWriteDelegationChangeException()
{
// Arrange
int delegatedByUserId = 20001336;
int offeredByPartyId = 50001337;
string coveredBy = "20001337";
string coveredByType = AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute;
List<Rule> unsortedRules = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "error", "error", "postgrewritechangefail"),
};
List<Rule> expected = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "error", "error", "postgrewritechangefail", createdSuccessfully: false),
};
// Act
List<Rule> actual = await _pap.TryWriteDelegationPolicyRules(unsortedRules);
// replacedert
replacedert.Equal(expected.Count, actual.Count);
replacedert.True(actual.All(r => string.IsNullOrEmpty(r.RuleId)));
replacedert.True(actual.All(r => !r.CreatedSuccessfully));
replacedertionUtil.replacedertEqual(expected, actual);
_logger.Verify(
x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((@object, @type) => @object.ToString() == "Writing of delegation change to authorization postgresql database failed for changes to delegation policy at path: error/postgrewritechangefail/50001337/20001337/delegationpolicy.xml" && @type.Name == "FormattedLogValues"),
It.IsAny<Exception>(),
(Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
Times.Once);
}
19
Source : PolicyAdministrationPointTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async Task TryWriteDelegationPolicyRules_Valid()
{
// Arrange
int delegatedByUserId = 20001336;
int offeredByPartyId = 50001337;
string coveredBy = "20001337";
string coveredByType = AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute;
List<Rule> unsortedRules = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1"),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org2", "app1"),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app2"),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Write", "org1", "app1", "task1"), // Should be sorted together with the first rule
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1", task: null, "event1") // Should be sorted together with the first rule
};
List<Rule> expected = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Write", "org1", "app1", "task1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1", task: null, "event1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org2", "app1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app2", createdSuccessfully: true)
};
// Act
List<Rule> actual = await _pap.TryWriteDelegationPolicyRules(unsortedRules);
// replacedert
replacedert.Equal(expected.Count, actual.Count);
replacedert.True(actual.All(r => r.CreatedSuccessfully));
replacedert.True(actual.All(r => !string.IsNullOrEmpty(r.RuleId)));
replacedertionUtil.replacedertEqual(expected, actual);
}
19
Source : PolicyAdministrationPointTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async Task TryWriteDelegationPolicyRules_PartialSuccess()
{
// Arrange
int delegatedByUserId = 20001336;
int offeredByPartyId = 50001337;
string coveredBy = "20001337";
string coveredByType = AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute;
List<Rule> unsortedRules = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1"),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org2", "app1"),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "unknownorg", "unknownapp"), // Should fail as there is no App Policy for this app
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Write", "org1", "app1", "task1"), // Should be sorted together with the first rule
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1", task: null, "event1") // Should be sorted together with the first rule
};
List<Rule> expected = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Write", "org1", "app1", "task1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1", task: null, "event1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org2", "app1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "unknownorg", "unknownapp", createdSuccessfully: false)
};
// Act
List<Rule> actual = await _pap.TryWriteDelegationPolicyRules(unsortedRules);
// replacedert
replacedert.Equal(expected.Count, actual.Count);
replacedert.True(actual.Where(r => r.CreatedSuccessfully).All(r => !string.IsNullOrEmpty(r.RuleId)));
replacedert.True(actual.Where(r => !r.CreatedSuccessfully).All(r => string.IsNullOrEmpty(r.RuleId)));
replacedertionUtil.replacedertEqual(expected, actual);
_logger.Verify(
x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((@object, @type) => @object.ToString() == "No valid App policy found for delegation policy path: unknownorg/unknownapp/50001337/20001337/delegationpolicy.xml" && @type.Name == "FormattedLogValues"),
It.IsAny<Exception>(),
(Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
Times.Once);
}
19
Source : PolicyAdministrationPointTest.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async Task TryWriteDelegationPolicyRules_PartialSuccess_UnsortableRule()
{
// Arrange
int delegatedByUserId = 20001336;
int offeredByPartyId = 50001337;
string coveredBy = "20001337";
string coveredByType = AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute;
List<Rule> unsortedRules = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1"),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org2", "app1"),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", null, null), // Should fail as the rule model is not complete (missing org/app)
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Write", "org1", "app1", "task1"), // Should be sorted together with the first rule
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1", task: null, "event1") // Should be sorted together with the first rule
};
List<Rule> expected = new List<Rule>
{
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Write", "org1", "app1", "task1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org1", "app1", task: null, "event1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", "org2", "app1", createdSuccessfully: true),
TestDataHelper.GetRuleModel(delegatedByUserId, offeredByPartyId, coveredBy, coveredByType, "Read", null, null, createdSuccessfully: false)
};
// Act
List<Rule> actual = await _pap.TryWriteDelegationPolicyRules(unsortedRules);
// replacedert
replacedert.Equal(expected.Count, actual.Count);
replacedert.True(actual.Where(r => r.CreatedSuccessfully).All(r => !string.IsNullOrEmpty(r.RuleId)));
replacedert.True(actual.Where(r => !r.CreatedSuccessfully).All(r => string.IsNullOrEmpty(r.RuleId)));
replacedertionUtil.replacedertEqual(expected, actual);
_logger.Verify(
x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((@object, @type) => @object.ToString().StartsWith("One or more rules could not be processed because of incomplete input:") && @type.Name == "FormattedLogValues"),
It.IsAny<Exception>(),
(Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
Times.Once);
}
19
Source : PartyLookupValidationTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public void TwoPropertiesSet_ReturnsIssue()
{
// Arrange
PartyLookup target = new PartyLookup { Ssn = "09054300139", OrgNo = "910072218" };
// Act
IList<ValidationResult> issues = ModelValidator.ValidateModel(target);
// replacedert
replacedert.True(issues.All(i => i.MemberNames.Contains("OrgNo") && i.ErrorMessage.Contains("With Ssn already")));
}
19
Source : PartyLookupValidationTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public void NoPropertiesSet_ReturnsIssue()
{
// Arrange
PartyLookup target = new PartyLookup();
// Act
IList<ValidationResult> issues = ModelValidator.ValidateModel(target);
// replacedert
replacedert.True(issues.All(i => i.MemberNames.Contains("OrgNo") && i.ErrorMessage.Contains("At least one")));
}
19
Source : PartyLookupValidationTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Theory]
[InlineData("12345678")]
[InlineData("1234567890")]
[InlineData("F23456789")]
public void OrgNoInvalid(string orgNo)
{
// Arrange
PartyLookup target = new PartyLookup { OrgNo = orgNo };
// Act
IList<ValidationResult> issues = ModelValidator.ValidateModel(target);
// replacedert
replacedert.True(issues.All(i => i.MemberNames.Contains("OrgNo") && i.ErrorMessage.Contains("exactly 9 digits")));
}
See More Examples