kenegozi.com

<form id='kenegozi' action='post'></form>

   
2008 May 9

Using nhibernate's named queries with ActiveRecord

tagged as: castle | activerecord | nhibernate | hql

One of the methods of querying the DB when using NHibernate, is to issue HQL queries. HQL stands for "Hibernate Query Language". It has a SQL-like syntax and is very intuitive for people with SQL background.

 

The way this works is that NHibernate 'compiles' the HQL query into SQL, and then issues the SQL query (using ADO.NET's facilities) to the DB.

 

Sounds pricey?

enter Named Queries.

now these are HQL (or SQL) queries, each has a name (obviously), that are been supplied to NH through the mapping. The queries are being translated and cached as IDbCommand objects as part of the framework initialisation, which mean that you get rid of the HQL->SQL overhead throughout the life of the process.

 

One other major benefit, is that the mechanism to actually execute these named queries, does not differentiate between HQL and SQL queries (for the simple fact that these queries have already been transferred to SQL at runtime). That gives you the possibility to replace HQL queries into tighter SQL queries (with the same parameters and which returns the same resultset) should your DBA figure out a better one.

 

But if you're using ActiveRecord, you usually do not have direct access into the mapping (.hbm) files. So how would you use named queries with AR?

 

enter HqlNamedQueryAttribute (not such a great name, as I did state that it would also work for SQL queries).

 

So, for an example, on this blog's source code, within PostRepository.cs you'd see this code:

...

 

#region queries
[assembly: HqlNamedQuery(Queries.FindPostsInArchive, Queries.FindPostsInArchive)]
[assembly: HqlNamedQuery(Queries.FindByUrlFriendlyTagName, Queries.FindByUrlFriendlyTagName)]
namespace KenEgozi.Com.Domain
{
    internal partial class Queries
    {
        internal const string FindPostsInArchive = @"
                from Post p
                where
                    year(p.Lifecycle.CreationDate) = :year and
                    month(p.Lifecycle.CreationDate) = :month
                order by p.Lifecycle.CreationDate desc";
        internal const string FindByUrlFriendlyTagName = @"
                select p
                from
                            Post p
                    join    p.Tags t
                where t.UrlFriendlyName like :urlFriendlyTagName
                order by p.Lifecycle.CreationDate desc;";
    }
}
#endregion

...

 

        public ICollection<Post> FindInArchive(int year, int month)
        {

            return session
                .GetNamedQuery(Queries.FindPostsInArchive)
                .SetParameter("year", year)
                .SetParameter("month", month)
                .List<Post>();
        }

...

Queries class is marked as partial, as other queries might be presented on other repositories or services that would need to add more named queries. I considered grouping of queries into groups by the using repository, or by aggregate roots, but the thing is - having all of the queries under the same namespace helps discoverability, and helps with preventing duplications

2008 May 8

50% up in four months

tagged as: personal

Wow, it feels like yesterday.

On last December, the feedburner's subscribers count on this blog has first reached 200.

 

Two weeks ago I've noticed that:

 

300

 

 

Silly, useless, but pats a certain shoulder nonetheless.

2008 May 8

Box Model recap - this time in Hebrew

tagged as: client-side | css | html

Over two year ago, I have posted about the un-orthodox box model that IE6 is using

Yesterday I saw that Ohad Aston (an Israeli Web developer who blogs in Hebrew at the Israeli MSDN blogs site) has written a Hebrew explanation to the same phenomena, so if you do web, especially using ASP.NET and can read Hebrew, I recommend that you take a peek. And if you're there, subscribe to his RSS. I did.

2008 Apr 29

AspView and C#3.0

tagged as: c# | aspview

MonoRail runs on .NET 2.0. AspView is no different, and is compiled for .NET 2.0, so people who cannot run 3.5 (shared hosting, other limitations) can still enjoy every shining new feature.

 

However, if you DO want to use c#3 stuff in view templates (like extension methods), then you can. Thanks to Felix Gartsman, the AspView compiler would try to load the c# compiler based on the codedom section of the application .config file.

 

So, if you're using autorecompilation=true, the add this to your web.config:

<system.codedom>
  <compilers>
    <compiler  language="c#;cs;csharp"
               extension=".cs"
               type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
               warningLevel="4">
      <provideroption value="v3.5" name="CompilerVersion" />
      <provideroption value="false" name="WarnAsError" />
    </compiler>
  </compilers> </system.codedom>

 

If you want to precompile your views, then add the same to vcompile's app.config.

2008 Apr 27

Javascript WTF

tagged as: miscellanea

This is a piece of screenshot that you probably hopefully won't see on sites I'm involved with:

document.write WTF

2008 Apr 27

Wacky JET syntax for UPDATE FROM

tagged as: SQL Server

Today I've given a little help to a friend, with a JET 4.0 (Ms-ACCESS) thing.

 

Situation

Given an existing schema:

  Customers (Id, Name, ..., Email)
  Ads (CustomerId, ...)

the client wanted to add a field name TargetEmail to Ads table.

Adding the field was simple enough:

ALTER TABLE Ads ADD COLUMN TargetEmail TEXT(255)

Now the client wanted to initialise the TargetEmail field for existing ads, based on the Customer's email.

A Naive and SQL Server jockey as I am, I gave him that little snippet:

UPDATE   Ads 
SET Ads.TargetEmail = Customers.Email
FROM Ads
JOIN Customers ON Ads.CustomerId = Customers.Id
WHERE Ads.TargetEmail IS NULL
 
 
Problem

JET had refused that syntax.

Or rather, Jet is weird.

 

 

Solution

Google to the rescue. answer was here.

UPDATE  Ads, 
Customers
SET Ads.TargetEmail = Customers.Email
WHERE Ads.CustomerId = Customers.Id
AND Ads.TargetEmail IS NULL
2008 Apr 16

Daily Error WTF

tagged as: miscellanea

Error - The current browser is either too old or too modern

 

All I wanted was to find a decent hotel in Barcelona, with the aid of my buddy Firefox

 

(from http://www.mygrouptour.com/)

2008 Apr 7

On Flying, Driving and Programming

tagged as: miscellanea

Let's talk about these three activities, or rather on aspects of them.

 

Assuming one want to get from London to Cambridge, by car. The directions would be something like "Take the M11 to north, leave at Junction 12 toward Cambridge and you're there".

One might require slightly more explicit instruction, such as "To get to the M11, you'd need to leave the M25 on junction 27", or "On junction 12 you'd want to turn to the right toward Cambridge".

At no point would someone need to be told to "Turn the steering wheel to the right" or "Do not forget to use the clutch when changing gears".

 

When driving, there are:

  • intention:
    either implicit ("Leave ... toward Cambridge") or explicit ("you'd want to turn to the right toward Cambridge")
  • mechanics:
    Turn the steering wheel, use the clutch
  • infrastructure:
    The steering wheel's movement is transferred to the front wheels, which turn to the desired side, then the various physic powers are causing the car to make the turn

 

When flying a small aircraft, there are several things that affect it's movement:

There's the Elevator which affects horizontal shifts, controlled by the moving the stick backwards and forwards.

There are the Ailerons which generates rolling motion, and controlled my moving the stick sideways.

There is the Rudder which controls the nose position, and controlled by kicking pedals with the pilot's feet.

And on single motored aircraft, even changing the engine's speed affects the "steering" as the radial movement of the propeller is inflicting different airflow on the wings, causing a slight difference in the elevation.

However, flight directions include things like "Fly to point A, use bearing X, keep altitude Y". At most, a flying student would be told to keep the aircraft's Nose at a specific position in the Horizon.

I remember that in flight school, when we were being taught about simple manoeuvres, the language used by the instructors was of the implicit intention kind. However, there was a guy that kept asking "so what am I supposed to do with the stick now?". He of course was one of the first to be kicked out of there.

 

All of the above apply to programmers, too.

 

In forums and mailing lists, sometimes someone asks a question, that gets answered with the needed intention, but that someone keeps asking for the exact mechanics. For example:

Q: How can disable the controls on a web page after a certain button click?
A (implicit intention): Hide the whole page with another, transparent element.

Q: How do I do that?
A (explicit intention): Use DOM manipulation and DHTML to add a div with the size of the entire page, positioned over the page.

Q: How do I do that?

A (more explicit): some pseudo code.

Q: I tried to run this code you've sent but it throws errors. Can you please send me the correct code?
A (mechanics): function disableControls() { ... }

 

You get the point, right?

 

If not?

a. When asking for help, expect to get the intention. That usually should be enough.

b. If you really can't figure out the code (at least to create an 'almost working' implementation) out of intention, then you probably are in the wrong business.

 

As for infrastructure - a driver does not have to know anything about Newton's Laws of Motion. However a professional racing driver has to understand the basics of that in order to be as good as he needs to. And definitely not being troubles by the angle of the steering wheel. That should become naturally. Just as transferring intentions into working code should come naturally for a programmer.

2008 Apr 7

git-self take two: git-hub key configuration

tagged as: Source Control

After failing to setup git access to my newly created repository on git-hub, I managed to nail the problem, thanks to Lee Henson's good advice (and by re-reading the hint text)

After generating the public key (with puttygen) I copied to git-hub only the key itself (the HEX part), while I was also supposed to copy the text surrounding it, as can be seen in the image below:

 

public rsa key

 

 

Copy + Paste => now it works
2008 Apr 4

Cannot explicitly convert System.Boolean to bool VS2008 WTF

tagged as: visual studio

I've just opened up a VS2005 solution in VS2008.

The conversion wizard popup up, with some bad UI (empty window with "Next", "Finish", "Cancel" buttons), but it worked ok, and at the end suggested that no errors occured.

 

Then I went to the project's properties and changed the target to .NET 3.5

 

VS told me that he had to reload the project, so I let him.

 

then I started to get weird errors in the IDE:

  1. Cannot explicitly convert System.Boolean to bool VS2008
  2. Cannot apply operator ++ to identifier of type int

 

huh?

 

anyway, closing the solution and re-opening made this weird happening go away.

 

And I thought I'm about to go back to vs2005 ...

2008 Apr 3

Logging SQL output from NHibernate, using Log4Net

tagged as: tools | nhibernate

Following a question from NHibernate's users list:

<configSections>
  <section name="log4net"
            type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
 
<log4net>
  <appender name="rollingFile"
            type="log4net.Appender.RollingFileAppender,log4net" >
    <param name="File" value="log.txt" />
    <param name="AppendToFile" value="true" />
    <param name="DatePattern" value="yyyy.MM.dd" />
    <layout type="log4net.Layout.PatternLayout,log4net">
      <conversionPattern value="%d %p %m%n" />
    </layout>
  </appender>
  <logger name="NHibernate.SQL">
    <level value="ALL" />
<appender-ref ref="rollingFile" />
</logger>
</log4net>

and configuring your application to use Log4Net (if you hadn't done that anyway):

 

log4net.Config.XmlConfigurator.Configure();

 

If you wan't to know more about log4net and it's configuration options - look here or use your favorite search engine.

2008 Apr 3

"Don't use bold, please use strong, cuz if you use bold it's old and wrong"

tagged as: client-side | css | html | miscellanea

Another quote:

Please don't use table even though they work fine,
when it comes to indexing they give searches a hard time

and also

Check in all browsers, I do it directly,
You got to make sure that it renders correctly

This should be in the curriculum for any webmasters 101 course

 

2008 Apr 1

git-self take one

tagged as: Source Control

Now that I'm getting old, I need to keep up with the cool kids, so I'm taking git for a spin.

 

Downloaded MSys Git.

Upon install I went for the git-bash option.  Running the bash shell has reminded my some of the old unix memories, however I am much more comfy with the windows shell these days, so I have manually added the the path things needed for running in cmd.exe/f

 

Now it was time to test remote. Luckily enough I got a git-hub invitation.

 

Step 1 - signup to git-hub.

downloaded the newest putty, then used puttygen to generate public and private key.

 

Step 2 - create a private repository - went smoothly.

 

Step 3 - trying to push to the remote repo.

I ran the PAGEANT.EXE tool, loaded it with the private key, and set the GIT_SSH environment variable to point to PLINK.EXE.

Then tried to "git push origin master" and got a message like "The server's key signature is not in the registry, press 'y' for storing in the registry, 'n' for skipping, 'return' to exit". the problem is - it got stuck, no input allowed except ctrl-C.

 

Then I tried to putty directly to the server, and now it did let me press the y, hoora - server's public key's signature is stored.

You'd think could push to the repository? think again. I then started getting other weird errors like "No supported authentication methods available".

 

grrrrr.

 

Maybe Ill try again tomorrow.

 

UPDATE (07/04/2008 - I guess tomorrow is a flexible term these days ...):
It was me being silly. Now it works perfectly

2008 Mar 25

Happy Birthday to ... ME

tagged as: personal

30, that is.

 

I've been snatched to birthday dinners all week, like it's not enough that Im on the most full-of-work time of my life. Non-urgent things (like improving AspView or taking a shower) got pushed aside. Just kidding, AspView is important enough ...

 

Sarit took me on a surprise vacation.

 

Mt. Hermon, view from Kefar Giladi:

Mt. Hermon, view from Kefar Giladi

 

Grotto at Rosh-Hanikra:
Grotto in Rosh-Hanikra

 

That's me at the Zavitan pools next to the waterfall:

אני בזויתן 2

 

 

As for "next year resolutions" - hmm, I did not put much thought in that so I'm just scribbling:

1. Complete the bachelor's degree. High time I did that;

2. Give at least three talks. I really enjoy sharing knowledge, and it also pushes me to know more on things I consider myself proficient in. First talk is already scheduled for 14 May, at "The Developers Group" meeting on Microsoft Victoria, London UK. I hope there'd more to come;

3. Delve into Silverlight 2.0;

4. Learn F#;

5. Increase my NHibernate skills;

6. Find time to contribute to Linq For NHibernate;

7. Continue pushing Castle forward. The whole stack. It's just great;

8. Do more sports (cycling and/or swimming);

2008 Mar 12

String.replace != String.Replace

tagged as: client-side

I have a html tag (image input) with id that looks like "delete-party-image".

On click, it should call XHR-ly to a server action, named DeletePartyImage.

Naively I did

var action = btn.id.replace('-', '');

which of course returned "deleteparty-image", because, as opposed to .NET's String object's Replace() method, this one (javascript's String.replace) only replaces the first occurrence.

Yeah, I already knew that, but have forgot it just when I needed it.

So for next time's sake - the way to do it in javascript is using a regex with global modifier:

var action = btn.id.replace(/-/g, '');
2008 Mar 9

AgentSmith - Resharper plugin

tagged as: visual studio | c# | tools

From the website:

Current version includes following features:

  • Naming convention validation.

  • XML comment validation.

  • XML comment, string literals, identifiers and resources (.resx files) spell checking

  • Smart paste.

The coolest thing is the ability to spell check identifiers. I'd love it.

 

It's at http://www.agentsmithplugin.com/ and I found out about it on Castle's dev list (thx Victor)

2008 Mar 6

The Only "ASP.NET MVC Preview 2 Announcement" Post You'd Want To Read

tagged as: asp.net ajax

It seam like every one (now including me) is posting excitingly about the new preview of ASP.NET MVC.

 

Probably to get traffic or whadever.

 

Most of those goes like "I usually do not do this, but hey- here's the link".

 

Justice Gray's post is different.

 

btw, as you are all excited about it, I'd use that to point you to something quite similar, more mature, that lets you "easily build MVC based applications in ASP.NET with routing, intellisense, and total joy, not to mention that it runs on .NET 2.0 " - that would be the MonoRail thing, preferably (by me and a few others) accompanied by AspView.

 

And since I didn't put the MVC p2 link here, I won't link to MonoRail and AspView. After all, if you're reading this, you probably have those links in your favorites ...

2008 Mar 4

[Tool] - Visual XPath

tagged as: tools

As I'm trying to avoid xml files as much as possible, when I do find the need to xpath, I always need to refresh my memory on the matter.

 

Today I've been working with kml files, and the need for some simple xpath queries came up, forcing me to do some trial-and-error in an area I don't really like ...

 

Next time I'll have Visual XPath to help me with that.

2008 Mar 4

The strength to document the complex

tagged as: castle

Another funny quote from Castle dev list:

Ayende (after a discussion on the lack of DynamicProxy documentation):
Yes, the underlying assumption that by the time you are done understanding DP you don't have the strength to write docs.

 

If you wanna grok that, then you can look at a small snippet from DP2 code on the blog's title, or browse the repo

Subscribe

Statistics

256
370

Related Books

Related Jobs

Related Ads

search page | Blog's home | About me