Is it possible to remove carriage returns from messages written to logs using the log4net framework - log4net

I want to remove carriage returns from strings before they are written to log4net.
Example:
string query = string.Format(#"select
*
from
<a table>
There are three \n there so if I log it via:
log.Debug(query);
I get somewhat of a messy log
The ideal output would have \n stripped. I can do this:
log.Debug(query.Replace("\n",""));
But have to remember to do for each call to the log method...

I'm not sure how to do this with the conversion pattern printf like syntax in the web.config. However, if you want to do this for all levels all the time, you could download the source and alter the internals.
Otherwise, you could create an extension method like so:
public static void Debug(this ILog logger, string message, bool removeNewLines)
{
if (logger == null)
throw new ArgumentNullException("logger");
logger.Debug(removeNewLines ? message.Replace("\n", string.Empty) : message);
}
..and then call it like this:
log.Debug(query, true);
Only problem is you sill have to remember to call this:
log.Debug(query, true);
Instead of this:
log.Debug(query);

Related

Equivalent to DateTime.Parse in NodaTime?

If I have a string like "2020-12-15T12:10:00.202" how can I parse this into NodaTime.LocalDateTime directly, rather than doing something like:
LocalDateTime.FromDateTime(DateTime.Parse("2020-12-15T12:10:00.202"))
And similarly for the other NodaTime types like LocalDate, Instant etc.
You use a LocalDateTimePattern. For example:
// Note: patterns are thread-safe and immutable. Various patterns are provided as
// static properties on the relevant pattern class. If you can't use one of those
// patterns, it's often useful to store the pattern in a static readonly field.
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd'T'HH:mm:ss.fff");
// There's no Parse/TryParse separation - there's just Parse, which returns a
// ParseResult<T> that indicates success/failure.
ParseResult<LocalDateTime> parsed = pattern.Parse("2020-12-15T12:10:00.202");
// Note: if you're okay with invalid input causing an exception, just use
// parsed.Value directly - it will throw a descriptive exception if parsing failed.
if (parsed.Success)
{
LocalDateTime result = parsed.Value;
// Use the result here
}
else
{
// Handle the failure
}
For more details about text handling, see the section in the user guide.
Note that there's no direct equivalent of DateTime.Parse itself, that tries multiple different date/time formats automatically - but you can use a CompositePatternBuilder<T> to try multiple patterns when parsing if you want.

The test failure message for mockito verify

For a parameter class
class Criteria {
private Map params;
public getMap(){ return params; }
}
and a service method accept this criteria
class Service{
public List<Person> query(Criteria criteria){ ... }
}
A custom featureMatcher is used to match the criteria key
private Matcher<Criteria> hasCriteria(final String key, final Matcher<?> valueMatcher){
return new FeatureMatcher<Criteria, Object>((Matcher<? super Object>)valueMatcher, key, key){
#Override protected Object featureValueOf(Criteria actual){
return actual.getMap().get(key);
}
}
}
when using mockito to veryify the arguments:
verify(Service).query((Criteria) argThat("id", hasCriteria("id", equalTo(new Long(12)))));
The error message shows that:
Argument(s) are different! Wanted:
Service.query(
id <12L>
);
-> at app.TestTarget.test_id (TestTarget.java:134)
Actual invocation has different arguments:
Service.query(
app.Criteria#509f5011
);
If I use ArugmentCaptor,
ArgumentCaptor<Criteria> argument = ArgumentCaptor.forClass(Criteria.class);
verify(Service).query(argument.capture());
assertThat(argument.getValue(), hasCriteria("id", equalTo(new Long(12))));
The message is much better:
Expected: id <12L> but id was <2L>
How can I get such message, without using ArgumentCaptor?
The short answer is to adjust the Criteria code, if it's under your control, to write a better toString method. Otherwise, you may be better off using the ArgumentCaptor method.
Why is it hard to do without ArgumentCaptor? You know you're expecting one call, but Mockito was designed to handle it even if you have a dozen similar calls to evaluate. Even though you're using the same matcher implementation, with the same helpful describeMismatch implementation, assertThat inherently tries once to match where verify sees a mismatch and keeps trying to match any other call.
Consider this:
// in code:
dependency.call(true, false);
dependency.call(false, true);
dependency.call(false, false);
// in test:
verify(mockDependency).call(
argThat(is(equalTo(true))),
argThat(is(equalTo(true))));
Here, Mockito wouldn't know which of the calls was supposed to be call(true, true); any of the three might have been it. Instead, it only knows that there was a verification you were expecting that was never satisfied, and that one of three related calls might have been close. In your code with ArgumentCaptor, you can use your knowledge that there's only one call, and provide a more-sane error message; for Mockito, the best it can do is to output all the calls it DID receive, and without a helpful toString output for your Criteria, that's not very helpful at all.

kxml is giving a xmlpullparser exception

