Linq expression decimal culture - linq

I have this piece of code:
fee.SingleOrDefault(f => 100.05M >= f.Rate);
In the database the Fee.Rate is a money field stored using invariant culture. But using this select gives an error because my current culture will convert "100.05" to "100,05" wihich results in;
An expression of non-boolean type specified in a context where a condition is expected, near ','.
What is the best way to do this?

This strikes me as less of a LINQ issue and more of a SubSonic issue. Taking a quick peek at their LINQ parser it looks like constant values are handled with ToString() with no regard for culture (see SubSonic.Linq.Structure.TSqlFormatter.VisitConstant). Writing/contributing a patch for this would be ideal (to either allow specification of a culture or at least to use invariant by default), otherwise I think you're stuck switching the thread culture.

Thank you for the answer. As a solution I have modified the SqlServer.ttinclude template to switch to invariant culture in the Find method.
Not a perfect but temporary solution, I'll create a patch or at least report the problem to SubSonic.

Related

Oracle Leading zero for number

How can I disable removing leading zero for decimal, when it convert to char?
For example:
select to_char(0.1) from dual;
return .1, not 0.1.
I know than i can use format parameter, but i want that it work correct for implicit conversion.
I have a lot of plsql code for get data from database.
In some case there are conversions from float to varchar2.
For example use dbms_sql.define_array with varchar2 table when column type of request is number.
I can try find all such things and correct them (and I do it), but IMHO it is better way to set up rule for such conversions.
Thanks in advance.
Afaik you cannot alter the default format for implicit conversion.
In case you limit yourself to using the conversion in the context of inserts/updates to a given table, you might mimic the intended behaviour using database triggers. I do not see any advantage compared to an express format model in your queries for that use case.
There are some official oracle docs claiming that you can override built-in functions by re-implementing them in java. I have never done that, I do not know whether this is a generally viable method, and I would strongly discourage any attempt at tinkering with the database API (therefore, nolink is included) !
Assuming that what you aim at is feasible somehow, reconsider why you do not want to expressly indicate the conversion format. The few additional keystrokes are hardly a nuisance for the developer while the idiom contributes to a self-documenting code base.
Spend your development resources more wisely than performing micro-optimizations !

Would you abstract your LINQ queries into extension methods

On my current project we set ourselves some goals for the code metrics "Maintainability Index" and "Cyclometic Complexity". Maintainability Index should be 60 or higher and Cyclometic Complexity 25 or less. We know that the Maintainability Index of 60 and higher is a pretty high one.
We also use a lot of linq to filter/group/select entities. I found out that these linq queries aren't scoring that high on Maintainability Index.
Abstracting this queries into extension methods is giving me a higher Maintainability Index, which is good. But in most of the cases the extension methods are not generic anymore because I use them with my Types instead of generic types.
For example the following linq-query vs extension method:
Linq query
List.Where(m => m.BeginTime >= selectionFrom && m.EndTime <= selectionTo)
Extension method:
public static IEnumerable<MyType> FilterBy(this IEnumerable<MyType> source, DateTime selectionFrom, DateTime selectionTo)
{
return (IEnumerable<MyType>)source.Where(m => m.BeginTime >= selectionFrom && m.EndTime <= selectionTo);
}
List.FilterBy(selectionFrom, selectionTo);
The extension method gives me a Maintainability Index improvement of 6 points, and gives a nice fluent syntax.
On the other hand I have to add a static class, it's not generic.
Any ideas on what approach would have your favor? Or maybe have different ideas about how to refactor the linq queries to improve Maintainability Index?
You shouldn't add classes for the sake of metrics. Any metrics are meant to make your code better but following rules blindly, even the best rules, may in fact harm your code.
I don't think it's a good idea to stick to certain Maintainability and Complexity indexes. I believe they are useful for evaluating old code, i.e. when you inherited a project and need to estimate its complexity. However, it's absurd to extract a method because you haven't scored enough points.
Only refactor if such refactoring adds value to the code. Such value is a complex human metric inexpressible in numbers, and estimating it is exactly what programming experience is about—finding balance between optimization vs readability vs clean API vs cool code vs simple code vs fast shipping vs generalization vs specification, etc.
This is the only metric you should follow but it's not always the metric everyone agrees upon...
As for your example, if the same LINQ query is used over and over, it makes perfect sense to create an EnumerableExtensions in Extensions folder and extract it there. However, if it used once or twice, or is subject to change, verbose query is so much better.
I also don't understand why you say they are not generic with somewhat negative connotations. You don't need generics everywhere! In fact, when writing extension methods, you should consider the most specific types you can choose as to not pollute other classes' method set. If you want your helper to only work with IEnumerable<MyType>, there is absolutely no shame in declaring an extension method exactly for this IEnumerable<MyType>. By the way, there's redundant casting in your example. Get rid of it.
And don't forget, tools are stupid. So are we, humans.
My advice to you would be ... don't be a slave to your metrics! They are machine generated and only intended to be used as guidance. They are never going to be a replacement for a skilled experienced programmer.
Which do you think is right for your application?
I for one agree with the extension method strategy. I've used it without a problem in a handful of real-world apps.
To me, it is not only about the metrics, but also the re-usability of the code there. See the following psuedo-examples:
var x = _repository.Customers().WhichAreGoldCustomers();
var y = _repository.Customers().WhichAreBehindInPayments();
Having those two extension methods accomplishes your goal for metrics, and it also provides "one place for the definition of what it is to be a gold customer." You don't have different queries being created in different places by different developers when they need to work with "gold customers."
Additionally, they are composable:
var z = _repository.Customers().WhichAreGoldCustomers().WhichAreBehindInPayments();
IMHO this is a winning approach.
The only problem we've faced is that there is a ReSharper bug that sometimes the Intellisense for the extension methods goes crazy. You type ".Whic" and it lets you pick the extension method you want, but when you "tab" on it, it puts something completely different into the code, not the extension method that you selected. I've considered switching from ReSharper for this, but... nah :)
NO: in this case I would ignore the cyclomatic complexity - what you had originally was better.
Ask yourself what is more explanatory. This:
List.Where(m => m.BeginTime >= selectionFrom && m.EndTime <= selectionTo)
or this:
List.FilterBy(selectionFrom, selectionTo);
The first clearly expresses what you want, whereas the second does not. The only way to know what "FilterBy" means is to go into the source code and look at its implementation.
Abstracting query fragments into extension methods makes sense with more complex scenarios, where it's not easy to judge at a glance what the query fragment is doing.
I have used this technique in places, for example a class Payment has a corresponding class PaymentLinqExtensions which provides domain specific extensions for Payments.
In the example you give I'd choose a more descriptive method name. There is also the question of whether the range is inclusive or exclusive, Otherwise it looks OK.
If you have multiple objects in your system for which the concept of having a date is common then consider an interface, maybe IHaveADate (or something better :-)
public static IQueryable<T> WithinDateRange(this IQueryable<T> source, DateTime from, DateTime to) where T:IHaveADate
(IQueryable is interesting. I don't think IEnumerable can cast to it which is a shame. If you're working with database queries then it can allow your logic to appear in the final SQL that is sent to the server which is good. There is the potential gotcha with all LINQ that your code is not executed when you expect it to be)
If date ranges are an important concept in your application, and you need to be consistent about whether the range starts at midnight on the end of "EndDate" or midnight at the start of it, then a DateRange class may be useful. Then
public static IQueryable<T> WithinDateRange(this IQueryable<T> source, DateRange range) where T:IHaveADate
You could also, if you feel like it, provide
public static IEnumerable<T> WithinDateRange(this IEnumerable<T> source, DateRange range, Func<DateTime,T> getDate)
but this to me feels more something to do with DateRange. I don't know how much it would be used, though your situation may vary. I've found that getting too generic can make things hard to understand, and LINQ can be hard to debug.
var filtered = myThingCollection.WithinDateRange(myDateRange, x => x.Date)

