Can I customize collation of query results in nHibernate? - nhibernate

In plain old SQL, I can do something like this:
select * from mytable COLLATE Latin1_General_CS_AS
Is there a way to specify the type of collation I want to use for a given query in nHibernate, in HQL or in criteria?

Germán Schuager has managed to specify collation at run time. Take a look here.
var user = session.CreateCriteria(typeof (User))
.Add(Expression.Sql("Username like ? collate Modern_Spanish_CS_AS", username, NHibernateUtil.String))
.UniqueResult<User>();

From the same link than rebelliard answer provide, Shuager also supplies a way to define a custom function for doing something similar. This has the advantage of being usable in HQL too.
His custom function implementation was too specific for your question and my own needs, so here is the implementation I have ended with:
/// <summary>
/// Customized dialect for allowing changing collation on <c>like</c> statements.
/// </summary>
public class CustomMsSqlDialect : MsSql2008Dialect
{
/// <summary>
/// Default constructor.
/// </summary>
public CustomMsSqlDialect()
{
RegisterFunction("withcollation",
new WithCollationFunction());
}
}
/// <summary>
/// Add collation to string argument.
/// </summary>
[Serializable]
public class WithCollationFunction : SQLFunctionTemplate, IFunctionGrammar
{
/// <summary>
/// Default constructor.
/// </summary>
public WithCollationFunction()
: base(NHibernateUtil.String, "?1 collate ?2")
{
}
bool IFunctionGrammar.IsSeparator(string token)
{
return false;
}
bool IFunctionGrammar.IsKnownArgument(string token)
{
return Regex.IsMatch(token, "[A-Z][A-Z0-9_]+_(?:CS|CI)_(?:AS|AI)(?:_KS)?(?:_WS)?", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
}
Mind the dialect base class, I have used 2008 dialect, you may wish to change that.
Do not forget to change your HQL dialect to your new custom dialect (using "dialect" configuration property of your session-factory for instance).
Example usage in HQL, standard query without collation customization :
from Cat as c
where c.Name like 'fel%'
With custom collation
from Cat as c
where c.Name like withCollation('fel%', French_CI_AI)
Works with Nhib 3.2.

Related

Fluent NHibernate Conventions : OptimisticLock.Is(x => x.Version()) doesn't work

I am having problems with using OptimisticLock as a Convention.
However, using OptimisticLock within Individual ClassMap's works fine. It throws Stale State Object Exceptions.
Each Class corresponding to a Table in the database has a property (which corresponds to a Column in the Table) of type DateTime which I am trying to use for Locking using OptimisticLock.Version().
It works only when I use it within every ClassMap, I don't want to write so many ClassMaps, I instead want to use Auto Mapping.
It WORKS like this within the Class Map
Version(x => x.UpdTs).Column("UPD_TS");
OptimisticLock.Version();
So, I started using Convention below, but it DOESN'T WORK.
OptimisticLock.IsAny(x => x.Version());
I tried setting the DynamicUpdate, etc. Nothing seems to work for me.
Please help !
Here's what I did to get it work using a Convention :
/// <summary>
/// Class represents the Convention which defines which Property/Column serves as a part of the Optimistic Locking Mechanism.
/// </summary>
public class VersionConvention : IVersionConvention, IVersionConventionAcceptance
{
public void Accept(IAcceptanceCriteria<IVersionInspector> criteria)
{
criteria.Expect(x => x.Name == "%COLUMN_NAME%");
}
/// <summary>
/// Method applies additional overrides to the <see cref="IVersionInstance"/>
/// </summary>
/// <param name="instance"><see cref="IVersionInstance"/></param>
public void Apply(IVersionInstance instance)
{
instance.Column("%COLUMN_NAME%");
}
}
%COLUMN_NAME% above is the Property being used for Locking using Version.
Then specified that the Version should be used for Optimistic Locking, when creating a FluentConfiguration Object, like this
OptimisticLock.Is(x => x.Version();

Moq - Is it possible to specify in a Setup the Verify criteria (e.g. Times called)?

If you need to Setup a return value, as well as Verify how many times the expression was called, can you do this in one statement?
From what I can gather, Moq's Setup(SomeExpression).Verifiable() called along with Verify(), basically does a Verify(SomeExpression, Times.AtLeastOnce)? i.e. it verifys the expression was called only.
Here's an example to explain the question better. For an interface:
interface IFoo
{
int ReturnSomething();
}
Are the following two blocks equivalent (other than the first will Verify all setups marked as verifiable)?
void Test()
{
var mock = new Mock<IFoo>();
mock.Setup((m) => m.ReturnSomething()).Returns(1).Verifiable();
mock.Verify();
}
and
void Test()
{
var mock = new Mock<IFoo>();
mock.Setup((m) => m.ReturnSomething()).Returns(1);
mock.Verify((m) => m.ReturnSomething(), Times.AtLeastOnce());
}
If I wanted to verify the number of calls (say twice), is this the only way, where the expression is repeated for the Setup and Verify?
void Test()
{
var mock = new Mock<IFoo>();
mock.Setup((m) => m.ReturnSomething()).Returns(1);
mock.Verify((m) => m.ReturnSomething(), Times.Exactly(2));
}
I just don't like having to call Setup and Verify. Well, since this is a good idea for AAA, to rephrase, I don't like having to repeat the expression for the Setup and Verify. At the moment I store the expression in a variable and pass it to each method, but doesn't feel so clean.
PS - The context for this is for a test checking when a cache is updated or not (expirations etc.)
I have this problem all the time. I use strict mocks, and I want to specify strictly (i.e. I used It.Is<>() instead of It.IsAny()) as well as verify strictly (i.e. specifying Times). You cannot use verifiable for this sadly, because Moq is missing a Verifiable(Times) overload.
The full expression of the call, including It.Is<>() is generally big. So in order to avoid duplication I generally resort to the following:
Expression<Action<MockedType>> expression = mockedTypeInstance => mockedTypeInstance.MockedMethod(It.Is<TFirstArgument>(firstArgument => <some complex statement>)/*, ...*/);
_mock.Setup(expression);
/* run the test*/
_mock.Verify(expression, Times.Once);
Not extremely readable, but I don't think there is another way to both use strict setup and strict verification.
To answer the first question, yes the two blocks are equivalent. Both will fail when .Verify is called if the method on the mock wasn't called.
You can't specify the verify up front as far as I am aware and if you think about it, it makes sense.
This is specifying the behavior of the mock:
mock.Setup(m => m.ReturnSomething()).Returns(1);
This is verifying the behavior of the caller:
mock.Verify(m => m.ReturnSomething(), Times.AtLeastOnce());
Personally I prefer calling verify individually to confirm the required behavior of the caller, the .Verifiable() and .Verify() are shortcuts that are less strict (they just check the method was called one or more times) however if you know your code should only call a method once, put the verify in at the end to confirm it.
I started doing that after a code merge resulted in a method being called twice, the test still passed since it was called at least once but it also meant that something else happened multiple times which shouldn't have!
Expounding on the answer by Evren Kuzucuoglu, I created the following extension methods to make creating the expressions a little simpler:
/// <summary>
/// Creates a method call expression that can be passed to both <see cref="Setup"/> and <see cref="Verify"/>.
/// </summary>
/// <typeparam name="T">Mocked object type.</typeparam>
/// <param name="mock">Mock of <see cref="T"/>.</param>
/// <param name="expression">Method call expression to record.</param>
/// <returns>Method call expression.</returns>
public static Expression<Action<T>> CallTo<T>(this Mock<T> mock, Expression<Action<T>> expression) where T : class
{
return expression;
}
/// <summary>
/// Creates a method call expression that can be passed to both <see cref="Setup"/> and <see cref="Verify"/>.
/// </summary>
/// <typeparam name="T">Mocked object type.</typeparam>
/// <typeparam name="TResult">Method call return type.</typeparam>
/// <param name="mock">Mock of <see cref="T"/>.</param>
/// <param name="expression">Method call expression to record.</param>
/// <returns>Method call expression.</returns>
public static Expression<Func<T, TResult>> CallTo<T, TResult>(this Mock<T> mock, Expression<Func<T, TResult>> expression) where T : class
{
return expression;
}
Usage example:
var createMapperCall = mockMappingFactory.CallTo(x => x.CreateMapper());
mockMappingFactory.Setup(createMapperCall).Returns(mockMapper.Object);
mockMappingFactory.Verify(createMapperCall, Times.Once());
I created a utility class that takes care of this:
public class TestUtils
{
private static List<Action> verifyActions = new List<Action>();
public static void InitVerifyActions() => verifyActions = new List<Action>();
public static void VerifyAllSetups()
{
foreach (var action in verifyActions)
{
action.Invoke();
}
}
public static ISetup<T> SetupAndVerify<T>(Mock<T> mock, Expression<Action<T>> expression, Times times) where T : class
{
verifyActions.Add(() => mock.Verify(expression, times));
return mock.Setup(expression);
}
public static ISetup<T, TResult> SetupAndVerify<T, TResult>(Mock<T> mock, Expression<Func<T, TResult>> expression, Times times) where T : class
{
verifyActions.Add(() => mock.Verify(expression, times));
return mock.Setup(expression);
}
}
Then in TestInitialize(), I call TestUtils.InitVerifyActions(), and in the unit tests:
TestUtils.SetupAndVerify(myMock, m => m.Foo("bar"), Times.Once()).Returns("baz");
TestUtils.SetupAndVerify(myOtherMock, m => m.Blah(), Times.Once());
...
TestUtils.VerifyAllSetups();
While far from enough Moq indeed has the AtMost() and AtMostOnce() methods on the Setup call, however it is marked as Obsolete, but it appears to be a mistake according to this GitHub issue

Singleton Data Access Object (Dao) & SQL Helper Instance, Is here any Performance drawback?

I need comments from Experts. I write my own SQL Helper Class to Communicate with DB.
Why I use it as because I try to
Encapsulate the Ado.Net logic.
Try to set a common standard for my developer in terms of DAL coding.
Flexible & Easy to use.
Same kind of code block for SQL Server/ Oracle / Access / Excel / Generic Database code block approach (SQL Server & Oracle) e.t.c.
Plug & Play or Reusable approach.
In terms of code optimization
This helper class or Assembly is CLS Compliant.
It pass Successfully by FxCop / Static Code Analysis.
I give you the sample Code Block (DAO). Please check bellow
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
#region include SQL Helper Namespace
using DBManager;
#endregion
#region include SQL Helper Namespace
using DBManager;
#endregion
namespace ContentManagementSystem.DataAccessLayer
{
/// <summary>
///
/// </summary>
public sealed class DaoContentOwner : DataAccessBase
{
#region CONSTRUCTOR
/// <summary>
///
/// </summary>
private DaoContentOwner()
{
GetInstance = new DaoContentOwner();
}
#endregion
//############################################# M E T H O D S ##########################
#region Retrieve Content Owner
/// <summary>
/// Retrieve Content Owner
/// </summary>
/// <returns></returns>
public static DataTable RetrieveContentOwner()
{
DataTable dt = null;
try
{
using (DBQuery dq = new DBQuery("stpGetContentOwner"))
{
dt = dq.ResultSetAsDataTable();
return dt;
}
}
catch (Exception)
{
throw;
}
finally
{
if (dt != null)
{
dt.Dispose();
}
}
}
#endregion
//############################################# P R O P E R T Y ########################
#region READ ONLY PROPERTY
/// <summary>
/// GetInstance of DaoContentOwner Class
/// </summary>
public static DaoContentOwner GetInstance { get; private set; }
#endregion
}
}
Justification:
"DataAccessBase" It is a Abstract class. Implement IDisposable Interface.
"DBQuery" is SQL Helper for SQL Server Only. It is a Sealed class. It is takes T-SQL / SP according to needs. Open an close database connection. No need to handel any thing by developer.
Why I make DAO Singleton Class, Because my all the methods withing DAO is a static method. I order to memory optimization I make it Singleton. It is also a design Principal.
Note: Needs comments. Whether need to change in the design or some thing is wrong that need to correct.
Personally I would go with:
DALFileItem dalF = new DALFileItem(DSN);
List<FileItem> list = dalF.GetAll("");
Allows accessing multiple databases, without making DSN static member.
In multithreaded environment only one thread will have access to the static method.
More object oriented: you can add interfaces, base classes and generics easier that way.

NHibernate (3.1.0.4000) NullReferenceException using Query<> and NHibernate Facility

I have a problem with NHibernate, I can't seem to find any solution for.
In my project I have a simple entity (Batch), but whenever I try and run the following test, I get an exception.
I've triede a couple of different ways to perform a similar query, but almost identical exception for all (it differs in which LINQ method being executed).
The first test:
[Test]
public void QueryLatestBatch()
{
using (var session = SessionManager.OpenSession())
{
var batch = session.Query<Batch>()
.FirstOrDefault();
Assert.That(batch, Is.Not.Null);
}
}
The exception:
System.NullReferenceException : Object reference not set to an instance of an object.
at NHibernate.Linq.NhQueryProvider.PrepareQuery(Expression expression, ref IQuery query, ref NhLinqExpression nhQuery)
at NHibernate.Linq.NhQueryProvider.Execute(Expression expression)
at System.Linq.Queryable.FirstOrDefault(IQueryable`1 source)
The second test:
[Test]
public void QueryLatestBatch2()
{
using (var session = SessionManager.OpenSession())
{
var batch = session.Query<Batch>()
.OrderBy(x => x.Executed)
.Take(1)
.SingleOrDefault();
Assert.That(batch, Is.Not.Null);
}
}
The exception:
System.NullReferenceException : Object reference not set to an instance of an object.
at NHibernate.Linq.NhQueryProvider.PrepareQuery(Expression expression, ref IQuery query, ref NhLinqExpression nhQuery)
at NHibernate.Linq.NhQueryProvider.Execute(Expression expression)
at System.Linq.Queryable.SingleOrDefault(IQueryable`1 source)
However, this one is passing (using QueryOver<>):
[Test]
public void QueryOverLatestBatch()
{
using (var session = SessionManager.OpenSession())
{
var batch = session.QueryOver<Batch>()
.OrderBy(x => x.Executed).Asc
.Take(1)
.SingleOrDefault();
Assert.That(batch, Is.Not.Null);
Assert.That(batch.Executed, Is.LessThan(DateTime.Now));
}
}
Using the QueryOver<> API is not bad at all, but I'm just kind of baffled that the Query<> API isn't working, which is kind of sad, since the First() operation is very concise, and our developers really enjoy LINQ.
I really hope there is a solution to this, as it seems strange if these methods are failing such a simple test.
EDIT
I'm using Oracle 11g, my mappings are done with FluentNHibernate registered through Castle Windsor with the NHibernate Facility.
As I wrote, the odd thing is that the query works perfectly with the QueryOver<> API, but not through LINQ.
There is an issue with the current implementation of the LINQ extensionmethods for NHibernate 3.1.0.4000 used together with NHibernate Facility 2.0RC (and previous versions) (see: https://nhibernate.jira.com/browse/NH-2626 and discussion here: http://groups.google.com/group/castle-project-devel/browse_thread/thread/ac90148a8d4c8477)
The fix I am using at the moment is to simply ignore the LINQ extensionmethods provided by NHibernate and create it myself. They're really just one-liners:
public static class NHibernateLinqExtensions
{
/// <summary>
/// Performs a LINQ query on the specified type.
/// </summary>
/// <typeparam name="T">The type to perform the query on.</typeparam>
/// <param name="session"></param>
/// <returns>A new <see cref="IQueryable{T}"/>.</returns>
/// <remarks>This method is provided as a workaround for the current bug in the NHibernate LINQ extension methods.</remarks>
public static IQueryable<T> Linq<T>(this ISession session)
{
return new NhQueryable<T>(session.GetSessionImplementation());
}
/// <summary>
/// Performs a LINQ query on the specified type.
/// </summary>
/// <typeparam name="T">The type to perform the query on.</typeparam>
/// <param name="session"></param>
/// <returns>A new <see cref="IQueryable{T}"/>.</returns>
/// <remarks>This method is provided as a workaround for the current bug in the NHibernate LINQ extension methods.</remarks>
public static IQueryable<T> Linq<T>(this IStatelessSession session)
{
return new NhQueryable<T>(session.GetSessionImplementation());
}
}
Then, when I need to do a LINQ query, I just use session.Linq<EntityType>() instead of session.Query<EntityType>.
Hope it helps someone in the same situation that I was.
I found the following: http://groups.google.com/group/castle-project-users/browse_thread/thread/5efc9f3b7b5d6a08
Apparently there is an issue with the current version of the NHibernate Facility and NHibernate 3.1.0.4000.
I guess I'll just have to wait for a fix :)

How to get full intellisense tooltip comments working?

I've got some C++/CLI software which is all nice and documented in a C#'ish kind of way which means DOxygen is able to pull it out into some nice html. Is there any way I can get that same information to appear in the intellisense tool tips the way that the .net framework does?
For example, lets say this is my header file (MyApp.h):
/*************** MyApp.h ***************/
/// My namespace containing all my funky classes
namespace MyNamespace
{
using namespace System;
ref class WorldHunger;
/// A truly elegent class which solves all the worlds problems
public ref class MyClass
{
public:
/// Constructs a MyClass
MyClass()
{
}
/// <summary>Attempts to fix world hunger</summary>
/// <param name="problem">The problem to try and fix</param>
/// <returns>Whether or not the problem was solved</param>
bool FixWorldHunger( WorldHunger^ problem );
};
}
...and this it's corresponding implementation:
/*************** MyApp.cpp ***************/
#include "MyApp.h"
using namespace MyNamespace;
MyClass::MyClass()
{
}
bool MyClass::FixWorldHunger( WorldHunger^ problem )
{
bool result = false;
/// TODO: implement something clever
return result;
}
Here's what intellisense does for built in functions when I'm typing:
http://www.geekops.co.uk/photos/0000-00-02%20%28Forum%20images%29/BrokenIntellisense1.jpg
Here's what intellisense does for my own functions when I type:
http://www.geekops.co.uk/photos/0000-00-02%20%28Forum%20images%29/BrokenIntellisense2.jpg
Surely there's a way to do this?
Just to summarise, for this to work you need your comments in a compatible form:
/// <summary>
/// Retrieves the widget at the specified index
/// </summary>
/// <param name="widgetIndex">Index of the widget to retrieve.</param>
/// <returns>The widget at the specified index</returns>
Widget* GetWidget(int widgetIndex);
Then you simply right-click on the project in Visual Studio and go to properties > configuration properties > C/C++ > Output Files and change Generate XML Documentation Files to Yes.
When you rebuild your project ad import it somewhere else, you should see fully documented tooltips appear.