/// <summary> /// Tries to valiidate text data using encoding. /// </summary> /// <param name="data">The text input data to be validated</param> /// <param name="option">The validate encoding to be use on the text input data.</param> /// <returns>True if the text input data is validated against the encoding provide, otherwise False.</returns> public bool TryValidate(string data, ValidateOptions option) { bool isValid = false; switch(option) { case ValidateOptions.UsASCII: { try { byte[] bytes = encoder.GetBytes(data); isValid = true; } catch (EncoderFallbackException e) { isValid = false; logger.TryLog(string.Format("Unable to encode {0} at index {1}", e.IsUnknownSurrogate() ? string.Format("U+{0:X4} U+{1:X4}", Convert.ToUInt16(e.CharUnknownHigh), Convert.ToUInt16(e.CharUnknownLow)) : string.Format("U+{0:X4}", Convert.ToUInt16(e.CharUnknown)), e.Index)); } } break; default: isValid = false; break; } return isValid; }
public void TestProcessCommand_Successful() { // Preconditions Debug.Assert(managerMock != null); Debug.Assert(outputMock != null); Debug.Assert(bootstrapperMock != null); /* GIVEN */ var command = new ValidateCommand(managerMock.Object, outputMock.Object, bootstrapperMock.Object); var options = new ValidateOptions { IsVerbose = false, ConfigPath = Assembly.GetExecutingAssembly().Location }; /* WHEN */ var returnCode = command.Execute(options); /* THEN */ // We test if the command was successful and returned code 0. Assert.AreEqual(successCode, returnCode); bootstrapperMock.Verify(bootstrapper => bootstrapper.ComposeImports(managerMock.Object), Times.Once); managerMock.Verify(manager => manager.LoadConfiguration(It.IsAny <FilePath>()), Times.Once); }
public void TestProcessCommand_OnBootstrapperError() { // Preconditions Debug.Assert(managerMock != null); Debug.Assert(outputMock != null); Debug.Assert(bootstrapperMock != null); /* GIVEN */ bootstrapperMock .Setup(bootstrapper => bootstrapper.ComposeImports(It.IsAny <object>()))? .Throws(new InvalidOperationException()); var command = new ValidateCommand(managerMock.Object, outputMock.Object, bootstrapperMock.Object); var options = new ValidateOptions { IsVerbose = false, ConfigPath = Assembly.GetExecutingAssembly().Location }; /* WHEN */ var returnCode = command.Execute(options); /* THEN */ // We test if the command failed and returned code -1. Assert.AreEqual(failCode, returnCode); bootstrapperMock.Verify(bootstrapper => bootstrapper.ComposeImports(managerMock.Object), Times.Once); managerMock.Verify(manager => manager.LoadConfiguration(It.IsAny <FilePath>()), Times.Never); outputMock.Verify(output => output.PrintError(It.IsAny <InvalidOperationException>()), Times.Once); }
/// <summary> /// Tries to valiidate text data using encoding. /// </summary> /// <param name="data">The text input data to be validated</param> /// <param name="option">The validate encoding to be use on the text input data.</param> /// <returns>True if the text input data is validated against the encoding provide, otherwise False.</returns> public bool TryValidate(string data, ValidateOptions option) { bool isValid = false; switch (option) { case ValidateOptions.UsASCII: { try { byte[] bytes = encoder.GetBytes(data); isValid = true; } catch (EncoderFallbackException e) { isValid = false; logger.TryLog(string.Format("Unable to encode {0} at index {1}", e.IsUnknownSurrogate() ? string.Format("U+{0:X4} U+{1:X4}", Convert.ToUInt16(e.CharUnknownHigh), Convert.ToUInt16(e.CharUnknownLow)) : string.Format("U+{0:X4}", Convert.ToUInt16(e.CharUnknown)), e.Index)); } } break; default: isValid = false; break; } return(isValid); }
public ValidationResult Validate(object target, ValidateOptions opts = ValidateOptions.Undefined) { var value = this.GetValue(target); foreach (var valid in this.Validations.Values) { if (valid.Name == "Required") { if (opts.HasFlag(ValidateOptions.IgnoreRequire)) { continue; } if (value == null || (opts.HasFlag(ValidateOptions.DefaultAsNull) && value.Equals(this.DefaultValue))) { return(new ValidationResult(valid, "Required")); } } var errorCode = valid.Check(value); if (!string.IsNullOrEmpty(errorCode)) { return(new ValidationResult(valid, errorCode)); } } return(null); }
internal ExitCode Run() { return(Opts switch { RunOptions runOptions => RunInternal(runOptions), ValidateOptions validateOptions => RunValidateInternal(validateOptions), _ => ExitCode.ExUsage });
static int Validate(ValidateOptions opts) { var configs = LoadConfiguration(opts.ConfigFile); if (ValidateConfiguration(configs)) { return(0); } return(2); }
public void ValidateCommand_AcceptsTargetFileWithSpaceInName() { // A minimal valid log file. string LogFileContents = @"{ ""$schema"": """ + SarifUtilities.SarifSchemaUri + @""", ""version"": ""2.0.0"", ""runs"": [ { ""tool"": { ""name"": ""TestTool"" }, ""results"": [] } ] }"; // A simple schema against which the log file successfully validates. // This way, we don't have to read the SARIF schema from disk to run this test. const string SchemaFileContents = @"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""object"" }"; // Here's the space: const string LogFileDirectory = @"c:\Users\John Smith\logs"; const string LogFileName = "example.sarif"; string logFilePath = Path.Combine(LogFileDirectory, LogFileName); const string SchemaFilePath = @"c:\schemas\SimpleSchemaForTest.json"; var mockFileSystem = new Mock <IFileSystem>(); mockFileSystem.Setup(x => x.DirectoryExists(LogFileDirectory)).Returns(true); mockFileSystem.Setup(x => x.GetDirectoriesInDirectory(It.IsAny <string>())).Returns(new string[0]); mockFileSystem.Setup(x => x.GetFilesInDirectory(LogFileDirectory, LogFileName)).Returns(new string[] { logFilePath }); mockFileSystem.Setup(x => x.ReadAllText(logFilePath)).Returns(LogFileContents); mockFileSystem.Setup(x => x.ReadAllText(SchemaFilePath)).Returns(SchemaFileContents); var validateCommand = new ValidateCommand(mockFileSystem.Object); var options = new ValidateOptions { SchemaFilePath = SchemaFilePath, TargetFileSpecifiers = new string[] { logFilePath } }; int returnCode = validateCommand.Run(options); returnCode.Should().Be(0); }
private void Validate(ValidateOptions options) { var agrix = LoadAgrix(options); if (agrix is null) { return; } try { agrix.Validate(); } catch (Exception e) { Console.Error.WriteLine(e.Message); ExitCode = ExitCode.BadConfig; return; } Console.WriteLine("Configuration is valid"); }
public void TestProcessCommand_IsVerbosePropagation() { // Preconditions Debug.Assert(managerMock != null); Debug.Assert(outputMock != null); Debug.Assert(bootstrapperMock != null); /* GIVEN */ outputMock.SetupSet(output => output.IsVerbose = true); var command = new ValidateCommand(managerMock.Object, outputMock.Object, bootstrapperMock.Object); var options = new ValidateOptions { IsVerbose = true, ConfigPath = "" }; /* WHEN */ command.Execute(options); /* THEN */ outputMock.VerifySet(output => output.IsVerbose = true); }
public void Show() { Container = Div.CreateContainer(default(Element), container=>{ Div.CreateRow(container, row=>{ // new Div(row,element=>{ element.ClassName="span4 offset4 well"; new Legend(element, l=>l.Text("Por favor inicie session")); new Form(element, fe=>{ fe.Action= "/api/User/login"; new TextField(fe, i=>{ i.SetPlaceHolder("NIT");i.Name="Nit";i.ClassName="span4"; i.SetRequired();i.SetMinLength(8); }); new TextField(fe, i=>{ i.SetPlaceHolder("nombre usuario"); i.Name="Nombre";i.ClassName="span4"; i.SetRequired();i.SetMinLength(4); }); new TextField(fe, i=>{ i.SetPlaceHolder("clave"); i.Name="Clave";i.ClassName="span4"; i.SetRequired();i.SetMinLength(4); i.Type="password"; }); var bt = new SubmitButton(fe, b=>{ b.JQuery().Text("Iniciar Session"); b.ClassName="btn btn-info btn-block"; b.LoadingText(" autenticando...."); }); var vo = new ValidateOptions() .SetSubmitHandler( f=>{ bt.ShowLoadingText(); var req=jQuery.PostRequest<UserLoginResponse>(f.Action, f.Serialize(), cb=>{},"json"); req.Done(d=>{ Cayita.Javascript.Firebug.Console.Log(d); f.Clear(); if(OnLogin!=null) OnLogin(d,this); }); req.Fail(e=> { Cayita.Javascript.Firebug.Console.Log("fail :",req); Div.CreateAlertErrorBefore(fe.Elements[0], req.Status.ToString()+":"+ (req.StatusText.StartsWith("ValidationException")? "Usario/clave no validos": req.StatusText)); }); req.Always(a=>{ bt.ResetLoadingText(); }) ; }); fe.Validate(vo); }); }); }); }); Parent.AppendChild(Container.Element()); }
void Paint(Element parent) { new Div(parent, div=>{ div.ClassName="span6 offset3 well"; div.Hide(); }) ; SearchDiv= new Div(default(Element), searchdiv=>{ searchdiv.ClassName= "span6 offset3 nav"; var inputFecha=new InputText(searchdiv, ip=>{ ip.ClassName="input-medium search-query"; ip.SetAttribute("data-mask","99.99.9999"); ip.SetPlaceHolder("dd.mm.aaaa"); }).Element(); new IconButton(searchdiv, (abn, ibn)=>{ ibn.ClassName="icon-search icon-large"; abn.JSelect().Click(evt=>{ if( ! inputFecha.Value.IsDateFormatted()){ Div.CreateAlertErrorAfter(SearchDiv.Element(),"Digite una fecha valida"); return; } LoadGastos( inputFecha.Value.ToServerDate() ); }); }); BNew= new IconButton(searchdiv, (abn, ibn)=>{ ibn.ClassName="icon-plus-sign icon-large"; abn.JSelect().Click(evt=>{ FormDiv.FadeIn(); GridDiv.FadeOut(); Form.Element().Reset(); BDelete.Element().Disabled=true; }); }); BDelete=new IconButton(searchdiv, (abn, ibn)=>{ ibn.ClassName="icon-remove-sign icon-large"; abn.Disabled=true; abn.JSelect().Click(evt=>{ RemoveRow(); }); }); BList= new IconButton(searchdiv, (abn, ibn)=>{ ibn.ClassName="icon-reorder icon-large"; abn.Disabled=true; abn.JSelect().Click(evt=>{ FormDiv.FadeOut(); GridDiv.FadeIn(); abn.Disabled=true; }); }); }); SearchDiv.AppendTo(parent); FormDiv= new Div(default(Element), formdiv=>{ formdiv.ClassName="span6 offset3 well"; Form = new Form(formdiv, f=>{ f.ClassName="form-horizontal"; f.Action="api/Gasto/"; f.Method="post"; var inputId= new InputText(f, e=>{ e.Name="Id"; e.Hide(); }); var cbConcepto=new SelectField(f, (e)=>{ e.Name="IdConcepto"; e.ClassName="span12"; new HtmlOption(e, o=>{ o.Value=""; o.Selected=true; o.Text="Seleccione el concepto ..."; }); LoadConceptos(e); }); var cbFuente= new SelectField(f, (e)=>{ e.Name="IdFuente"; e.ClassName="span12"; new HtmlOption(e, o=>{ o.Value=""; o.Selected=true; o.Text="Seleccione la fuente de pago ..."; }); LoadFuentes(e); }); var fieldValor= new TextField(f,(field)=>{ field.ClassName="span12"; field.Name="Valor"; field.SetPlaceHolder("$$$$$$$$$$"); field.AutoNumericInit(); field.Style.TextAlign="right"; }); new TextField(f,(field)=>{ field.ClassName="span12"; field.Name="Beneficiario"; field.SetPlaceHolder("Pagado a ...."); }); new TextField(f,(field)=>{ field.ClassName="span12"; field.Name="Descripcion"; field.SetPlaceHolder("Descripcion"); }); var bt = new SubmitButton(f, b=>{ b.JSelect().Text("Guardar"); b.LoadingText(" Guardando ..."); b.ClassName="btn btn-info btn-block" ; }); var vo = new ValidateOptions() .SetSubmitHandler( form=>{ bt.ShowLoadingText(); var action= form.Action+(string.IsNullOrEmpty(inputId.Value())?"create":"update"); jQuery.PostRequest<BLResponse<Gasto>>(action, form.AutoNumericGetString(), cb=>{},"json") .Success(d=>{ Cayita.Javascript.Firebug.Console.Log("Success guardar gasto",d); if(string.IsNullOrEmpty(inputId.Value()) ) AppendRow(d.Result[0]); else UpdateRow(d.Result[0]); form.Reset(); }) .Error((request, textStatus, error)=>{ Cayita.Javascript.Firebug.Console.Log("request", request ); Cayita.Javascript.Firebug.Console.Log("error", error ); Div.CreateAlertErrorBefore(form.Elements[0], textStatus+": "+ request.StatusText); }) .Always(a=>{ bt.ResetLoadingText(); }); }) .AddRule((rule, msg)=>{ rule.Element=fieldValor.Element(); rule.Rule.Required(); msg.Required("Digite el valor del gasto"); }) .AddRule((rule, msg)=>{ rule.Element=cbConcepto.Element(); rule.Rule.Required(); msg.Required("Seleccione el concepto"); }) .AddRule((rule, msg)=>{ rule.Element=cbFuente.Element(); rule.Rule.Required(); msg.Required("Seleccione al fuente del pago"); }); f.Validate(vo); }); }); FormDiv.AppendTo(parent); GridDiv= new Div(default(Element), gdiv=>{ gdiv.ClassName="span10 offset1"; TableGastos= new HtmlTable(gdiv, table=>{ InitTable (table); }); gdiv.Hide(); }); GridDiv.AppendTo(parent); }
public void Show() { Container = Div.CreateContainer(default(Element), container=>{ Div.CreateRow(container, row=>{ // new Div(row,element=>{ element.ClassName="span4 offset4 well"; new Legend(element, new LegendConfig{Text="Por favor inicie session"}); new Form(element, fe=>{ fe.Action= Config.Action; fe.Method = Config.Method; var cg = Div.CreateControlGroup(fe); var user= new InputText(cg.Element(), pe=>{ pe.ClassName="span4"; pe.SetPlaceHolder("nombre de usuario"); pe.Name="UserName"; }); cg = Div.CreateControlGroup(fe); var pass =new InputPassword(cg.Element(), pe=>{ pe.ClassName="span4"; pe.SetPlaceHolder("Digite su clave"); pe.Name="Password"; }); var bt = new SubmitButton(fe, b=>{ b.JSelect().Text("Iniciar Session"); b.ClassName="btn btn-info btn-block"; b.LoadingText(" autenticando...."); }); var vo = new ValidateOptions() .SetSubmitHandler( f=>{ bt.ShowLoadingText(); jQuery.PostRequest<LoginResponse>(f.Action, f.Serialize(), cb=>{ Cayita.Javascript.Firebug.Console.Log("callback", cb); },"json") .Success(d=>{ UserName= user.Element().Value; if(OnLogin!=null) OnLogin(d,this); }) .Error((request, textStatus, error)=>{ Div.CreateAlertErrorBefore(fe.Elements[0],textStatus+": " +( request.StatusText.StartsWith("ValidationException")? "Usario/clave no validos": request.StatusText)); }) .Always(a=>{ bt.ResetLoadingText(); }) ; }) .AddRule((rule, msg)=>{ rule.Element=pass.Element(); rule.Rule.Minlength(2).Required(); msg.Minlength("minimo 2 caracteres").Required("Digite su password"); }) .AddRule( (rule, msg)=> { rule.Element= user.Element(); rule.Rule.Required().Minlength(2); msg.Minlength("minimo 2 caracteres"); }); fe.Validate(vo); }); }); }); }); Parent.AppendChild(Container.Element()); }
internal ContextDefinition(string name, string literal, IEnumerable <ContextItem> items, ValidateOptions validate, bool exclusive) { this.Items = new List <ContextItem>(items ?? throw new ArgumentException("Items required")); this.Name = name; this.Literal = literal; this.Validate = validate; this.Exclusive = exclusive; }
private static Tuple <string, GeneratorFactory, IReadOnlyList <GeneratorOption>, ValidateOptions> CreateGen(string label, GeneratorFactory fac, IReadOnlyList <GeneratorOption> options, ValidateOptions validatorFunc) { #if DEBUG //Validate and warn about the generator options. var optionKeys = new HashSet <string>(); foreach (var option in options) { if (option.Key == null) { throw new ArgumentException($"Generator option key must be non-null. Option {option.Label} on generator named {label}"); //If the key is null, the program will crash when you try to make the generator construct a map. } if (option.Label == null) { Debug.WriteLine("Option doesn't have an associated label."); } if (option.ControlOptions != null && option.Control != GeneratorOption.ControlType.Dropdown) { Debug.WriteLine("Generator option has list of ControlOptions, but the ControlType doesn't use them."); } switch (option.Control) { case GeneratorOption.ControlType.Dropdown: if (option.ControlOptions == null) { Debug.WriteLine("Generator option is missing ControlOptions"); } if (!int.TryParse(option.DefaultContent, out int _)) { throw new ArgumentException($"Default content for option {option.Label} on generator {label} must be parseable to an integer because the ControlType is {option.Control}."); } break; case GeneratorOption.ControlType.Checkbox: if (!bool.TryParse(option.DefaultContent, out bool _)) { throw new ArgumentException($"Default content for option {option.Label} on generator {label} must be parseable to a boolean because the ControlType is {option.Control}."); } break; case GeneratorOption.ControlType.IntegerField: if (!int.TryParse(option.DefaultContent, out int _)) { throw new ArgumentException($"Default content for option {option.Label} on generator {label} must be parseable to an integer because the ControlType is {option.Control}."); } break; default: break; } if (optionKeys.Contains(option.Key)) { Debug.WriteLine($"Options for generator has duplicate keys. Duplicate key: {option.Key}"); } else { optionKeys.Add(option.Key); } } #endif return(new Tuple <string, GeneratorFactory, IReadOnlyList <GeneratorOption>, ValidateOptions>(label, fac, options, validatorFunc)); }
protected override string ConstructTestOutputFromInputResource(string inputResourceName, object parameter) { string v2LogText = GetResourceText(inputResourceName); string inputLogDirectory = this.OutputFolderPath; string inputLogFileName = Path.GetFileName(inputResourceName); string inputLogFilePath = Path.Combine(this.OutputFolderPath, inputLogFileName); string actualLogFilePath = Guid.NewGuid().ToString(); string ruleUnderTest = Path.GetFileNameWithoutExtension(inputLogFilePath).Split('.')[1]; // All SARIF rule prefixes require update to current release. // All rules with JSON prefix are low level syntax/deserialization checks. // We can't transform these test inputs as that operation fixes up erros in the file. bool updateInputsToCurrentSarif = ruleUnderTest.StartsWith("SARIF") ? true : false; var validateOptions = new ValidateOptions { SarifOutputVersion = SarifVersion.Current, TargetFileSpecifiers = new[] { inputLogFilePath }, OutputFilePath = actualLogFilePath, Quiet = true, UpdateInputsToCurrentSarif = updateInputsToCurrentSarif, PrettyPrint = true, Optimize = true }; var mockFileSystem = new Mock <IFileSystem>(); mockFileSystem.Setup(x => x.DirectoryExists(inputLogDirectory)).Returns(true); mockFileSystem.Setup(x => x.GetDirectoriesInDirectory(It.IsAny <string>())).Returns(new string[0]); mockFileSystem.Setup(x => x.GetFilesInDirectory(inputLogDirectory, inputLogFileName)).Returns(new string[] { inputLogFilePath }); mockFileSystem.Setup(x => x.ReadAllText(inputLogFilePath)).Returns(v2LogText); mockFileSystem.Setup(x => x.ReadAllText(It.IsNotIn <string>(inputLogFilePath))).Returns <string>(path => File.ReadAllText(path)); mockFileSystem.Setup(x => x.WriteAllText(It.IsAny <string>(), It.IsAny <string>())); var validateCommand = new ValidateCommand(mockFileSystem.Object); int returnCode = validateCommand.Run(validateOptions); if (validateCommand.ExecutionException != null) { Console.WriteLine(validateCommand.ExecutionException.ToString()); } returnCode.Should().Be(0); SarifLog actualLog = JsonConvert.DeserializeObject <SarifLog>(File.ReadAllText(actualLogFilePath)); // First, we'll strip any validation results that don't originate with the rule under test var newResults = new List <Result>(); foreach (Result result in actualLog.Runs[0].Results) { if (result.RuleId == ruleUnderTest) { newResults.Add(result); } } // Next, we'll remove non-deterministic information, most notably, timestamps emitted for the invocation data. var removeTimestampsVisitor = new RemoveOptionalDataVisitor(OptionallyEmittedData.NondeterministicProperties); removeTimestampsVisitor.Visit(actualLog); // Finally, we'll elide non-deterministic build root details var rebaseUrisVisitor = new RebaseUriVisitor("TEST_DIR", new Uri(inputLogDirectory)); rebaseUrisVisitor.Visit(actualLog); // There are differences in log file output depending on whether we are invoking xunit // from within Visual Studio or at the command-line via xunit.exe. We elide these differences. ToolComponent driver = actualLog.Runs[0].Tool.Driver; driver.Name = "SARIF Functional Testing"; driver.Version = null; driver.FullName = null; driver.SemanticVersion = null; driver.DottedQuadFileVersion = null; driver.Product = null; driver.Organization = null; driver.Properties?.Clear(); actualLog.Runs[0].OriginalUriBaseIds = null; return(JsonConvert.SerializeObject(actualLog, Formatting.Indented)); }
private static int Validate(ValidateOptions compileOptions) { _logger.Warn(ErrorArgumentVerbNotImplemented); return 0; }
void Paint(Element parent) { new Div(parent, div=>{ div.ClassName="span6 offset3 well"; div.Hide(); }) ; SearchDiv= new Div(default(Element), searchdiv=>{ searchdiv.ClassName= "span6 offset3 nav"; BNew = new IconButton(searchdiv, (abn, ibn)=>{ ibn.ClassName="icon-plus-sign icon-large"; abn.JSelect().Click(evt=>{ GridDiv.Hide(); FormDiv.FadeIn(); Form.Element().Reset(); BDelete.Element().Disabled=true; BList.Element().Disabled=false; }); }); BDelete= new IconButton(searchdiv, (abn, ibn)=>{ ibn.ClassName="icon-remove-sign icon-large"; abn.Disabled=true; abn.JSelect().Click(evt=>{ RemoveRow(); }); }); BList= new IconButton(searchdiv, (abn, ibn)=>{ ibn.ClassName="icon-reorder icon-large"; abn.JSelect().Click(evt=>{ FormDiv.Hide(); GridDiv.FadeIn(); BList.Element().Disabled=true; }); }); }); SearchDiv.AppendTo(parent); GridDiv= new Div(default(Element), gdiv=>{ gdiv.ClassName="span6 offset3"; TableFuentes= new HtmlTable(gdiv, table=>{ InitTable(table); LoadFuentes(table); }); }); GridDiv.AppendTo(parent); FormDiv= new Div(default(Element), formdiv=>{ formdiv.ClassName="span6 offset3 well"; formdiv.Hide(); Form = new Form(formdiv, f=>{ f.ClassName="form-horizontal"; f.Action="api/Fuente/"; var inputId= new InputText(f, e=>{ e.Name="Id"; e.Hide(); }); var cbTipo= new SelectField(f, (e)=>{ e.Name="Tipo"; e.ClassName="span12"; new HtmlOption(e, o=>{ o.Value=""; o.Selected=true; o.Text="Seleccione el tipo "; }); new HtmlOption(e, o=>{ o.Value="Credito"; o.Text="Credito"; }); new HtmlOption(e, o=>{ o.Value="Debito"; o.Text="Debito"; }); }); var fieldCodigo=new TextField(f,(field)=>{ field.ClassName="span12"; field.Name="Codigo"; field.SetPlaceHolder("Codigo del Recurso ## Grupo ##.## Item"); }); var fieldNombre=new TextField(f,(field)=>{ field.ClassName="span12"; field.Name="Nombre"; field.SetPlaceHolder("Nombre del Recurso"); }); var bt = new SubmitButton(f, b=>{ b.JSelect().Text("Guardar"); b.LoadingText(" Guardando ..."); b.ClassName="btn btn-info btn-block" ; }); var vo = new ValidateOptions() .SetSubmitHandler( form=>{ bt.ShowLoadingText(); var action= form.Action+(string.IsNullOrEmpty(inputId.Value())?"create":"update"); jQuery.PostRequest<BLResponse<Fuente>>(action, form.Serialize(), cb=>{},"json") .Success(d=>{ Cayita.Javascript.Firebug.Console.Log("Success guardar recurso",d); if(string.IsNullOrEmpty(inputId.Value()) ) AppendRow(d.Result[0]); else UpdateRow(d.Result[0]); FormDiv.FadeOut(); GridDiv.Show (); }) .Error((request, textStatus, error)=>{ Cayita.Javascript.Firebug.Console.Log("request", request ); Div.CreateAlertErrorBefore(form.Elements[0], textStatus+": "+ request.StatusText); }) .Always(a=>{ bt.ResetLoadingText(); }); }) .AddRule((rule, msg)=>{ rule.Element=cbTipo.Element(); rule.Rule.Required(); msg.Required("Seleccione tipo de Recurso"); }) .AddRule((rule,msg)=>{ rule.Element=fieldNombre.Element(); rule.Rule.Required().Maxlength(64); msg.Required("Indique el nombre del Recurso").Maxlength("Maximo 64 Caracteres"); }).AddRule((rule,msg)=>{ rule.Element=fieldCodigo.Element(); rule.Rule.Required().Maxlength(5); msg.Required("Indique el codigo del Recurso").Maxlength("Maximo 5 caracteres"); }); f.Validate(vo); }); }); FormDiv.AppendTo(parent); }
private static int Validate(ValidateOptions compileOptions) { _logger.Warn(ErrorArgumentVerbNotImplemented); return(0); }
protected override string ConstructTestOutputFromInputResource(string inputResourceName, object parameter) { string v2LogText = GetResourceText(inputResourceName); string inputLogDirectory = this.OutputFolderPath; string inputLogFileName = Path.GetFileName(inputResourceName); string inputLogFilePath = Path.Combine(this.OutputFolderPath, inputLogFileName); string actualLogFilePath = Guid.NewGuid().ToString(); string ruleUnderTest = Path.GetFileNameWithoutExtension(inputLogFilePath).Split('.')[1]; // All SARIF rule prefixes require update to current release. // All rules with JSON prefix are low level syntax/deserialization checks. // We can't transform these test inputs as that operation fixes up errors in the file. // Also, don't transform the tests for SARIF1011 or SARIF2008, because these rules // examine the actual contents of the $schema property. string[] shouldNotTransform = { "SARIF1011", "SARIF2008" }; bool updateInputsToCurrentSarif = ruleUnderTest.StartsWith("SARIF") && !shouldNotTransform.Contains(ruleUnderTest); var validateOptions = new ValidateOptions { SarifOutputVersion = SarifVersion.Current, TargetFileSpecifiers = new[] { inputLogFilePath }, OutputFilePath = actualLogFilePath, Quiet = true, UpdateInputsToCurrentSarif = updateInputsToCurrentSarif, PrettyPrint = true, Optimize = true, Verbose = true // Turn on note-level rules. }; var mockFileSystem = new Mock <IFileSystem>(); mockFileSystem.Setup(x => x.DirectoryExists(inputLogDirectory)).Returns(true); mockFileSystem.Setup(x => x.GetDirectoriesInDirectory(It.IsAny <string>())).Returns(new string[0]); mockFileSystem.Setup(x => x.GetFilesInDirectory(inputLogDirectory, inputLogFileName)).Returns(new string[] { inputLogFilePath }); mockFileSystem.Setup(x => x.ReadAllText(inputLogFilePath)).Returns(v2LogText); mockFileSystem.Setup(x => x.ReadAllText(It.IsNotIn <string>(inputLogFilePath))).Returns <string>(path => File.ReadAllText(path)); mockFileSystem.Setup(x => x.WriteAllText(It.IsAny <string>(), It.IsAny <string>())); mockFileSystem.Setup(x => x.FileExists(validateOptions.ConfigurationFilePath)).Returns(true); var validateCommand = new ValidateCommand(mockFileSystem.Object); int returnCode = validateCommand.Run(validateOptions); if (validateCommand.ExecutionException != null) { Console.WriteLine(validateCommand.ExecutionException.ToString()); } returnCode.Should().Be(0); string actualLogFileContents = File.ReadAllText(actualLogFilePath); SarifLog actualLog = JsonConvert.DeserializeObject <SarifLog>(actualLogFileContents); Run run = actualLog.Runs[0]; // First, we'll strip any validation results that don't originate with the rule under test. // But leave the results that originate from JSchema! Also, be careful because output files // from "valid" test cases don't have any results. run.Results = run.Results ?.Where(r => IsRelevant(r.RuleId, ruleUnderTest)) ?.ToList(); // Next, remove any rule metadata for those rules. The output files from "valid" test // cases don't have any rules. run.Tool.Driver.Rules = run.Tool.Driver.Rules ?.Where(r => IsRelevant(r.Id, ruleUnderTest)) ?.ToList(); // Since there's only one rule in the metadata, the ruleIndex for all remaining results // must be 0. foreach (Result result in run.Results) { result.RuleIndex = 0; } // Next, we'll remove non-deterministic information, most notably, timestamps emitted for the invocation data. var removeTimestampsVisitor = new RemoveOptionalDataVisitor(OptionallyEmittedData.NondeterministicProperties); removeTimestampsVisitor.Visit(actualLog); // Finally, we'll elide non-deterministic build root details var rebaseUrisVisitor = new RebaseUriVisitor("TEST_DIR", new Uri(inputLogDirectory)); rebaseUrisVisitor.Visit(actualLog); // There are differences in log file output depending on whether we are invoking xunit // from within Visual Studio or at the command-line via xunit.exe. We elide these differences. ToolComponent driver = actualLog.Runs[0].Tool.Driver; driver.Name = "SARIF Functional Testing"; driver.Version = null; driver.FullName = null; driver.SemanticVersion = null; driver.DottedQuadFileVersion = null; driver.Product = null; driver.Organization = null; driver.Properties?.Clear(); actualLog.Runs[0].OriginalUriBaseIds = null; return(JsonConvert.SerializeObject(actualLog, Formatting.Indented)); }
public ValidationResponse Validate(ValidationRequest validationRequest) { string inputFilePath = Path.Combine(_postedFilesDirectory, validationRequest.SavedFileName); string outputFileName = Path.GetFileNameWithoutExtension(validationRequest.SavedFileName) + ValidationLogSuffix; string outputFilePath = Path.Combine(_postedFilesDirectory, outputFileName); string configFilePath = Path.Combine(_policyFilesDirectory, PolicyFileName); ValidationResponse validationResponse; try { var validateOptions = new ValidateOptions { OutputFilePath = outputFilePath, Force = true, PrettyPrint = true, Level = new FailureLevel[] { FailureLevel.Error, FailureLevel.Warning, FailureLevel.Note }, Kind = new ResultKind[] { ResultKind.Fail, ResultKind.Informational, ResultKind.NotApplicable, ResultKind.Open, ResultKind.Open, ResultKind.Pass, ResultKind.Review }, ConfigurationFilePath = configFilePath, TargetFileSpecifiers = new string[] { inputFilePath } }; var validateResponse = new ValidateCommand().Run(validateOptions); validationResponse = new ValidationResponse { Message = $"The SARIF validation service received a request to validate \"{validationRequest.PostedFileName}\".", ExitCode = validateResponse, Arguments = string.Empty, StandardError = string.Empty, StandardOutput = string.Empty, ResultsLogContents = _fileSystem.FileReadAllText(outputFilePath) }; } catch (Exception ex) { validationResponse = new ValidationResponse { ExitCode = int.MaxValue, Message = $"Validation of file {validationRequest.PostedFileName} failed: {ex.Message}" }; } finally { if (_fileSystem.FileExists(outputFilePath)) { _fileSystem.FileDelete(outputFilePath); } if (_fileSystem.FileExists(inputFilePath)) { _fileSystem.FileDelete(inputFilePath); } } return(validationResponse); }