IDataReader from Oracle Overflows when returning decimal values

I have some code that is responsible for converting data from an IDataReader into an IronPython.Runtime.List of PythonTuples. This same code is employed for several different kinds of database connections (including Access, Oracle and MySql).
Oracle's OracleDecimal datatype causes an overflow when calling dataReader.GetValues() when the cursor contains a value with a large precision. This issue has been well documented, and the solutions always involve using specific methods on the OracleDataAdapter. I only have an IDataReader interface.
Is there any way around this issue without binding my code specifically to ODP.NET? Surely there must be some way to get at this data in a provider-agnostic way?
The only provider agnostic method that I am aware of is to round the values in your select statement. I've found that rounding to 15 decimal places usually does the trick.
It may not be exactly what you're looking for, but the System.Data.Common.DbDataReader class has a GetProviderSpecificValues function that may do what you want

LINQ string compare in VB when using NHibernate

Come across an issue when doing a string compare as part of the where section of a linq expression against LINQ for NHibernate.
from x in NhibernateObject
where x.StringCol = "value"
select x
When it runs it retrns a runtime error about casting to an integer. I found a nice post about the issue and the solution at http://jason.pettys.name/archive/2009/09/28/nhibernate-with-linq-error-with-string-comparisons-in-vb.net.aspx
But my question is what is a "visitor" and what code would I write to achive the solution highlighted in the above post - missing the link here !!!
Visitor is a design pattern. You can find a description of it here http://www.dofactory.com/Patterns/PatternVisitor.aspx or here http://en.wikipedia.org/wiki/Visitor_pattern
If I correctly understand the article you linked to (haven't read it fully), then it is required to change NHibernate to work around this problem.
The definition of the visitor pattern is: "Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new
operation without changing the classes of the elements on which it operates."
The namespace of the visitor(s) you want to change is NHibernate.Linq.Visitors. You will probably have more difficulties using VB instead of C# with NHibernate.Linq, because VB3 does not support everything c#3 does. Those problems will be solved if you use .Net 4.0 (or c# of course)

Is there an application for displaying some kind of query plan for a Linq to object query?

I'm looking for an application to display what a linq expression would do, in particular regarding the usage of multiple access to the same list in a query.
Better yet, the tool would tell if the linq query is good.
I used the expression tree visualizer in the past to at least help decode what is inside of an expression tree. It aids in figureing out the parts of the tree and how gives each part is related.
Well, to begin with, I could easily foresee a tool that would pick a query apart and detect that the Where-clause is the standard runtime implementation, and thus not examine that method, but "know" what the execution plan for that method would be, and could thus piece together a plan for the whole query.
Right up until the point where you introduce a custom Linq provider, where the only way to figure out what it will be doing would be to read the code.
So I daresay there is no such tool, and making one would be very hard.
Would be fun to try though, at least for standard classes, would be a handy debugging visualizer for Visual Studio.
What about making the tool yourself?! ;)
Take a look at Expression trees, I believe they might be useful

Resources