I checked SO for the xmlpullparser exception but it's giving me others questions with Android and SOUP. I am using J2me and normal HTTPrequest to get my XML and I am using kXMl to parser the xml text. Below is the code that I am working on. And above it is more parsing code and they work perfectly.
if (parser.getName().equals("comments")) {
event = parser.next();
boolean flag = false;
if (parser.getName().equals("comment")) {
flag = true;
System.out.println("Flag is true");
}
while (flag) {
event = parser.next();
Questioncomments.addComponent(new Label(parser.nextText()));
event = parser.next();
System.out.println("Inside the While");
if (!parser.getName().equals("comment")) {
flag = false;
System.out.println("Flag is false");
}
}
Questioncomments.repaint();
}
XML I am sending this side - <comments><comment>Awesome Question #dulitha<idComment></idComment></comment></comments>
The error is -
org.xmlpull.v1.XmlPullParserException: precondition: START_TAG
(position:TEXT Awesome Question...#1:399 in
java.io.InputStreamReader#f828ed68)
at org.kxml2.io.KXmlParser.exception(+47)
at org.kxml2.io.KXmlParser.nextText(+14)
at
com.petmill.mobile.view.qanda.QuestionCanvas.setData(QuestionCanvas.java:189)
at
com.petmill.mobile.view.qanda.QuestionsList$5$1$1.actionPerformed(QuestionsList.java:119)
The error comes up at the line where I am trying to get the text - parser.nextText(). How can I parse the xml to get the data required... Thanks in advance.
It looks like you are not on the START_TAG event when you call parser.nextText(). Check that you are on a START_TAG event when you call parser.nextText() with the parser.getEventType(). I suspect that you have some whitespace between <comments> and <comment> tag and therefore your parser is not at the event that you expect it to be.
Perhaps you should also consider a safer approach for parsing this xml.
<comments>
<comment>Awesome Question #dulitha
<idComment></idComment>
</comment>
</comments>
this is not valid xml

SVNKit: How to get the revision number from a working directory

I would like to implement a method that can get the svn revision number from the path where a SVN repository has been checked out. The method declaration would look something like this:
long getRevisionNumber(String localPath) { ... }
I'm trying to use SVNKit for this, but it seems to require an SVN URL to start with. Is there any way to start with a local path?
public static long getRevisionNumber(String localPath) throws SVNException {
final SVNStatus status = SVNClientManager.newInstance().getStatusClient().doStatus(new File(localPath), false);
return status != null ? status.getRevision().getNumber() : -1;
}
Also you can use getCommittedRevision() method. It returns revision for a particular file when it was last commited.
clientManager.getStatusClient().doStatus(destination, false).getCommittedRevision().getNumber();

IEnumerable<T>.ConvertAll & DDD

I have an interesting need for an extension method on the IEumerable interface - the same thing as List.ConvertAll. This has been covered before here and I found one solution here. What I don't like about that solution is he builds a List to hold the converted objects and then returns it. I suspect LINQ wasn't available when he wrote his article, so my implementation is this:
public static class IEnumerableExtension
{
public static IEnumerable<TOutput> ConvertAll<T, TOutput>(this IEnumerable<T> collection, Func<T, TOutput> converter)
{
if (null == converter)
throw new ArgumentNullException("converter");
return from item in collection
select converter(item);
}
}
What I like better about this is I convert 'on the fly' without having to load the entire list of whatever TOutput's are. Note that I also changed the type of the delegate - from Converter to Func. The compilation is the same but I think it makes my intent clearer - I don't mean for this to be ONLY type conversion.
Which leads me to my question: In my repository layer I have a lot of queries that return lists of ID's - ID's of entities. I used to have several classes that 'converted' these ID's to entities in various ways. With this extension method I am able to boil all that down to code like this:
IEnumerable<Part> GetBlueParts()
{
IEnumerable<int> keys = GetBluePartKeys();
return keys.ConvertAll<Part>(PartRepository.Find);
}
where the 'converter' is really the repository's Find-by-ID method. In my case, the 'converter' is potentially doing quite a bit. Does anyone see any problems with this approach?
The main issue I see with this approach is it's completely unnecessary.
Your ConvertAll method is nothing different than Enumerable.Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>), which is a standard LINQ operator. There's no reason to write an extension method for something that already is in the framework.
You can just do:
IEnumerable<Part> GetBlueParts()
{
IEnumerable<int> keys = GetBluePartKeys();
return keys.Select<int,Part>(PartRepository.Find);
}
Note: your method would require <int,Part> as well to compile, unless PartRepository.Find only works on int, and only returns Part instances. If you want to avoid that, you can probably do:
IEnumerable<Part> GetBlueParts()
{
IEnumerable<int> keys = GetBluePartKeys();
return keys.Select(i => PartRepository.Find<Part>(i)); // I'm assuming that fits your "Find" syntax...
}
Why not utilize the yield keyword (and only convert each item as it is needed)?
public static class IEnumerableExtension
{
public static IEnumerable<TOutput> ConvertAll<T, TOutput>
(this IEnumerable<T> collection, Func<T, TOutput> converter)
{
if(null == converter)
throw new ArgumentNullException("converter");
foreach(T item in collection)
yield return converter(item);
}
}

Resources