public void FormatMessage_caches_reused_pattern() { var parserMock = new Mock<IPatternParser>(); var realParser = new PatternParser(new LiteralParser()); parserMock.Setup(x => x.Parse(It.IsAny<StringBuilder>())) .Returns((StringBuilder sb) => realParser.Parse(sb)); var library = new FormatterLibrary(); var subject = new MessageFormatter(patternParser: parserMock.Object, library: library, useCache: true); var pattern = "Hi {gender, select, male {Sir} female {Ma'am}}!"; var actual = subject.FormatMessage(pattern, new { gender = "male" }); Assert.Equal("Hi Sir!", actual); // '2' because it did not format "Ma'am" yet. parserMock.Verify(x => x.Parse(It.IsAny<StringBuilder>()), Times.Exactly(2)); actual = subject.FormatMessage(pattern, new { gender = "female" }); Assert.Equal("Hi Ma'am!", actual); parserMock.Verify(x => x.Parse(It.IsAny<StringBuilder>()), Times.Exactly(3)); // '3' because it has cached all options actual = subject.FormatMessage(pattern, new { gender = "female" }); Assert.Equal("Hi Ma'am!", actual); parserMock.Verify(x => x.Parse(It.IsAny<StringBuilder>()), Times.Exactly(3)); }
private void Benchmark(MessageFormatter subject) { var pattern = "\r\n----\r\nOh {name}? And if we were " + "to surround {gender, select, " + "male {his} " + "female {her}" + "} name with \\{ and \\}, it would look " + "like \\{{name}\\}? Yeah, I know {gender, select, " + "male {him} " + "female {her}" + "}. {gender, select, " + "male {He's}" + "female {She's}" + "} got {messageCount, plural, " + "zero {no messages}" + "one {just one message}" + "=42 {a universal amount of messages}" + "other {uuhm... let's see.. Oh yeah, # messages - and here's a pound: \\#}" + "}!"; int iterations = 100000; var args = new Dictionary<string, object>[iterations]; var rnd = new Random(); for (int i = 0; i < iterations; i++) { var val = rnd.Next(50); args[i] = new { gender = val % 2 == 0 ? "male" : "female", name = val % 2 == 0 ? "Jeff" : "Amanda", messageCount = val }.ToDictionary(); } TestHelpers.Benchmark.Start("Formatting message " + iterations + " times, no warm-up.", this.outputHelper); var output = new StringBuilder(); for (int i = 0; i < iterations; i++) { output.AppendLine(subject.FormatMessage(pattern, args[i])); } TestHelpers.Benchmark.End(this.outputHelper); this.outputHelper.WriteLine(output.ToString()); }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { if(!ShouldGenerateClientSideRules()) yield break; // Don't generate clientside rules if min/max are lazily loaded. var lengthVal = LengthValidator as LengthValidator; if (lengthVal != null && lengthVal.MaxFunc != null && lengthVal.MinFunc != null) { yield break; } var formatter = new MessageFormatter() .AppendPropertyName(Rule.GetDisplayName()) .AppendArgument("MinLength", LengthValidator.Min) .AppendArgument("MaxLength", LengthValidator.Max); string message = LengthValidator.ErrorMessageSource.GetString(); if(LengthValidator.ErrorMessageSource.ResourceType == typeof(Messages)) { // If we're using the default resources then the mesage for length errors will have two parts, eg: // '{PropertyName}' must be between {MinLength} and {MaxLength} characters. You entered {TotalLength} characters. // We can't include the "TotalLength" part of the message because this information isn't available at the time the message is constructed. // Instead, we'll just strip this off by finding the index of the period that separates the two parts of the message. message = message.Substring(0, message.IndexOf(".") + 1); } message = formatter.BuildMessage(message); yield return new ModelClientValidationStringLengthRule(message, LengthValidator.Min, LengthValidator.Max) ; }
public void FormatMessage_using_real_parser_and_library_mock(string source, string expected) { var mockLibary = new Mock<IFormatterLibrary>(); var dummyFormatter = new Mock<IFormatter>(); var subject = new MessageFormatter( new PatternParser(new LiteralParser()), mockLibary.Object, false); var args = new Dictionary<string, object>(); args.Add("name", "Jeff"); dummyFormatter.Setup(x => x.Format("en", It.IsAny<FormatterRequest>(), args, "Jeff", subject)) .Returns("Jeff"); mockLibary.Setup(x => x.GetFormatter(It.IsAny<FormatterRequest>())).Returns(dummyFormatter.Object); // Warm up Benchmark.Start("Warm-up", this.outputHelper); subject.FormatMessage(source, args); Benchmark.End(this.outputHelper); Benchmark.Start("Aaaand a few after warm-up", this.outputHelper); for (int i = 0; i < 1000; i++) { subject.FormatMessage(source, args); } Benchmark.End(this.outputHelper); Assert.Equal(expected, subject.FormatMessage(source, args)); }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { if (!ShouldGenerateClientSideRules()) yield break; var formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName()); var message = formatter.BuildMessage(Validator.ErrorMessageSource.GetString()); yield return new ModelClientValidationRequiredRule(message); }
public PropertyValidatorContext(string propertyDescription, object instance, object propertyValue, string propertyName) { PropertyDescription = propertyDescription; Instance = instance; messageFormatter = new MessageFormatter(); PropertyValue = propertyValue; PropertyName = propertyName; }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { if (!ShouldGenerateClientSideRules()) yield break; var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyDescription); string message = formatter.BuildMessage(RegexValidator.ErrorMessageSource.GetString()); yield return new ModelClientValidationRegexRule(message, RegexValidator.Expression); }
public Server(Func<RequestMessage, ResponseMessage> messageHandler) { Requires.NotNull(messageHandler, "messageHandler"); _messageHandler = messageHandler; _listenerCancellationTokenSource = new CancellationTokenSource(); _listenerThread = new Thread(ListenerLoop); _messageFormatter = new MessageFormatter(); }
public void UnescapeLiterals(string source, string expected) { var patternParserMock = new Mock<IPatternParser>(); var libraryMock = new Mock<IFormatterLibrary>(); var subject = new MessageFormatter(patternParserMock.Object, libraryMock.Object, false, locale: "en"); var actual = subject.UnescapeLiterals(new StringBuilder(source)).ToString(); Assert.Equal(expected, actual); }
public void EnrichDescription(SpecInfo spec, MessageFormatter formatter) { foreach (var given in _given) given.DescribeTo(s => spec.ReportGivenStep(new StepInfo(s)), formatter); _when.DescribeTo(spec.ReportWhenStep, formatter); _expectations.DescribeTo(spec, formatter); }
/// <summary> /// Initializes a new instance of the <see cref="MessageFormatterTests"/> class. /// </summary> public MessageFormatterTests() { this.patternParserMock = new Mock<IPatternParser>(); this.libraryMock = new Mock<IFormatterLibrary>(); this.collectionMock = new Mock<IFormatterRequestCollection>(); this.formatterMock1 = new Mock<IFormatter>(); this.formatterMock2 = new Mock<IFormatter>(); this.subject = new MessageFormatter(this.patternParserMock.Object, this.libraryMock.Object, false); }
public PropertyValidatorContext(string propertyDescription, object instance, PropertySelector propertyValueFunc, string propertyName, MemberInfo member) { propertyValueFunc.Guard("propertyValueFunc cannot be null"); PropertyDescription = propertyDescription; Instance = instance; messageFormatter = new MessageFormatter(); this.PropertyName = propertyName; this.propertyValueFunc = propertyValueFunc; this.Member = member; }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyDescription); string message = formatter.BuildMessage(EmailValidator.ErrorMessageSource.GetString()); yield return new ModelClientValidationRule { ValidationType = "email", ErrorMessage = message }; }
public void VerifyTo(object[] input, SpecInfo results, MessageFormatter formatter) { if (input.Any(x => _comparer.Compare(x, _expected).AreEqual)) { results.ReportExpectationPass(this); return; } results.ReportExpectationFail(this, new ExpectationFailedException(this, input)); }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { if (!ShouldGenerateClientSideRules()) yield break; var formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName()); string message = formatter.BuildMessage(EmailValidator.ErrorMessageSource.GetString()); yield return new ModelClientValidationRule { ValidationType = "email", ErrorMessage = message }; }
public string ConstructMessage(string message, string propertyName, params string[] additionalPropertyNames) { if (additionalPropertyNames == null) { throw new ArgumentNullException("additionalPropertyNames"); } var messageFormatter = new MessageFormatter(); messageFormatter.AppendPropertyName(propertyName); messageFormatter.AppendAdditionalArguments(additionalPropertyNames); return(messageFormatter.BuildMessage(message)); }
public void TestRecursiveBreaking() { Message result = MessageFormatter.FormatMessage(new Message { Content = "This is a [https://osu.ppy.sh [[simple test]]]." }); Assert.AreEqual("This is a [[simple test]].", result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("https://osu.ppy.sh", result.Links[0].Url); Assert.AreEqual(10, result.Links[0].Index); Assert.AreEqual(15, result.Links[0].Length); }
public void TestNewFormatLinkWithBackslashesInside() { Message result = MessageFormatter.FormatMessage(new Message { Content = "This is a [https://osu.ppy.sh link \\ with \\ backslashes \\]" }); Assert.AreEqual("This is a link \\ with \\ backslashes \\", result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("https://osu.ppy.sh", result.Links[0].Url); Assert.AreEqual(10, result.Links[0].Index); Assert.AreEqual(27, result.Links[0].Length); }
public void TestNewFormatLinkWithEscapedBrackets() { Message result = MessageFormatter.FormatMessage(new Message { Content = "This is a [https://osu.ppy.sh nasty link with escaped brackets: \\] and \\[]" }); Assert.AreEqual("This is a nasty link with escaped brackets: ] and [", result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("https://osu.ppy.sh", result.Links[0].Url); Assert.AreEqual(10, result.Links[0].Index); Assert.AreEqual(41, result.Links[0].Length); }
public void TestNewFormatLink() { Message result = MessageFormatter.FormatMessage(new Message { Content = "This is a [https://osu.ppy.sh simple test]." }); Assert.AreEqual("This is a simple test.", result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("https://osu.ppy.sh", result.Links[0].Url); Assert.AreEqual(10, result.Links[0].Index); Assert.AreEqual(11, result.Links[0].Length); }
public void TestOldFormatLinkWithEscapedAndBalancedBrackets() { Message result = MessageFormatter.FormatMessage(new Message { Content = "This is a (\\)super\\(\\( tricky (one))[https://osu.ppy.sh]!" }); Assert.AreEqual("This is a )super(( tricky (one)!", result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("https://osu.ppy.sh", result.Links[0].Url); Assert.AreEqual(10, result.Links[0].Index); Assert.AreEqual(21, result.Links[0].Length); }
public void TestOldFormatWithBackslashes() { Message result = MessageFormatter.FormatMessage(new Message { Content = "This link (should end with a backslash \\)[https://osu.ppy.sh]." }); Assert.AreEqual("This link should end with a backslash \\.", result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("https://osu.ppy.sh", result.Links[0].Url); Assert.AreEqual(10, result.Links[0].Index); Assert.AreEqual(29, result.Links[0].Length); }
public void TestOldFormatLinkWithEscapedBrackets() { Message result = MessageFormatter.FormatMessage(new Message { Content = "This is (another loose bracket \\))[https://osu.ppy.sh]." }); Assert.AreEqual("This is another loose bracket ).", result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("https://osu.ppy.sh", result.Links[0].Url); Assert.AreEqual(8, result.Links[0].Index); Assert.AreEqual(23, result.Links[0].Length); }
public void TestBareLink() { Message result = MessageFormatter.FormatMessage(new Message { Content = "This is a http://www.basic-link.com/?test=test." }); Assert.AreEqual(result.Content, result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("http://www.basic-link.com/?test=test", result.Links[0].Url); Assert.AreEqual(10, result.Links[0].Index); Assert.AreEqual(36, result.Links[0].Length); }
public void TestWikiLink() { Message result = MessageFormatter.FormatMessage(new Message { Content = "This is a [[Wiki Link]]." }); Assert.AreEqual("This is a Wiki Link.", result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("https://osu.ppy.sh/wiki/Wiki Link", result.Links[0].Url); Assert.AreEqual(10, result.Links[0].Index); Assert.AreEqual(9, result.Links[0].Length); }
public void TestOsuMpProtocol() { Message result = MessageFormatter.FormatMessage(new Message { Content = "Join my multiplayer game osump://12346." }); Assert.AreEqual(result.Content, result.DisplayContent); Assert.AreEqual(1, result.Links.Count); Assert.AreEqual("osump://12346", result.Links[0].Url); Assert.AreEqual(25, result.Links[0].Index); Assert.AreEqual(13, result.Links[0].Length); }
public override IEnumerable <ModelClientValidationRule> GetClientValidationRules() { if (!ShouldGenerateClientSideRules()) { yield break; } var formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName()); var message = formatter.BuildMessage(Validator.ErrorMessageSource.GetString()); yield return(new ModelClientValidationRequiredRule(message)); }
protected void btnDeclineBulkMaker_Click(object sender, EventArgs e) { int totalRec = 0; foreach (GridViewRow row in GridView2.Rows) { totalRec += ProcessRequest(Convert.ToInt32(row.Cells[0].Text), "NULL"); //values.Add(row.Cells[0].Text); } this.lblMsg.Text = MessageFormatter.GetFormattedNoticeMessage(string.Format("{0} Customer Record Successfully Declined!", totalRec)); }
protected override void LogMessageCore(string message, IDictionary <string, string> additionalData, Severity severity) { var sb = new StringBuilder(); MessageFormatter.Format(message, additionalData, severity, sb); sb.AppendLine(); // TODO: temporary workaround lock (fileWriteLock) { File.AppendAllText(GetLogFileName(), sb.ToString(), fileEncoding); } }
public void TestMessageFormatterGlobalOldMethod() { ChatState state = new ChatState(); // Note, variable starts with 's' to make sure the s is treated properly in formatting state.GlobalAnswers["session"] = "global test"; string text = "Format '%session%'"; var formattedText = MessageFormatter.FormatMessage(state, "sampleflow", text); Assert.AreEqual(formattedText, "Format 'global test'"); }
public void FormatMessageWithReasonSuccess() { // Given var formatter = new MessageFormatter(); // When var actual = formatter.FormatMessage("1", "is 2", "to be 3", "4"); // Then var rn = Environment.NewLine; Assert.Equal($"{rn}1{rn}is 2{rn}but was expected to be 3{rn}because 4", actual); }
protected void buttonInstall_Click(object sender, EventArgs e) { try { SqlScriptRunner.RunScript(Server.MapPath("~") + @"\App_Data\SQL\Schema\Create-Schema.sql"); SqlScriptRunner.RunScript(Server.MapPath("~") + @"\App_Data\SQL\Data\Create-Data.sql"); labelMessage.Text = MessageFormatter.GetFormattedSuccessMessage("Congratulations! Database installation successful. Click <a href=\"../../../default.aspx\">here </a>to start using Employee Info Starter Kit."); } catch (Exception ex) { labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("Database installation failed. Please provide a appropriate creadential that has permission to install database. <br>" + ex.ToString()); } }
public void TestMessageFormatterLocal() { ChatState state = new ChatState(); var local = state.GetFlowAnswers("sampleflow"); local.FieldAnswers["test"] = "local test"; string text = "Format '%local.test%'"; var formattedText = MessageFormatter.FormatMessage(state, "sampleflow", text); Assert.AreEqual(formattedText, "Format 'local test'"); }
public void VerifyTo(object[] input, SpecInfo results, MessageFormatter formatter) { if (_count != input.Length) { results.ReportExpectationFail(string.Format("Expected {0} new messages, but found {1}.", _count, input.Length), new MessageCountMismatchException(_count, input, formatter)); } else { results.ReportExpectationPass(string.Format("The correct number of messages ({0}) were generated.", _count)); } }
public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var messageFormatter = new MessageFormatter().AppendPropertyName(metadata.DisplayName); var FormattedMessage = messageFormatter.BuildMessage(Options.ErrorMessageSource.GetString(null)); var rule = new ModelClientValidationRule { ErrorMessage = FormattedMessage, ValidationType = "requiredcheckbox" }; yield return(rule); }
public override IEnumerable <ModelClientValidationRule> GetClientValidationRules() { if (!ShouldGenerateClientSideRules()) { yield break; } var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyName); string message = formatter.BuildMessage(RemoteValidator.ErrorMessageSource.GetString(null)); //This is the rule that asp.net mvc 3, uses for Remote attribute. yield return(new ModelClientValidationRemoteRule(message, RemoteValidator.Url, RemoteValidator.HttpMethod, RemoteValidator.AdditionalFields)); }
/// <summary> /// Prepares an exception message /// </summary> /// <param name="id"> the id of the message </param> /// <param name="messageTemplate"> the message template to use </param> /// <param name="parameters"> the parameters for the message (optional) /// </param> /// <returns> the prepared exception message </returns> protected internal virtual string exceptionMessage(string id, string messageTemplate, params object[] parameters) { string formattedTemplate = formatMessageTemplate(id, messageTemplate); if (parameters == null || parameters.Length == 0) { return(formattedTemplate); } else { return(MessageFormatter.arrayFormat(formattedTemplate, parameters).Message); } }
public void FormatMessage_nesting_with_brace_escaping() { var subject = new MessageFormatter(false); const string Pattern = @"{s1, select, 1 {{s2, select, 2 {\{} }} }"; var actual = subject.FormatMessage(Pattern, new { s1 = 1, s2 = 2 }); this.outputHelper.WriteLine(actual); Assert.Equal("{", actual); }
public void FormatMessage(string source, Dictionary <string, object> args, string expected) { var subject = new MessageFormatter(false); // Warmup subject.FormatMessage(source, args); Benchmark.Start("Formatting", this.outputHelper); string result = subject.FormatMessage(source, args); Benchmark.End(this.outputHelper); Assert.Equal(expected, result); this.outputHelper.WriteLine(result); }
/// <summary> /// Adds a client validation rule /// </summary> /// <param name="context"></param> protected override void AddClientValidation(ClientModelValidationContext context) { var formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName()); var message = formatter.BuildMessage(Validator.ErrorMessageSource.GetString()); string minValue = Convert.ToString(MaxValue, CultureInfo.InvariantCulture); if (!string.IsNullOrWhiteSpace(minValue)) { MergeClientAttribute(context, "data-val", "true"); MergeClientAttribute(context, "data-val-range", message); MergeClientAttribute(context, "data-val-range-max", minValue); } }
protected void btnSearchMaker_Click(object sender, EventArgs e) { OracleCommand cmd = new OracleCommand(); cmd.Connection = con; cmd.CommandText = "pkg_cdms2.prc_indivd_customer_per_maker"; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.BindByName = true; try { con.Open(); //cmd.Parameters.Add("p_maker", OracleDbType.Varchar2).Value = this.DDLMakerList.SelectedValue; cmd.Parameters.Add(new OracleParameter("p_maker", OracleDbType.Varchar2, 50)); cmd.Parameters[0].Value = this.DDLMakerList.SelectedValue; cmd.Parameters.Add("p_out", OracleDbType.RefCursor).Direction = ParameterDirection.Output; DataSet ds = new DataSet(); OracleDataAdapter da = new OracleDataAdapter(); da.SelectCommand = cmd; da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { GridView2.DataSource = ds; GridView2.DataBind(); } else { ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); GridView2.DataSource = ds; GridView2.DataBind(); int columncount = GridView2.Rows[0].Cells.Count; GridView2.Rows[0].Cells.Clear(); GridView2.Rows[0].Cells.Add(new TableCell()); GridView2.Rows[0].Cells[0].ColumnSpan = columncount; GridView2.Rows[0].Cells[0].Text = "No Records Found"; } } catch (Exception ex) { lblMsg.Text = MessageFormatter.GetFormattedErrorMessage(ex.Message + ex.StackTrace + " <br />"); } finally { con.Close(); con.Dispose(); } }
private void DQIAfterBVNPageDataBind() { hidTAB.Value = "#tab3"; //string cat = "INDIVIDUAL"; //string branch = "001"; OracleCommand cmd = new OracleCommand(); cmd.Connection = con; cmd.CommandText = "select table_category,table_name,column_name, sum(failed_pct) as Completeness_Failed_PCT,sum(VALIDITY_FAILED_PCT) as Correctness_Failed_PCT " + "from DQI_PROFILE_RESULT_BVN group by table_category,table_name,column_name order by table_category desc"; cmd.CommandType = System.Data.CommandType.Text; cmd.BindByName = true; try { con.Open(); //cmd.Parameters.Add("cust", OracleDbType.RefCursor).Direction = ParameterDirection.Output; DataSet ds = new DataSet(); OracleDataAdapter da = new OracleDataAdapter(); da.SelectCommand = cmd; da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { GridView6.DataSource = ds; GridView6.DataBind(); } else { ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); GridView6.DataSource = ds; GridView6.DataBind(); int columncount = GridView6.Rows[0].Cells.Count; GridView6.Rows[0].Cells.Clear(); GridView6.Rows[0].Cells.Add(new TableCell()); GridView6.Rows[0].Cells[0].ColumnSpan = columncount; GridView6.Rows[0].Cells[0].Text = "No Records Found"; } } catch (Exception ex) { lblMsg.Text = MessageFormatter.GetFormattedErrorMessage(ex.Message + " <br />"); //ex.StackTrace + } finally { con.Close(); // con.Dispose(); } }
void HandleServerRequests(TcpClient client) { while (MessageFormatter.Connected(client)) { if (client.GetStream().DataAvailable) { string sessionJson = MessageFormatter.ReadStreamOnce(client.GetStream()); UserSession ses = JsonConvert.DeserializeObject <UserSession>(sessionJson); switch (ses.Request) { case SessionRequest.GetAllSessions: { byte[] data = MessageFormatter.MessageBytes(sessions); client.GetStream().Write(data, 0, data.Length); } break; case SessionRequest.GetUserSession: break; case SessionRequest.SetStatus: { foreach (var item in sessions) { if (item.UserID == ses.UserID) { item.InGame = ses.InGame; Console.WriteLine("User {0} ingame status is now {1}", item.UserID, item.InGame); } break; } } break; case SessionRequest.GetOnlineSessions: { List <UserSession> temp = sessions.Where(o => o.InGame == true).ToList(); byte[] data = MessageFormatter.MessageBytes(temp); client.GetStream().Write(data, 0, data.Length); } break; default: break; } } } }
private void HandleTcpRequest(PatchClient patchClient) { while (MessageFormatter.Connected(patchClient.client)) { try { List <string> filesToDownload; if (patchClient.client.GetStream().DataAvailable) { if (patchClient.fileList == null) { patchClient.fileList = JsonConvert.DeserializeObject <Dictionary <string, string> >(MessageFormatter.ReadStreamOnce(patchClient.client.GetStream())); Console.WriteLine("Filelist received!"); Console.WriteLine("Comparing files to master list"); filesToDownload = FileChecker.CompareFileDictionaries(masterFiles, patchClient.fileList); Console.WriteLine("Missing files on client:"); foreach (var item in filesToDownload) { Console.WriteLine(item); } FileTransferModel fileTransferModel = GenerateFileTransferModel(filesToDownload, masterFilesPath); Console.WriteLine("Sending missing files list to client"); byte [] modelData = MessageFormatter.MessageBytes(fileTransferModel); patchClient.client.GetStream().Write(modelData, 0, modelData.Length); Console.WriteLine("Files list sent"); } else { string fileToSend = MessageFormatter.ReadStreamOnce(patchClient.client.GetStream()); FileInfo fi = new FileInfo(masterFilesPath + '/' + fileToSend); Console.WriteLine("{0} size: {1}", fi.Name, fi.Length); byte [] preBuffer = BitConverter.GetBytes((int)fi.Length); patchClient.client.Client.SendFile(fi.FullName, preBuffer, null, TransmitFileOptions.UseDefaultWorkerThread); Console.WriteLine("{0} sent", fi.Name); } } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } } lock (clients) clients.Remove(patchClient); Console.WriteLine("{0} disconnected!", patchClient.client.Client.RemoteEndPoint.ToString()); Console.WriteLine("Currently {0} other connected clients!", clients.Count); }
/// <inheritdoc /> public void HandleValueMismatch(string expectedValue, string actualValue, string reason, params object[] reasonArgs) { expectedValue = expectedValue ?? "match"; actualValue = actualValue ?? MessageFormatter.FormatValue(this.Value); var message = MessageFormatter.Format( "The {0} value shall {1}{2} but was {3}.", this.Name == null ? "actual" : $"'{this.Name}'", expectedValue, MessageFormatter.FormatReason(reason, reasonArgs), actualValue); throw new AssertFailedException(message); }
public void Should_NotPassParameters_When_ContainsInvalidParameters() { var argCount = 0; var arg = new TestArg(parameters => { argCount++; }) { Name = "arg", Value = "value", AllowedParameters = new[] { "param" } }; var result = MessageFormatter.Format("test {arg|param=x|someparameter=somevalue}", new IMessageArg[] { arg }); Assert.Equal("test {arg|param=x|someparameter=somevalue}", result); Assert.Equal(0, argCount); }
private static string getMessage(int count, object[] inputs, MessageFormatter formatter) { var sb = new StringBuilder(); sb.AppendFormat("Expected {0} messages, but the following {1} were generated:", count, inputs.Length); sb.AppendLine(); foreach (var input in inputs) { sb.AppendLine(formatter.FormatMessage(input)); } sb.AppendLine("--End of expected messages--"); return sb.ToString(); }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { var propertyToCompare = EqualValidator.MemberToCompare as PropertyInfo; if(propertyToCompare != null) { // If propertyToCompare is not null then we're comparing to another property. // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call. // We only care about property comparisons in this case. var formatter = new MessageFormatter() .AppendPropertyName(Rule.PropertyDescription) .AppendArgument("PropertyValue", propertyToCompare.Name); string message = formatter.BuildMessage(EqualValidator.ErrorMessageSource.GetString()); yield return new ModelClientValidationEqualToRule(message, CompareAttribute.FormatPropertyForClientValidation(propertyToCompare.Name)) ; } }
public void FormatMessage() { var patternParserMock = new Mock<IPatternParser>(); var libraryMock = new Mock<IFormatterLibrary>(); var collectionMock = new Mock<IFormatterRequestCollection>(); var formatterMock1 = new Mock<IFormatter>(); var formatterMock2 = new Mock<IFormatter>(); var subject = new MessageFormatter(patternParserMock.Object, libraryMock.Object, false, locale: "en"); // I can use a bogus plural argument. Mocks <3 var pattern = "{name} has {messages, plural, 123}."; var expected = "Jeff has 123 messages."; var args = new Dictionary<string, object> { { "name", "Jeff" }, { "messages", 1 } }; var requests = new[] { new FormatterRequest( new Literal(0, 5, 1, 7, new StringBuilder("name")), "name", null, null), new FormatterRequest( new Literal(11, 33, 1, 7, new StringBuilder("messages, plural, 123")), "messages", "plural", " 123") }; formatterMock1.Setup(x => x.Format("en", requests[0], args, subject)).Returns("Jeff"); formatterMock2.Setup(x => x.Format("en", requests[1], args, subject)).Returns("123 messages"); collectionMock.Setup(x => x.GetEnumerator()).Returns(EnumeratorMock(requests)); libraryMock.Setup(x => x.GetFormatter(requests[0])).Returns(formatterMock1.Object); libraryMock.Setup(x => x.GetFormatter(requests[1])).Returns(formatterMock2.Object); patternParserMock.Setup(x => x.Parse(It.IsAny<StringBuilder>())).Returns(collectionMock.Object); // First request, and "name" is 4 chars. collectionMock.Setup(x => x.ShiftIndices(0, 4)).Callback( (int index, int length) => { // The '- 2' is also done in the used implementation. requests[1].SourceLiteral.ShiftIndices(length - 2, requests[0].SourceLiteral); }); var actual = subject.FormatMessage(pattern, args); collectionMock.Verify(x => x.ShiftIndices(0, 4), Times.Once); Assert.Equal(expected, actual); }
public void Correctly_assigns_default_localized_error_message() { var originalCulture = Thread.CurrentThread.CurrentUICulture; try { var validator = new TestValidator(v => v.RuleFor(x => x.Surname).NotEmpty()); foreach (var culture in new[] { "en", "de", "fr", "es", "de", "it", "nl", "pl", "pt", "ru", "sv" }) { Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture); var message = Messages.ResourceManager.GetString("notempty_error"); var errorMessage = new MessageFormatter().AppendPropertyName("Surname").BuildMessage(message); Debug.WriteLine(errorMessage); var result = validator.Validate(new Person{Surname = null}); result.Errors.Single().ErrorMessage.ShouldEqual(errorMessage); } } finally { // Always reset the culture. Thread.CurrentThread.CurrentUICulture = originalCulture; } }
public void Correctly_assigns_default_localized_error_message() { var originalCulture = Thread.CurrentThread.CurrentUICulture; try { var validator = new NotEmptyValidator(null); foreach (var culture in new[] {"en", "de", "fr"}) { Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture); var message = Messages.ResourceManager.GetString("notempty_error"); var errorMessage = new MessageFormatter().AppendPropertyName("name").BuildMessage(message); Debug.WriteLine(errorMessage); var result = validator.Validate(new PropertyValidatorContext("name", null, x => null)); result.Single().ErrorMessage.ShouldEqual(errorMessage); } } finally { // Always reset the culture. Thread.CurrentThread.CurrentUICulture = originalCulture; } }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { var formatter = new MessageFormatter() .AppendPropertyName(Rule.PropertyDescription) .AppendArgument("From", RangeValidator.From) .AppendArgument("To", RangeValidator.To); string message = RangeValidator.ErrorMessageSource.GetString(); if (RangeValidator.ErrorMessageSource.ResourceType == typeof(Messages)) { // If we're using the default resources then the mesage for length errors will have two parts, eg: // '{PropertyName}' must be between {From} and {To}. You entered {Value}. // We can't include the "Value" part of the message because this information isn't available at the time the message is constructed. // Instead, we'll just strip this off by finding the index of the period that separates the two parts of the message. message = message.Substring(0, message.IndexOf(".") + 1); } message = formatter.BuildMessage(message); yield return new ModelClientValidationRangeRule(message, RangeValidator.From, RangeValidator.To); }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { if (!ShouldGenerateClientSideRules()) yield break; var propertyToCompare = EqualValidator.MemberToCompare as PropertyInfo; if(propertyToCompare != null) { // If propertyToCompare is not null then we're comparing to another property. // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call. // We only care about property comparisons in this case. var comparisonDisplayName = ValidatorOptions.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null) ?? propertyToCompare.Name.SplitPascalCase(); var formatter = new MessageFormatter() .AppendPropertyName(Rule.GetDisplayName()) .AppendArgument("ComparisonValue", comparisonDisplayName); string message = formatter.BuildMessage(EqualValidator.ErrorMessageSource.GetString()); yield return new ModelClientValidationEqualToRule(message, CompareAttribute.FormatPropertyForClientValidation(propertyToCompare.Name)) ; } }
private void WriteQueueToDisk(Queue<QueuedMessage> queue, string path) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); MessageFormatter messageFormatter = new MessageFormatter(); while (queue.Count > 0) { QueuedMessage queuedMessage; lock (queue) { queuedMessage = queue.Dequeue(); } string routingKey = queuedMessage.RoutingKey; ServiceEventMessage message = queuedMessage.Message; if (message.MessageID == Guid.Empty) message.MessageID = Guid.NewGuid(); if (message.TimeStamp == 0) message.TimeStamp = DateTime.UtcNow.Ticks; string filename = Path.Combine(path, string.Format("{0}_{1}.lck", routingKey, message.MessageID)); string messageFilename = Path.ChangeExtension(filename, ".msg"); if (!File.Exists(messageFilename)) { using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 4096, FileOptions.None)) { messageFormatter.Serialise(stream, message); } File.Move(filename, messageFilename); } } }
public void FormatMessage(string source, Dictionary<string, object> args, string expected) { var subject = new MessageFormatter(false); // Warmup subject.FormatMessage(source, args); Benchmark.Start("Formatting", this.outputHelper); string result = subject.FormatMessage(source, args); Benchmark.End(this.outputHelper); Assert.Equal(expected, result); this.outputHelper.WriteLine(result); }
public void FormatMessage_lets_non_ascii_characters_right_through() { var input = "中test中国话不用彁字。"; var subject = new MessageFormatter(false); var actual = subject.FormatMessage(input, new Dictionary<string, object>()); Assert.Equal(input, actual); }
public void ReadMe_test_to_make_sure_I_dont_look_like_a_fool() { { var mf = new MessageFormatter(false); var str = @"You have {notifications, plural, zero {no notifications} one {one notification} =42 {a universal amount of notifications} other {# notifications} }. Have a nice day, {name}!"; var formatted = mf.FormatMessage( str, new Dictionary<string, object> { { "notifications", 4 }, { "name", "Jeff" } }); Assert.Equal("You have 4 notifications. Have a nice day, Jeff!", formatted); } { var mf = new MessageFormatter(false); var str = @"You {NUM_ADDS, plural, offset:1 =0{didnt add this to your profile} zero{added this to your profile} one{and one other person added this to their profile} other{and # others added this to their profiles} }."; var formatted = mf.FormatMessage(str, new Dictionary<string, object> { { "NUM_ADDS", 0 } }); Assert.Equal("You didnt add this to your profile.", formatted); formatted = mf.FormatMessage(str, new Dictionary<string, object> { { "NUM_ADDS", 1 } }); Assert.Equal("You added this to your profile.", formatted); formatted = mf.FormatMessage(str, new Dictionary<string, object> { { "NUM_ADDS", 2 } }); Assert.Equal("You and one other person added this to their profile.", formatted); formatted = mf.FormatMessage(str, new Dictionary<string, object> { { "NUM_ADDS", 3 } }); Assert.Equal("You and 2 others added this to their profiles.", formatted); } { var mf = new MessageFormatter(false); var str = @"{GENDER, select, male {He} female {She} other {They} } found {NUM_RESULTS, plural, one {1 result} other {# results} } in {NUM_CATEGORIES, plural, one {1 category} other {# categories} }."; var formatted = mf.FormatMessage( str, new Dictionary<string, object> { { "GENDER", "male" }, { "NUM_RESULTS", 1 }, { "NUM_CATEGORIES", 2 } }); Assert.Equal(formatted, "He found 1 result in 2 categories."); formatted = mf.FormatMessage( str, new Dictionary<string, object> { { "GENDER", "male" }, { "NUM_RESULTS", 1 }, { "NUM_CATEGORIES", 1 } }); Assert.Equal(formatted, "He found 1 result in 1 category."); formatted = mf.FormatMessage( str, new Dictionary<string, object> { { "GENDER", "female" }, { "NUM_RESULTS", 2 }, { "NUM_CATEGORIES", 1 } }); Assert.Equal(formatted, "She found 2 results in 1 category."); } { var mf = new MessageFormatter(false); var str = @"Your {NUM, plural, one{message} other{messages}} go here."; var formatted = mf.FormatMessage(str, new Dictionary<string, object> { { "NUM", 1 } }); Assert.Equal(formatted, "Your message go here."); formatted = mf.FormatMessage(str, new Dictionary<string, object> { { "NUM", 3 } }); Assert.Equal(formatted, "Your messages go here."); } { var mf = new MessageFormatter(false); var str = @"His name is {LAST_NAME}... {FIRST_NAME} {LAST_NAME}"; var formatted = mf.FormatMessage( str, new Dictionary<string, object> { { "FIRST_NAME", "James" }, { "LAST_NAME", "Bond" } }); Assert.Equal(formatted, "His name is Bond... James Bond"); } { var mf = new MessageFormatter(false); var str = @"{GENDER, select, male{He} female{She} other{They}} liked this."; var formatted = mf.FormatMessage(str, new Dictionary<string, object> { { "GENDER", "male" } }); Assert.Equal(formatted, "He liked this."); formatted = mf.FormatMessage(str, new Dictionary<string, object> { { "GENDER", "female" } }); Assert.Equal(formatted, "She liked this."); formatted = mf.FormatMessage(str, new Dictionary<string, object> { { "GENDER", "somethingelse" } }); Assert.Equal(formatted, "They liked this."); formatted = mf.FormatMessage(str, new Dictionary<string, object> { }); Assert.Equal(formatted, "They liked this."); } { var mf = new MessageFormatter(true, "en"); mf.Pluralizers["en"] = n => { // ´n´ is the number being pluralized. if (n == 0) { return "zero"; } if (n == 1) { return "one"; } if (n > 1000) { return "thatsalot"; } return "other"; }; var actual = mf.FormatMessage( "You have {number, plural, thatsalot {a shitload of notifications} other {# notifications}}", new Dictionary<string, object> { { "number", 1001 } }); Assert.Equal("You have a shitload of notifications", actual); } }
public void FormatMessage_with_reflection_overload() { var subject = new MessageFormatter(false); var pattern = "You have {UnreadCount, plural, " + "zero {no unread messages}" + "one {just one unread message}" + "other {# unread messages}" + "} today."; var actual = subject.FormatMessage(pattern, new { UnreadCount = 0 }); Assert.Equal("You have no unread messages today.", actual); // The absence of UnreadCount means it will be treated as "zero". actual = subject.FormatMessage(pattern, new { }); Assert.Equal("You have no unread messages today.", actual); actual = subject.FormatMessage(pattern, new { UnreadCount = 1 }); Assert.Equal("You have just one unread message today.", actual); actual = subject.FormatMessage(pattern, new { UnreadCount = 2 }); Assert.Equal("You have 2 unread messages today.", actual); actual = subject.FormatMessage(pattern, new { UnreadCount = 3 }); Assert.Equal("You have 3 unread messages today.", actual); }
public void FormatMessage_nesting_with_brace_escaping() { var subject = new MessageFormatter(false); var pattern = @"{s1, select, 1 {{s2, select, 2 {\{} }} }"; var actual = subject.FormatMessage(pattern, new { s1 = 1, s2 = 2 }); this.outputHelper.WriteLine(actual); Assert.Equal("{", actual); }
public void FormatMessage_debug() { var source = @"{gender, select, male {He} female {She} other {They} } said: You have {count, plural, zero {no notifications} one {just one notification} =42 {a universal amount of notifications} other {# notifications} }. Have a nice day!"; var expected = "He said: You have 5 notifications. Have a nice day!"; var args = new Dictionary<string, object> { { "gender", "male" }, { "count", 5 } }; var subject = new MessageFormatter(false); string result = subject.FormatMessage(source, args); Assert.Equal(expected, result); }