Login

Username

Password





Register   Reset password

This is a read-only archive of the forum.

# baldec 10/10/2008 10:57 AM
Hello there, this is your local forum questionmonkey with its latest update.

I am currently at the stage where i am about to connect the module to the DB for all the candy that comes from that. And since NHibernate seems to be the choice way to do this I have started down that path. Though the documentation on module creation dont explain field values so here comes some questions.

First of all, the generator sequence field. Obligagtory or can you skip this one and run it with the identity(1,1) attribute in the DB instead?
%id name="... 
  %generator ... /generator%
/id%

Timestamp field, obligatory or not? Does it update autoatically or does it need to be systematically set later on?

property tag, special workings of these fields? These the fields that are accessable through NHibernate?

Mappings are only required if you have constraints between different tables I assume.

bag... what is this tag?


And there comes the first forum monkey questions of the day .)
# baldec 10/13/2008 10:55 AM
Ok, some time have now passed and the question on this topic have evolved.

I do not manage to create a successful query against my db.

DB created as follows.
CREATE TABLE People(
id int identity(1,1) NOT NULL PRIMARY KEY,
resellerName nvarchar(100)NOT NULL,
phone nvarchar(100) NOT NULL,
address nvarchar(100) NOT NULL,
city nvarchar(100) NOT NULL,
country nvarchar(100) DEFAULT 'Sverige' NOT NULL,
updateTimestamp datetime DEFAULT current_timestamp NOT NULL)
GO



The mapping file is as follows
%?xml version="1.0" encoding="utf-8" ?%
%hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"%
  %class name="icenet.Modules.ListResellers.Domain.Reseller, icenet.Modules.ListResellers"
         table="People"%
    
    %id name="Id" column="id" type="Int32" unsaved-value="-1"%
      %generator class="identity" /%
    %/id%
    
    %property name="Name" column="resellerName" type="String" length="100" not-null="true" /%
    %property name="Phone" column="phone" type="String" length="100" not-null="true" /%
    %property name="Address" column="address" type="String" length="100" not-null="true" /%
    %property name="City" column="city" type="String" length="100" not-null="true" /%
    %property name="Country" column="country" type="String" length="100" not-null="true" /%

    %timestamp name="UpdateTimestamp" column="updateTimestamp" unsave-value="1/1/0001" /%
    
  %/class%
  
%/hibernate-mapping%

And into this I just want to begin by doing simple retrievals. Though I do not get to that stage bug get the following error.
[QueryException: in expected: %end-of-text% (possibly an invalid or unmapped class name was used in the query) [from Reseller]]
   NHibernate.Hql.Classic.FromParser.End(QueryTranslator q) +84
   NHibernate.Hql.Classic.ClauseParser.EndChild(QueryTranslator q) +34
   NHibernate.Hql.Classic.ClauseParser.End(QueryTranslator q) +50
   NHibernate.Hql.Classic.PreprocessingParser.End(QueryTranslator q) +44
   NHibernate.Hql.Classic.ParserHelper.Parse(IParser p, String text, String seperators, QueryTranslator q) +232
   NHibernate.Hql.Classic.QueryTranslator.Compile() +126
   NHibernate.Hql.Classic.QueryTranslator.Compile(IDictionary replacements, Boolean scalar) +54
   NHibernate.Impl.SessionFactoryImpl.GetQuery(String queryString, Boolean shallow, IDictionary enabledFilters) +135
   NHibernate.Impl.SessionImpl.GetQueries(String query, Boolean scalar) +34
   NHibernate.Impl.SessionImpl.Find(String query, QueryParameters parameters, IList results) +132
   NHibernate.Impl.SessionImpl.Find(String query, QueryParameters parameters) +42
   NHibernate.Impl.QueryImpl.List() +105
   icenet.Modules.ListResellers.ListResellersModule.getAllResellers() +66

[Exception: KABOOOOM!!!!
 Err: Reseller Listing]
   icenet.Modules.ListResellers.ListResellersModule.getAllResellers() +153
   icenet.Modules.ListResellers.Web.ListResellers.DoMagic_Click(Object sender, EventArgs e) +47
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

I have the Reseller.hbm.xml file as an embedded resource, which appears to be a common issue when this error message is tossed.

Error with mapping of the class... Mapping how, when, why?

Or is it something with how the call is made for the DB?
public IList getAllResellers()
        {
            ISession session = this._sessionManager.OpenSession();

            string hql = "from Reseller";
            IQuery q = session.CreateQuery(hql);

            try
            {
                return q.List();
            }
            catch (Exception X)
            {
                throw new Exception("KABOOOOM!!!!\n Err: " + base.Section.Title, X);
            }
        }


Any clues from anyone. Like always, all help is appreciated.
# Ryan 10/13/2008 11:31 AM
Hmmm, I'm not to sure what the problem could be with the mapping file as I always use MyGeneration to generate the files for me.

