public static void UpdateDatesInWRFNamelist(WrfConfiguration config, DateTime startDate, DateTime endDate, IFileSystem fileSystem) { string wrfNamelistPath = config.WRFNamelist; string wrfNamelistContent = fileSystem.ReadFileContent(wrfNamelistPath); Namelist nameList = NamelistParser.ParseFromString(wrfNamelistContent); nameList["time_control"]["start_year"].Values.Clear(); nameList["time_control"]["start_month"].Values.Clear(); nameList["time_control"]["start_day"].Values.Clear(); nameList["time_control"]["start_hour"].Values.Clear(); nameList["time_control"]["end_year"].Values.Clear(); nameList["time_control"]["end_month"].Values.Clear(); nameList["time_control"]["end_day"].Values.Clear(); nameList["time_control"]["end_hour"].Values.Clear(); nameList["time_control"]["start_year"].Values.Add(startDate.Year); nameList["time_control"]["start_month"].Values.Add(startDate.Month); nameList["time_control"]["start_day"].Values.Add(startDate.Day); nameList["time_control"]["start_hour"].Values.Add(startDate.Hour); nameList["time_control"]["end_year"].Values.Add(endDate.Year); nameList["time_control"]["end_month"].Values.Add(endDate.Month); nameList["time_control"]["end_day"].Values.Add(endDate.Day); nameList["time_control"]["end_hour"].Values.Add(endDate.Hour); string updatedContent = NamelistParser.ParseToString(nameList); fileSystem.WriteFileContent(wrfNamelistPath, updatedContent); }
public static void UpdatePhysicsParameters(WrfConfiguration config, PhysicsConfigurationProcessed physicsConfig, IFileSystem iFileSystem) { string wrfNamelistPath = config.WRFNamelist; string wrfNamelistContent = iFileSystem.ReadFileContent(wrfNamelistPath); Namelist nameList = NamelistParser.ParseFromString(wrfNamelistContent); PropertyInfo[] physicsProperties = typeof(PhysicsConfigurationProcessed).GetProperties(); foreach (PropertyInfo prop in physicsProperties) { ConfigurationPropertyAttribute configPropertyAttribute = prop.GetCustomAttribute <ConfigurationPropertyAttribute>(); if (configPropertyAttribute != null) { string propertyName = configPropertyAttribute.Name; if (propertyName.ToLower() != "name") { List <object> values = new List <object>(); int value = (int)(float)prop.GetValue(physicsConfig); values.Add(value); nameList["physics"][propertyName].Values = values; } } } string newFileContent = NamelistParser.ParseToString(nameList); iFileSystem.WriteFileContent(wrfNamelistPath, newFileContent); }
public void Process_replaces_by_context_properly(bool useProperContext) { var testPattern = "pre<replaceme>post"; var properContext = _fixture.CreateMany <string>(); var improperContext = _fixture.CreateMany <string>(); var properReplacement = _fixture.Create <string>(); var improperReplacement = _fixture.Create <string>(); var properExpression = new Mock <IContextExpression>(); properExpression.Setup(x => x.Matches(properContext)).Returns(true); var improperExpression = new Mock <IContextExpression>(); improperExpression.Setup(x => x.Matches(improperContext)).Returns(true); var namelist = new Namelist("replaceme"); namelist.AddFragment(new NameFragment(properReplacement, properExpression.Object)); namelist.AddFragment(new NameFragment(improperReplacement, improperExpression.Object)); var expectedResult = ""; IEnumerable <string> context; if (useProperContext) { context = properContext; expectedResult = "pre" + properReplacement + "post"; } else { context = improperContext; expectedResult = "pre" + improperReplacement + "post"; } var mockNamelistSource = new Mock <INamelistSource>(); mockNamelistSource .Setup(x => x.GetNamelist("replaceme")) .Returns(namelist); var lexer = new PatternLexer(new SimpleLexer.Lexer()); var parameters = new PatternProcessingParameters(testPattern) { Context = context }; var parser = new NameParser(mockNamelistSource.Object, lexer, _fixture.Create <int>()); parser.Initialize(); var result = parser.Process(parameters); Assert.That(result, Is.EqualTo(expectedResult)); }
public void Process_handles_uniqueness_check_properly() { var testPattern = "<replaceme>"; var replacements = _fixture.CreateMany <string>(); var namelist = new Namelist("replaceme"); var expression = new Mock <IContextExpression>(); expression.Setup(x => x.Matches(It.IsAny <IEnumerable <string> >())).Returns(true); foreach (var replacement in replacements) { namelist.AddFragment(new NameFragment(replacement, expression.Object)); } var mockNamelistSource = new Mock <INamelistSource>(); mockNamelistSource .Setup(x => x.GetNamelist("replaceme")) .Returns(namelist); var lexer = new PatternLexer(new SimpleLexer.Lexer()); var parser = new NameParser(mockNamelistSource.Object, lexer, _fixture.Create <int>()); parser.Initialize(); var results = new List <string>(); PatternProcessingParameters parameters; for (int i = 0; i < replacements.Count(); i++) { parameters = new PatternProcessingParameters(testPattern) { UniqueCheck = results }; results.Add(parser.Process(parameters)); } parameters = new PatternProcessingParameters(testPattern) { UniqueCheck = results }; Assert.Throws <PatternParseException>( () => parser.Process(parameters)); foreach (var replacement in replacements) { Assert.That(results.Where(x => x == replacement).Count() == 1); } }
public void Subpatterns_are_processed_before_being_substituted() { var expression = new Mock <IContextExpression>(); expression.Setup(x => x.Matches(It.IsAny <IEnumerable <string> >())).Returns(true); var subPattern = "<first> and then the <second>"; var pattern = "<^sub_pattern> and then some more <first>"; var expected = "first_sub and then the second_sub and then some more first_sub"; var subPatternNamelist = new Namelist("sub_pattern"); subPatternNamelist.AddFragment(new NameFragment(subPattern, expression.Object)); var firstNamelist = new Namelist("first"); firstNamelist.AddFragment(new NameFragment("first_sub", expression.Object)); var secondNamelist = new Namelist("second"); secondNamelist.AddFragment(new NameFragment("second_sub", expression.Object)); var mockNamelistSource = new Mock <INamelistSource>(); mockNamelistSource .Setup(x => x.GetNamelist("sub_pattern")) .Returns(subPatternNamelist); mockNamelistSource .Setup(x => x.GetNamelist("first")) .Returns(firstNamelist); mockNamelistSource .Setup(x => x.GetNamelist("second")) .Returns(secondNamelist); var parser = new NameParser(mockNamelistSource.Object, 0); parser.Initialize(); var parameters = new PatternProcessingParameters(pattern); var result = parser.Process(parameters); Assert.That(result, Is.EqualTo(expected)); }
public void ParseFileContentsWithString() { string namelistContent = File.ReadAllText("TestFiles/wrfnamelist.input"); Namelist nameList = NamelistParser.ParseFromString(namelistContent); string value = nameList["geogrid"]["map_proj"].Values[0].ToString(); Assert.AreEqual("lambert", value); nameList["geogrid"]["map_proj"].Values.Clear(); nameList["geogrid"]["map_proj"].Values.Add("test"); string asString = NamelistParser.ParseToString(nameList); Assert.IsTrue(asString.Contains("map_proj = 'test'")); }
public static void UpdateDatesInWPSNamelist(WrfConfiguration config, DateTime startDate, DateTime endDate, IFileSystem fileSystem) { string wpsNamelistPath = config.WPSNamelist; string wpsNamelistContent = fileSystem.ReadFileContent(wpsNamelistPath); Namelist nameList = NamelistParser.ParseFromString(wpsNamelistContent); nameList["share"]["start_date"].Values = new List <object>( new string[] { startDate.ToString("yyyy-MM-dd_HH:mm:ss") }); nameList["share"]["end_date"].Values = new List <object>( new string[] { endDate.ToString("yyyy-MM-dd_HH:mm:ss") }); string updatedContent = NamelistParser.ParseToString(nameList); fileSystem.WriteFileContent(wpsNamelistPath, updatedContent); }
public void Process_honors_capitalization_by_sentence() { var expression = new Mock <IContextExpression>(); expression.Setup(x => x.Matches(It.IsAny <IEnumerable <string> >())).Returns(true); var firstNamelist = new Namelist("first_part"); var firstReplacement = "first"; firstNamelist.AddFragment(new NameFragment(firstReplacement, expression.Object)); var secondNamelist = new Namelist("second_part"); var secondReplacement = "second"; secondNamelist.AddFragment(new NameFragment(secondReplacement, expression.Object)); var testPattern = "some begining <first_part> and then. sOME more <second_part> mIxeD CASe"; var expectedResult = "Some begining first and then. SOME more second mIxeD CASe"; var mockNamelistSource = new Mock <INamelistSource>(); mockNamelistSource .Setup(x => x.GetNamelist("first_part")) .Returns(firstNamelist); mockNamelistSource .Setup(x => x.GetNamelist("second_part")) .Returns(secondNamelist); var lexer = new PatternLexer(new SimpleLexer.Lexer()); var parser = new NameParser(mockNamelistSource.Object, lexer, _fixture.Create <int>()); parser.Initialize(); var parameters = new PatternProcessingParameters(testPattern) { CapitalizationScheme = CapitalizationScheme.BY_SENTENCE }; var result = parser.Process(parameters); Assert.That(result, Is.EqualTo(expectedResult)); }
public static string ParseToString(Namelist namelist) { StringBuilder sb = new StringBuilder(1024 * 2); foreach (NamelistSection section in namelist.Sections) { sb.AppendLine($"&{section.Name}"); foreach (NamelistItem item in section.Items) { if (item.Values[0].GetType() == typeof(bool)) { sb.Append($"{item.Name} = "); foreach (bool val in item.Values) { sb.Append($".{val.ToString().ToLower()}.,"); } sb.AppendLine(); } else if (item.Values[0].GetType() == typeof(string)) { if (!item.Values[0].ToString().StartsWith(".")) { for (int c = 0; c < item.Values.Count; c++) { item.Values[c] = $"'{item.Values[c]}'"; } } sb.AppendLine($"{item.Name} = {string.Join(",", item.Values)},"); } else { sb.AppendLine($"{item.Name} = {string.Join(",", item.Values)},"); } } sb.AppendLine("/" + Environment.NewLine); } return(sb.ToString()); }
public void Process_correctly_subsitutes_fragments_in_simple_pattern() { var testPattern = "<first_part><second_part>"; var expression = new Mock <IContextExpression>(); expression.Setup(x => x.Matches(It.IsAny <IEnumerable <string> >())).Returns(true); var firstNamelist = new Namelist("first_part"); var firstReplacement = _fixture.Create <string>(); firstNamelist.AddFragment(new NameFragment(firstReplacement, expression.Object)); var secondNamelist = new Namelist("second_part"); var secondReplacement = _fixture.Create <string>(); secondNamelist.AddFragment(new NameFragment(secondReplacement, expression.Object)); var expectedResult = firstReplacement + secondReplacement; var lexer = new PatternLexer(new SimpleLexer.Lexer()); var mockNamelistSource = new Mock <INamelistSource>(); mockNamelistSource .Setup(x => x.GetNamelist("first_part")) .Returns(firstNamelist); mockNamelistSource .Setup(x => x.GetNamelist("second_part")) .Returns(secondNamelist); var parser = new NameParser(mockNamelistSource.Object, lexer, _fixture.Create <int>()); parser.Initialize(); var parameters = new PatternProcessingParameters(testPattern); var result = parser.Process(parameters); Assert.That(result, Is.EqualTo(expectedResult)); }
public void ParseFileContents() { string namelistContent = File.ReadAllText("TestFiles/namelist.input"); Namelist nameList = NamelistParser.ParseFromString(namelistContent); Assert.AreEqual(8, nameList.Sections.Count); Assert.AreEqual("time_control", nameList["time_control"].Name); Assert.AreEqual("run_days", nameList["time_control"]["run_days"].Name); Assert.AreEqual(1, nameList["time_control"].Items[0].Values.Count); Assert.AreEqual(125.0, nameList["time_control"]["run_hours"].Values[0]); Assert.AreEqual(1, nameList["time_control"]["start_year"].Values.Count); string namelistBackToString = NamelistParser.ParseToString(nameList); nameList = NamelistParser.ParseFromString(namelistBackToString); Assert.AreEqual(8, nameList.Sections.Count); Assert.AreEqual("time_control", nameList["time_control"].Name); Assert.AreEqual("run_days", nameList["time_control"]["run_days"].Name); Assert.AreEqual(1, nameList["time_control"].Items[0].Values.Count); Assert.AreEqual(125.0, nameList["time_control"]["run_hours"].Values[0]); Assert.AreEqual(1, nameList["time_control"]["start_year"].Values.Count); }
public static Namelist ParseFromString(string namelistContent) { Namelist ret = new Namelist(); ret.Sections = new List <NamelistSection>(); StringReader reader = new StringReader(namelistContent); NamelistSection currentSection = null; string line = null; while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (line.StartsWith("!")) { continue; } if (line.StartsWith("&")) { // new section. currentSection = new NamelistSection(); currentSection.Name = line.Replace("&", "").Trim(); currentSection.Items = new List <NamelistItem>(); ret.Sections.Add(currentSection); } else if (!line.StartsWith("/") && line.Length > 0 && currentSection != null) { string[] bits = line.Split('='); string name = bits[0].Trim(); string[] stringValues = bits[1].Trim().Split(',').Where( n => !string.IsNullOrEmpty(n)).Select(n => n.Trim()).ToArray(); List <object> values = new List <object>(); double dResult = 0; if (double.TryParse(stringValues[0], out dResult)) { foreach (string stringValue in stringValues) { values.Add(double.Parse(stringValue)); } } else if (stringValues[0] == ".true." || stringValues[0] == ".false.") { foreach (string stringValue in stringValues) { if (stringValue == ".true.") { values.Add(true); } else if (stringValue == ".false.") { values.Add(false); } } } else if (stringValues[0].StartsWith("\'")) { foreach (string stringValue in stringValues) { values.Add(stringValue.Replace("\'", "")); } } currentSection.Items.Add(new NamelistItem { Name = name, Values = values }); } } return(ret); }
public static void ConfigureMobileApp(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); //For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686 config.EnableSystemDiagnosticsTracing(); new MobileAppConfiguration() .UseDefaultConfiguration() .ApplyTo(config); // Use Entity Framework Code First to create database tables based on your DbContext Database.SetInitializer(new RepToolInitializer()); // To prevent Entity Framework from modifying your database schema, use a null database initializer // Database.SetInitializer<RepToolContext>(null); MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings(); if (string.IsNullOrEmpty(settings.HostName)) { // This middleware is intended to be used locally for debugging. By default, HostName will // only have a value when running in an App Service application. app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions { SigningKey = ConfigurationManager.AppSettings["SigningKey"], ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] }, ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] }, TokenHandler = config.GetAppServiceTokenHandler() }); } app.UseWebApi(config); using (var ctx = new RepToolContext()) { ActionCode actionCode = new ActionCode(); actionCode.Description = "Created new user"; DataObjects.Action action = new DataObjects.Action(); action.Date = DateTime.Now; action.Code = actionCode; List <DataObjects.Action> actions = new List <DataObjects.Action>(); actions.Add(action); Customer customer = new Customer(); customer.Name = "Test Customer"; customer.Email = "*****@*****.**"; customer.Address = "1234 W All American Lane"; customer.City = "Chino Valley"; customer.State = "Arizona"; customer.Country = "USA"; List <Customer> customers = new List <Customer>(); customers.Add(customer); Rep rep = new Rep(); rep.FirstName = "Todd"; rep.LastName = "Hubbard"; rep.Email = "*****@*****.**"; rep.IsAdmin = true; rep.IsManager = true; rep.Actions = actions; rep.Customers = customers; Product product = new Product(); product.Name = "KMP"; List <Names> names = new List <Names>(); for (int i = 0; i < 5; i++) { Names name = new Names(); name.Name = "Test" + i.ToString(); names.Add(name); } Namelist namelist = new Namelist(); namelist.Name = "Boys"; namelist.Product = product; namelist.Names = names; OrderStatus orderStatusCode = new OrderStatus(); orderStatusCode.Description = "Just created"; List <OrderLine> orderLines = new List <OrderLine>(); foreach (Names nameWorking in names) { OrderLine orderLine = new OrderLine(); orderLine.Name = nameWorking.Name; orderLine.Qty = 3; orderLine.Order_ID = 1; orderLines.Add(orderLine); } Order order = new Order(); order.Product = product; order.Rep = rep; order.Customer = customer; order.PO = "12345"; order.PlacedOn = DateTime.Now; order.FullfulBy = DateTime.Now; order.CompletedOn = DateTime.Now; order.ShippedOn = DateTime.Now; order.Status = orderStatusCode; order.OrderLines = orderLines; ctx.ActionCodes.Add(actionCode); ctx.Actions.Add(action); ctx.Customers.Add(customer); ctx.Reps.Add(rep); ctx.Products.Add(product); ctx.Namelists.Add(namelist); ctx.OrderStatusCodes.Add(orderStatusCode); ctx.Orders.Add(order); ctx.SaveChanges(); } }