本文整理汇总了C#中Catel.Data.ValidationContext.AddBusinessRuleValidationResult方法的典型用法代码示例。如果您正苦于以下问题:C# ValidationContext.AddBusinessRuleValidationResult方法的具体用法?C# ValidationContext.AddBusinessRuleValidationResult怎么用?C# ValidationContext.AddBusinessRuleValidationResult使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Catel.Data.ValidationContext
的用法示例。
在下文中一共展示了ValidationContext.AddBusinessRuleValidationResult方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Validate
public IValidationContext Validate(string machineIdToValidate)
{
Argument.IsNotNullOrWhitespace(() => machineIdToValidate);
var validationContext = new ValidationContext();
Log.Debug("Retrieving machine id");
var machineId = _identificationService.GetMachineId();
Log.Debug("Validating machine id '{0}' against expected machine id '{1}'", machineId, machineIdToValidate);
var machineSplitted = machineId.Split(new[] { LicenseElements.IdentificationSeparator }, StringSplitOptions.None);
var expectedSplitter = machineIdToValidate.Split(new[] { LicenseElements.IdentificationSeparator }, StringSplitOptions.None);
if (machineSplitted.Length != expectedSplitter.Length)
{
var error = "The number of items inside the license differ too much, assuming machine ids do not match";
Log.Error(error);
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError(error));
return validationContext;
}
var invalidEntries = 0;
for (var i = 0; i < machineSplitted.Length; i++)
{
if (!string.Equals(expectedSplitter[i], machineSplitted[i], StringComparison.OrdinalIgnoreCase))
{
invalidEntries++;
}
}
if (invalidEntries > Threshold)
{
var error = string.Format("{0} values are not equal, not accepting the machine id, maximum threshold is '{1}'", invalidEntries, Threshold);
Log.Error(error);
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError(error));
return validationContext;
}
if (invalidEntries > 0)
{
var warning = string.Format("One of the values is not equal, but we have a threshold of {0} so accepting machine id", Threshold);
Log.Warning(warning);
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateWarning(warning));
}
return validationContext;
}
示例2: Validate
//.........这里部分代码省略.........
// As the last step, sync the field validation results with the context
foreach (var fieldValidationResult in fieldValidationResults)
{
validationContext.AddFieldValidationResult(fieldValidationResult);
}
#endregion
#region Business rules
if (validator != null)
{
validator.BeforeValidateBusinessRules(this, validationContext.GetBusinessRuleValidations());
}
OnValidatingBusinessRules(validationContext);
if (validator != null)
{
validator.ValidateBusinessRules(this, businessRuleValidationResults);
}
ValidateBusinessRules(businessRuleValidationResults);
OnValidatedBusinessRules(validationContext);
if (validator != null)
{
validator.AfterValidateBusinessRules(this, businessRuleValidationResults);
}
// As the last step, sync the field validation results with the context
foreach (var businessRuleValidationResult in businessRuleValidationResults)
{
validationContext.AddBusinessRuleValidationResult(businessRuleValidationResult);
}
#endregion
if (validator != null)
{
validator.Validate(this, validationContext);
}
IsValidated = true;
// Manual sync to get the changes
changes = existingValidationContext.SynchronizeWithContext(validationContext);
}
}
OnValidated(validationContext);
if (validator != null)
{
validator.AfterValidation(this, validationContext.GetFieldValidations(), validationContext.GetBusinessRuleValidations());
}
#region Notify changes
bool hasNotifiedBusinessWarningsChanged = false;
bool hasNotifiedBusinessErrorsChanged = false;
foreach (var change in changes)
{
var changeAsFieldValidationResult = change.ValidationResult as IFieldValidationResult;
var changeAsBusinessRuleValidationResult = change.ValidationResult as IBusinessRuleValidationResult;
if (changeAsFieldValidationResult != null)
{
示例3: ValidateLicense
/// <summary>
/// Validates the license.
/// </summary>
/// <param name="license">The license key the user has given to be validated.</param>
/// <returns>The validation context containing all the validation results.</returns>
public IValidationContext ValidateLicense(string license)
{
Argument.IsNotNullOrWhitespace(() => license);
var validationContext = new ValidationContext();
Log.Info("Validating license");
try
{
var licenseObject = License.Load(license);
var failureList = licenseObject.Validate()
.Signature(_applicationIdService.ApplicationId)
.AssertValidLicense().ToList();
if (failureList.Count > 0)
{
foreach (var failure in failureList)
{
var businessRuleValidationResult = BusinessRuleValidationResult.CreateErrorWithTag(failure.Message, failure.HowToResolve);
validationContext.AddBusinessRuleValidationResult(businessRuleValidationResult);
}
}
var licenseAttributes = licenseObject.AdditionalAttributes;
if (licenseAttributes != null)
{
foreach (var licenseAttribute in licenseAttributes.GetAll())
{
if (string.Equals(licenseAttribute.Key, LicenseElements.MachineId))
{
Log.Debug("Validating license using machine ID");
var machineLicenseValidationContext = _machineLicenseValidationService.Validate(licenseAttribute.Value);
validationContext.SynchronizeWithContext(machineLicenseValidationContext, true);
if (machineLicenseValidationContext.HasErrors)
{
Log.Error("The license can only run on machine with ID '{0}'", licenseAttribute.Value);
}
}
// TODO: add additional attribute checks here
}
}
// Also validate the xml, very important for expiration date and version
var xmlValidationContext = ValidateXml(license);
validationContext.SynchronizeWithContext(xmlValidationContext, true);
}
catch (Exception ex)
{
Log.Error(ex, "An error occurred while loading the license");
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("An unknown error occurred while loading the license, please contact support"));
}
finally
{
if (validationContext.GetErrors().Count > 0)
{
Log.Warning("License is not valid:");
Log.Indent();
foreach (var error in validationContext.GetErrors())
{
Log.Warning("- {0}\n{1}", error.Message, error.Tag as string);
}
Log.Unindent();
}
else
{
Log.Info("License is valid");
}
}
return validationContext;
}
示例4: ValidateXml
/// <summary>
/// Validates the XML
/// </summary>
/// <param name="license">The license.</param>
/// <returns>The validation context containing all the validation results.</returns>
/// <exception cref="ArgumentException">The <paramref name="license" /> is <c>null</c> or whitespace.</exception>
/// <exception cref="XmlException">The license text is not valid XML.</exception>
/// <exception cref="Exception">The root element is not License.</exception>
/// <exception cref="Exception">There were no inner nodes found.</exception>
public IValidationContext ValidateXml(string license)
{
var validationContext = new ValidationContext();
if (string.IsNullOrWhiteSpace(license))
{
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("No license available"));
}
var xmlDataList = new List<XmlDataModel>();
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(license);
var xmlRoot = xmlDoc.DocumentElement;
if (!string.Equals(xmlRoot.Name, "License"))
{
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("Please make sure that you pasted the complete license, including the <License> tags"));
}
var xmlNodes = xmlRoot.ChildNodes;
foreach (XmlNode node in xmlNodes)
{
if (!string.Equals(node.Name, "ProductFeatures"))
{
xmlDataList.Add(new XmlDataModel
{
Name = node.Name,
Value = node.InnerText
});
}
else
{
foreach (XmlNode featureNode in node.ChildNodes)
{
xmlDataList.Add(new XmlDataModel
{
Name = featureNode.Attributes[0].Value,
Value = featureNode.InnerText
});
}
}
}
if (xmlDataList.Count == 0)
{
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("License contains no valid data"));
}
var expData = xmlDataList.FirstOrDefault(x => string.Equals(x.Name, LicenseElements.Expiration));
if (expData != null)
{
DateTime expirationDateTime;
if (DateTime.TryParse(expData.Value, out expirationDateTime))
{
Log.Debug("Using expiration behavior '{0}'", _expirationBehavior.GetType().Name);
var portableLicense = License.Load(license);
if (_expirationBehavior.IsExpired(portableLicense, expirationDateTime, DateTime.Now))
{
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("The license is expired"));
}
}
else
{
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("The expiration date was not a valid date / tim value"));
}
}
var xmlDataVersion = xmlDataList.FirstOrDefault(x => string.Equals(x.Name, LicenseElements.Version));
if (xmlDataVersion != null)
{
Version licenseVersion;
if (Version.TryParse(xmlDataVersion.Value, out licenseVersion))
{
var productVersion = Assembly.GetExecutingAssembly().GetName().Version;
if (productVersion > licenseVersion)
{
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("Your license only supports versions up to '{0}' while the current version of this product is '{1}'", licenseVersion, productVersion));
}
}
else
{
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError("The version was not a valid version value"));
}
}
}
catch (XmlException xmlex)
{
Log.Debug(xmlex);
//.........这里部分代码省略.........
示例5: CorrectlyHandlesRemovalOfExistingValidationResult
public void CorrectlyHandlesRemovalOfExistingValidationResult()
{
var validationContext = new ValidationContext();
var businessRuleValidation = BusinessRuleValidationResult.CreateError("MyError");
validationContext.AddBusinessRuleValidationResult(businessRuleValidation);
Assert.AreEqual(1, validationContext.GetBusinessRuleValidationCount());
validationContext.RemoveBusinessRuleValidationResult(businessRuleValidation);
Assert.AreEqual(0, validationContext.GetBusinessRuleValidationCount());
}
示例6: AddsValidationResultTwice
public void AddsValidationResultTwice()
{
var validationContext = new ValidationContext();
var businessRuleValidation = BusinessRuleValidationResult.CreateError("MyProperty");
validationContext.AddBusinessRuleValidationResult(businessRuleValidation);
Assert.AreEqual(1, validationContext.GetBusinessRuleValidationCount());
validationContext.AddBusinessRuleValidationResult(businessRuleValidation);
Assert.AreEqual(2, validationContext.GetBusinessRuleValidationCount());
}
示例7: ThrowsArgumentNullExceptionForNullValidationResult
public void ThrowsArgumentNullExceptionForNullValidationResult()
{
var validationContext = new ValidationContext();
ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => validationContext.AddBusinessRuleValidationResult(null));
}
示例8: Parse
public IValidationContext Parse(List<string> commandLineArguments, IContext targetContext)
{
var validationContext = new ValidationContext();
targetContext.OriginalCommandLine = string.Join(" ", commandLineArguments);
var isHelp = commandLineArguments.Any(commandLineArgument => commandLineArgument.IsHelp());
if (isHelp)
{
targetContext.IsHelp = true;
return validationContext;
}
var optionDefinitions = _optionDefinitionService.GetOptionDefinitions(targetContext);
var handledOptions = new HashSet<char>();
Log.Debug("Parsing command line");
for (var i = 0; i < commandLineArguments.Count; i++)
{
var commandLineArgument = commandLineArguments[i];
try
{
// Allow the first one to be a non-switch
if (i == 0)
{
if (!commandLineArguments[i].IsSwitch())
{
var emptyOptionDefinition = (from x in optionDefinitions
where !x.HasSwitch()
select x).FirstOrDefault();
if (emptyOptionDefinition == null)
{
var message = string.Format(_languageService.GetString("CommandLine_CannotParseNoEmptySwitch"), commandLineArgument);
Log.Error(message);
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError(message));
continue;
}
UpdateContext(targetContext, emptyOptionDefinition, commandLineArgument);
handledOptions.Add(emptyOptionDefinition.ShortName);
continue;
}
}
if (!commandLineArgument.IsSwitch())
{
var message = string.Format(_languageService.GetString("CommandLine_CannotParseNoSwitch"), commandLineArgument);
Log.Warning(message);
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateWarning(message));
continue;
}
var optionDefinition = (from x in optionDefinitions
where x.IsSwitch(commandLineArgument)
select x).FirstOrDefault();
if (optionDefinition == null)
{
var message = string.Format(_languageService.GetString("CommandLine_CannotParseSwitchNotRecognized"), commandLineArgument);
Log.Warning(message);
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateWarning(message));
continue;
}
var value = string.Empty;
if (!optionDefinition.AcceptsValue)
{
// Assume boolean switch
value = "true";
}
else
{
if (commandLineArguments.Count <= i + 1)
{
var message = string.Format(_languageService.GetString("CommandLine_CannotParseValueMissing"), commandLineArgument);
Log.Warning(message);
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateWarning(message));
continue;
}
value = commandLineArguments[++i];
}
UpdateContext(targetContext, optionDefinition, value);
handledOptions.Add(optionDefinition.ShortName);
}
catch (Exception ex)
{
validationContext.AddBusinessRuleValidationResult(BusinessRuleValidationResult.CreateError(_languageService.GetString("CommandLine_CannotParseExceptionOccurred"), commandLineArgument, ex.Message));
}
}
Log.Debug("Checking if all required options are specified");
foreach (var optionDefinition in optionDefinitions)
{
if (optionDefinition.IsMandatory)
//.........这里部分代码省略.........