Maybe try not using hql, like so:

public IList getAllResellers()
        {
            ISession session = this._sessionManager.OpenSession();
            ICriteria criteria = session.CreateCriteria(typeof(icenet.Modules.ListResellers.Domain.Reseller));
            try
            {
                return criteria .List();
            }
            catch (Exception X)
            {
                throw new Exception("KABOOOOM!!!!\n Err: " + base.Section.Title, X);
            }
        }
# baldec 10/13/2008 1:02 PM
That do not work, then I get a casting error from ArrayList() to Generic List(). And since I dont have any arrays in my app. I assume it is from the ICriteria.

Though what is MyGeneration? Perhaps it can solve/sort the mapping file atleast.
# YKS 10/13/2008 3:14 PM (edited 10/13/2008 3:21 PM)
In propertis of hbm.xml file (mapping file) you must select "Embedded Resource" in Build Action.

# baldec 10/13/2008 3:54 PM
YKSIn propertis of hbm.xml file (mapping file) you must select "Embedded Resource" in Build Action.
baldecI have the Reseller.hbm.xml file as an embedded resource, which appears to be a common issue when this error message is tossed.

Thanks, but as I specified it is defined as an embedded resource :)

So the issue is someplace else, though it eludes me tremendously at the moment. Dont know how many pages of examples/tutorials/guides I have gone through today and still I haven't found the issue. Quite annoying to say the least. Would have been nice if it was easy to get to work, though with this instep I am currently seriously considering to just do it the old fashioned way with direct db connection. Though would rather get this to work since it will most likely come in handy later on.

So anyone with a new suggestion on what might be the cause of this shifty error?
# Ryan 10/13/2008 4:03 PM
Shouldn't this:
< timestamp name="UpdateTimestamp" column="updateTimestamp" unsave-value="1/1/0001" / >

Actually be this:
< property name="UpdateTimestamp" column="updateTimestamp" unsave-value="1/1/0001" / >
# baldec 10/13/2008 4:55 PM
NHibernate.InvalidProxyTypeException: The following types may not be used as proxies:
icenet.Modules.ListResellers.Domain.Reseller: method set_Id should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method get_Address should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method get_Country should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method set_UpdateTimestamp should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method get_Id should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method get_City should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method get_UpdateTimestamp should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method set_Country should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method set_Phone should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method set_Address should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method get_Phone should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method get_ResellerName should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method set_City should be virtual
icenet.Modules.ListResellers.Domain.Reseller: method set_ResellerName should be virtual

I get this error on first load after publish with that change, the unsave value was not useable on the property attribute though so that is not present.

After a reload I can't access the above error messages any longer. And when I try and fetch the information from the db I get the same error as before.
# martijnb 10/13/2008 10:13 PM
You're very close!

The reason that Reseller is not known in the query is because adding the mapping to the sessionfactory failed. Like NHibernate suggests, you have to make all properties of Reseller virtual. This is because NHibernate creates a subclass of the Reseller class at runtime to perform its magic (like lazy loading) and the original properties are overridden to add the extra behaviour.

So just make every property virtual and it should be done. The mapping looks perfect otherwise and the original UpdateTimestamp mapping (via the timestamp tag) is also ok.
# baldec 10/14/2008 9:49 AM
martijnbYou're very close!

The reason that Reseller is not known in the query is because adding the mapping to the sessionfactory failed. Like NHibernate suggests, you have to make all properties of Reseller virtual. This is because NHibernate creates a subclass of the Reseller class at runtime to perform its magic (like lazy loading) and the original properties are overridden to add the extra behaviour.

So just make every property virtual and it should be done. The mapping looks perfect otherwise and the original UpdateTimestamp mapping (via the timestamp tag) is also ok.

Ok, this looks like a promising answer, though I do not get it to work.

If I use timestamp on the updateTimestamp property I get the following answer even when I add the virtual to the access methods.
[XmlSchemaValidationException: Elementet class i namnområdet urn:nhibernate-mapping-2.2 har ett ogiltigt underordnat element, timestamp i namnområdet urn:nhibernate-mapping-2.2. En lista med möjliga element förväntades: 'urn:nhibernate-mapping-2.2:property urn:nhibernate-mapping-2.2:many-to-one urn:nhibernate-mapping-2.2:one-to-one urn:nhibernate-mapping-2.2:component urn:nhibernate-mapping-2.2:dynamic-component urn:nhibernate-mapping-2.2:any urn:nhibernate-mapping-2.2:map urn:nhibernate-mapping-2.2:set urn:nhibernate-mapping-2.2:list urn:nhibernate-mapping-2.2:bag urn:nhibernate-mapping-2.2:idbag urn:nhibernate-mapping-2.2:array urn:nhibernate-mapping-2.2:primitive-array urn:nhibernate-mapping-2.2:subclass urn:nhibernate-mapping-2.2:joined-subclass urn:nhibernate-mapping-2.2:loader urn:nhibernate-mapping-2.2:sql-insert urn:nhibernate-mapping-2.2:sql-update urn:nhibernate-mapping-2.2:sql-delete urn:nhibernate-mapping-2.2:filter'.]

