detail/ValidateCimInstanceAttribute.cs
#nullable enable
using System; using System.Management.Automation; using System.Text; using Microsoft.Management.Infrastructure; public class ValidateCimInstanceAttribute : System.Management.Automation.ValidateArgumentsAttribute { public string ClassName; public string Namespace; public ValidateCimInstanceAttribute() { ClassName = ""; Namespace = ""; } public ValidateCimInstanceAttribute(string ClassName) { this.ClassName = ClassName; Namespace = ""; } public ValidateCimInstanceAttribute(string ClassName, string Namespace) { this.ClassName = ClassName; this.Namespace = Namespace; } protected override void Validate(object value, EngineIntrinsics engine_intrinsics) { if (value is not CimInstance) { throw new ArgumentException("Value is not a CimInstance."); } if ((this.ClassName == "") && (this.Namespace == "")) { // No restrictions, return return; } this.Namespace = this.Namespace.Replace("\\", "/"); var instance = (CimInstance)value; for (CimClass? current_CIM_class = instance.CimClass; current_CIM_class is not null; current_CIM_class = current_CIM_class.CimSuperClass ) { // If the current class is not the one we are looking for we attempt to check the parent class. if ((this.ClassName != "") && (0 != String.Compare(this.ClassName, current_CIM_class.CimSystemProperties.ClassName, comparisonType: StringComparison.OrdinalIgnoreCase))) { continue; } // If the current namespace is not the one we are looking for we attempt to check the parent class. if ((this.Namespace != "") && (0 != String.Compare(this.Namespace, current_CIM_class.CimSystemProperties.Namespace, comparisonType: StringComparison.OrdinalIgnoreCase))) { continue; } // If we've reached this far it means that both the class and namespace are a match. Return from validate(). return; } throw new ArgumentException(make_error_message()); } string make_error_message() { const string error_message_start = "CimInstance doesn't match the requirements ("; const string error_message_class_name_pre = "CIM class name: '"; const string error_message_class_name_post = "'"; const string error_message_delimiter = "; "; const string error_message_namespace_pre = "CIM namespace: '"; const string error_message_namespace_post = "'"; const string error_message_end = ")."; const int error_message_length = 150; var error_message_builder = new StringBuilder(error_message_start, error_message_length); if (this.ClassName != "") { error_message_builder.Append(error_message_class_name_pre); error_message_builder.Append(this.ClassName); error_message_builder.Append(error_message_class_name_post); if (this.Namespace != "") { error_message_builder.Append(error_message_delimiter); } } if (this.ClassName != "") { error_message_builder.Append(error_message_namespace_pre); error_message_builder.Append(this.Namespace); error_message_builder.Append(error_message_namespace_post); } error_message_builder.Append(error_message_end); return error_message_builder.ToString(); } } |