[MappingException: icenet.Modules.ListResellers.Domain.Reseller.hbm.xml(20,6): XML validation error: Elementet class i namnområdet urn:nhibernate-mapping-2.2 har ett ogiltigt underordnat element, timestamp i namnområdet urn:nhibernate-mapping-2.2. En lista med möjliga element förväntades: 'urn:nhibernate-mapping-2.2:property urn:nhibernate-mapping-2.2:many-to-one urn:nhibernate-mapping-2.2:one-to-one urn:nhibernate-mapping-2.2:component urn:nhibernate-mapping-2.2:dynamic-component urn:nhibernate-mapping-2.2:any urn:nhibernate-mapping-2.2:map urn:nhibernate-mapping-2.2:set urn:nhibernate-mapping-2.2:list urn:nhibernate-mapping-2.2:bag urn:nhibernate-mapping-2.2:idbag urn:nhibernate-mapping-2.2:array urn:nhibernate-mapping-2.2:primitive-array urn:nhibernate-mapping-2.2:subclass urn:nhibernate-mapping-2.2:joined-subclass urn:nhibernate-mapping-2.2:loader urn:nhibernate-mapping-2.2:sql-insert urn:nhibernate-mapping-2.2:sql-update urn:nhibernate-mapping-2.2:sql-delete urn:nhibernate-mapping-2.2:filter'.]
   NHibernate.Cfg.Configuration.LogAndThrow(MappingException me) +40

Though if I use updateTimestamp as an property I get past that and just get a cast exception, though to make sure I got the virtual thing straight it should be as follows right?
private string city = null;

public virtual string City
{
    get { return city; }
    set { city = value; }
}

Though why would I get a cast error? Shouldn't the NHibernate queries return an List? And not an ArrayList? Though that could be my sodden skull not working straight at the moment, the cold from hell making the insides of my skull pretty soggy...
[InvalidCastException: Det gick inte att omvandla ett objekt av typen System.Collections.ArrayList till typen System.Collections.Generic.List`1[icenet.Modules.ListResellers.Domain.Reseller].]

Another question about timestamp attribute in the mapping file, you say it should be ok. Though if I have it as a timestamp attribute then it flakes on the mapping file. So any special rules about the timestamp attribute? Should or should not be mapped in the reseller file like other class attributes or is the timestamp variable only a db sageguard so shouldn't be there in the code file? Or is it something completely different?

Alot of strange questions about NHibernate atm, hope you can all cope :)
# baldec 10/14/2008 10:08 AM
NHibernate access example from the module creation document
public IList GetAllFiles()
{
  ISession session = this._sessionManager.OpenSession();
  string hql = "from File f where f.Section.Id = :sectionId order by f.DatePublished desc";
  IQuery q = session.createQuery(hql);
  q.SetInt32("sectionId", base.Section.Id);
  try
  {
    return q.List();
  }
  catch (Exception ex)
  {
    throw new Exception("Unable to get Files for section: " + base.Section.Title, ex);
  }
}

My code for access
public IList getAllResellers()
{
  ISession session = this._sessionManager.OpenSession();
  string hql = "from Reseller";
  IQuery q = session.CreateQuery(hql);

  try
  {
    return q.List();
  }
  catch (Exception X)
  {
    throw new Exception("KABOOOOM!!!!\n Err: " + base.Section.Title, X);
  }
}

My Code to cause a cast exception since the type returned by q.List() is an ArrayList and thus not compatible with the type IList it seems (like I have said before, quite new to C#). Though I do not see any discrepancies from my code and the example. So I am now wondering if the code in the example document is still valid or if things have changed from the time of writing so that it is a broken piece of equipment.

Or have I just done something very strange while translating the example into my own code?

And like I have said a couple of times by now. Thank you for your patience .)
# baldec 10/14/2008 11:36 AM
Ok, issue with the casting solved. I blame the sodden insides of my skull for that brainfreeze.

I short, q.List() returns an ArrayList implementation of IList and not a List implementation of IList. So just had to accept the IList as an Arraylist later on and all was just fine.

Though the issue with Timestamp is still there, dont get that to work if it is set as a timestamp but works fine if I set it as a property. So I assume that it have something to do with automatic updates of some sort and that it shouldn't be present in the Reseller class.
# martijnb 10/15/2008 9:16 AM
Just remove the timestamp to get things going. It's not required.
# baldec 10/15/2008 2:43 PM
martijnbJust remove the timestamp to get things going. It's not required.

Thats what I did, though still a hole of curiosity to fill in :)