-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 10 posts ] 
Author Message
 Post subject: Trying to use web.config with nhibernate
PostPosted: Mon Jun 26, 2006 12:33 pm 
Newbie

Joined: Mon Jun 26, 2006 12:27 pm
Posts: 16
I'm trying to get NHibernate to just use my settings in web.config on an ASP.net project (2.0 if it matters) and I'm confused about something. I've built my NHibernate model off of Ben Day's reference application just to get going. The problem is that when he calls Configure() on the Configuration object I get an exception that hibernate.cfg.xml does not exist in the web app's bin directory. (Yes, his code includes that file, but I'm trying to drive everything from web.config to only have one config file).

I have looked at the configuration object and it contains the name/value pairs that were put in web.config. Is this configuration call unnecessary? If not, is there some way I should be telling it to use web.config? I'm about to dive into the source to see what NHiberate is doing on that call, but I'm just wondering what is supposed to be there. I've looked at lots of samples, but I'm not clear on how this should be. Any help would be much appreciated.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 26, 2006 1:01 pm 
Pro
Pro

Joined: Fri Nov 19, 2004 5:52 pm
Posts: 232
Location: Chicago, IL
Who's Ben Day? It would help if you posted some code...


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 26, 2006 1:08 pm 
Beginner
Beginner

Joined: Sat Dec 10, 2005 6:22 pm
Posts: 28
Location: Chicago, IL
For Ben Day's project here is what I changed during the configure calls. I changed both the SchemaUtility.cs and NHibernateHttpModule.cs

It is really much easier to have two seperate files. For my projects I usually just add a key to the web config that points to the nhibernate config file. I also change my nhibernate config file to nhibernate.config that way the web server will block a request for the file.

Code:
               if (System.Web.HttpContext.Current != null)
                 config.Configure(System.Web.HttpContext.Current.Request.MapPath("~/hibernate.cfg.xml"));
               else
                  config.Configure();


I also altered the CreateSchema.aspx.cs file to the following. This wll build a minimum config to start playing with.

Code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Com.Benday.NHibernate.Facades;
using VSLive.RightsBasedSecurity.Security.DomainModel;
using VSLive.RightsBasedSecurity.Security.Facades;

public partial class CreateSchema : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SchemaFacade.Export();
            CreateRightGrants();
    }

      protected List<UserLogin> CreateUsers()
      {
         List<UserLogin> users = new List<UserLogin>();

         users.Add(CreateUser("Catalog", "Administrator", "admin", "admin@test.org", "password"));
         users.Add(CreateUser("Joe Q.", "Public", "public", "joe.q.public@test.org", "password"));
         users.Add(CreateUser("FirstName3", "LastName3", "UserName3", "username3@test.org", "password"));
         users.Add(CreateUser("FirstName4", "LastName4", "UserName4", "username4@test.org", "password"));

         BusinessFacade<UserLogin> facade = new BusinessFacade<UserLogin>(SessionFacade.Session);

         facade.Save(users);

         return users;
      }

      protected List<UserGroup> CreateGroups()
      {
         List<UserGroup> groups = new List<UserGroup>();

         groups.Add(CreateUserGroup("CatalogAdmins"));
         groups.Add(CreateUserGroup("CatalogPublicUsers"));
         groups.Add(CreateUserGroup("CatalogInternalUsers"));

         BusinessFacade<UserGroup> facade = new BusinessFacade<UserGroup>(SessionFacade.Session);

         facade.Save(groups);

         return groups;
      }

      protected UserLogin CreateUser(string firstName, string lastName, string userName, string email, string password)
      {
         UserLogin login = new UserLogin();

         login.FirstName = firstName;
         login.LastName = lastName;
         login.Username = userName;
         login.Password = password;
         login.Email = email;

         return login;
      }

      protected UserGroup CreateUserGroup(string name)
      {
         UserGroup group = new UserGroup();

         group.Name = name;

         return group;
      }

      protected UserGroupMember CreateUserGroupMember(UserGroup group, UserLogin user)
      {
         group.AddMember(user);

         return group.FindMember(user);
      }

      protected ItemRight CreateItemRight(string name, bool isItemSpecific, SecurableItem securableItem)
      {
         ItemRight right = new ItemRight();

         right.IsItemSpecific = isItemSpecific;
         right.Name = name;
         right.SecurableItem = securableItem;

         return right;
      }

      protected SecurableItem CreateSecurableItem(string name)
      {
         SecurableItem item = new SecurableItem();

         item.Name = name;
         item.ItemType = "Library Entry";

         return item;
      }

      protected List<ItemRight> CreateItemRights(SecurableItem securableItem)
      {
         List<ItemRight> itemRights = new List<ItemRight>();

         itemRights.Add(CreateItemRight("CATALOG_ADMIN", false, null));
         itemRights.Add(CreateItemRight("CATALOG_USER", false, null));

         itemRights.Add(CreateItemRight("VIEW_ENTRY", true, securableItem));
         itemRights.Add(CreateItemRight("VIEW_RELATED", true, securableItem));
         itemRights.Add(CreateItemRight("EXPORT_TO_EXCEL", true, securableItem));
         itemRights.Add(CreateItemRight("DOWNLOAD_EDOC", true, securableItem));

         BusinessFacade<ItemRight> facade = new BusinessFacade<ItemRight>(SessionFacade.Session);

         facade.Save(itemRights);

         return itemRights;
      }

      public List<UserGroupMember> CreateUsersAndGroups()
      {
         List<UserGroup> groups = CreateGroups();
         List<UserLogin> users = CreateUsers();

         List<UserGroupMember> members = new List<UserGroupMember>();

         BusinessFacade<UserGroupMember> facade = new BusinessFacade<UserGroupMember>(SessionFacade.Session);


         members.Add(CreateUserGroupMember(groups[0], users[0]));
         members.Add(CreateUserGroupMember(groups[1], users[1]));
         members.Add(CreateUserGroupMember(groups[1], users[2]));
         members.Add(CreateUserGroupMember(groups[1], users[3]));

         facade.Save(members);

         return members;
      }

      public ItemGroup CreateItemGroup(string name, SecurableItem securableItem)
      {
         ItemGroup itemGroup = new ItemGroup();

         itemGroup.Name = name;
         itemGroup.SecurableItem = securableItem;

         return itemGroup;
      }

      public List<ItemGroup> CreateItemGroups(SecurableItem securableItem)
      {
         List<ItemGroup> list = new List<ItemGroup>();

         list.Add(CreateItemGroup("Public", securableItem));
         list.Add(CreateItemGroup("Private", securableItem));
         list.Add(CreateItemGroup("Internal", securableItem));

         BusinessFacade<ItemGroup> facade = new BusinessFacade<ItemGroup>(SessionFacade.Session);

         facade.Save(list);

         return list;
      }

      public ItemGroupMember CreateItemGroupMember(ItemGroup itemGroup, int itemId)
      {
         ItemGroupMember member = new ItemGroupMember();

         member.ItemGroup = itemGroup;
         member.ItemId = itemId;

         return member;
      }

      public void CreateRightGrants()
      {
         SecurableItem item = CreateSecurableItem("Library Entry");

         List<ItemRight> itemRights = CreateItemRights(item);
         List<ItemGroup> itemGroups = CreateItemGroups(item);
         List<UserGroupMember> userGroupMembers = CreateUsersAndGroups();

         BusinessFacade<UserLogin> userFacade = new BusinessFacade<UserLogin>(SessionFacade.Session);

         IList users = userFacade.GetList();
         UserLogin user1 = users[0] as UserLogin;
         UserLogin user2 = users[1] as UserLogin;

         BusinessFacade<ItemGroupMember> facade = new BusinessFacade<ItemGroupMember>(SessionFacade.Session);

         ItemGroupMember igm = CreateItemGroupMember(itemGroups[0], 10);
         facade.Save(igm);

         igm = CreateItemGroupMember(itemGroups[0], 20);
         facade.Save(igm);

         igm = CreateItemGroupMember(itemGroups[1], 30);
         facade.Save(igm);

         igm = CreateItemGroupMember(itemGroups[1], 40);
         facade.Save(igm);

         BusinessFacade<RightGrant> rgFacade = new BusinessFacade<RightGrant>(SessionFacade.Session);
         BusinessFacade<UserGroup> ugFacade = new BusinessFacade<UserGroup>(SessionFacade.Session);
         BusinessFacade<ItemRight> rightsFacade = new BusinessFacade<ItemRight>(SessionFacade.Session);

         UserGroup ugCatalogUsers = ugFacade.Get("Name", "CatalogUsers");
         ItemRight rightViewEntry = rightsFacade.Get("Name", "VIEW_ENTRY");

         RightGrant rg = null;

         // Grant UserGroup Right on Item
         rg = new RightGrant();
         rg.Recipient.UserGroup = userGroupMembers[0].UserGroup;
         rg.Right = itemRights[0];
         rg.Target.Item = CreateItemGrantTarget(10, "GrantTarget1");
         rgFacade.Save(rg);

         // Grant UserGroup Right on ItemGroup
         rg = new RightGrant();
         rg.Recipient.UserGroup = userGroupMembers[0].UserGroup;
         rg.Right = itemRights[0];
         rg.Target.ItemGroup = itemGroups[0];
         rgFacade.Save(rg);

         // Grant UserGroup Right on ItemGroup
         rg = new RightGrant();
         rg.Recipient.UserGroup = ugCatalogUsers;
         rg.Right = rightViewEntry;
         rg.Target.ItemGroup = itemGroups[1];
         rgFacade.Save(rg);

         // Grant User Right on Item
         rg = new RightGrant();
         rg.Recipient.User = user1;
         rg.Right = itemRights[0];
         rg.Target.Item = CreateItemGrantTarget(10, "GrantTarget2");
         rgFacade.Save(rg);

         // Grant User Right on ItemGroup
         rg = new RightGrant();
         rg.Recipient.User = user1;
         rg.Right = itemRights[0];
         rg.Target.ItemGroup = itemGroups[0];
         rgFacade.Save(rg);

         // Grant User Right on Item
         rg = new RightGrant();
         rg.Recipient.User = user2;
         rg.Right = itemRights[1];
         rg.Target.Item = CreateItemGrantTarget(10, "GrantTarget2");
         rgFacade.Save(rg);

         // Grant User Right on ItemGroup
         rg = new RightGrant();
         rg.Recipient.User = user2;
         rg.Right = itemRights[1];
         rg.Target.ItemGroup = itemGroups[1];
         rgFacade.Save(rg);
      }

      public ItemGrantTarget CreateItemGrantTarget(int itemId, string itemType)
      {
         ItemGrantTarget igt = new ItemGrantTarget();

         igt.ItemId = itemId;
         igt.ItemType = itemType;

         return igt;
      }
}

[/code]


Last edited by abombss on Mon Jun 26, 2006 3:42 pm, edited 1 time in total.

Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 26, 2006 1:47 pm 
Newbie

Joined: Mon Jun 26, 2006 12:27 pm
Posts: 16
jemiller wrote:
Who's Ben Day? It would help if you posted some code...


Sorry, his name comes up a lot in the wikis and documentation I've seen about ASP.NET approaches with NHibernate so I assumed his method was well known. I got the code from http://blog.benday.com/archive/2005/10/25/3054.aspx .


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 26, 2006 1:57 pm 
Newbie

Joined: Mon Jun 26, 2006 12:27 pm
Posts: 16
abombss wrote:
For Ben Day's project here is what I changed during the configure calls. I changed both the ExportSchema.cs and NHibernateHttpModule.cs


I don't see an ExportSchema.cs in mine, just a SchemaUtility.cs. I'm using the 2005 version of his project and I know it's been updated several times. I can use a Hibernate.config and load it the way your code snippet referenced it.

Just so I understand, though, why is it not loading currectly the way I have it now, which is:
Code:
       protected static ISessionFactory CreateSessionFactory()
        {
            Configuration config;
            ISessionFactory factory;

            config = new Configuration();

            if (config == null)
            {
                throw new InvalidOperationException("NHibernate configuration is null.");
            }

            config.Configure();

            factory = config.BuildSessionFactory();

            if (factory == null)
            {
                throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
            }
            else
            {
                return factory;
            }
        }


I have this in my web.config:
Code:
<configSections>
    <section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System,
         Version=2.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
   </configSections>
....
   <nhibernate>
      <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
      <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect"/>
      <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
      <add key="hibernate.connection.connection_string" value="user id=user; password=password; initial catalog=catalog; server=server;"/>
    <add key="hibernate.use_outer_join" value="true" />
    <add key="hibernate.mapping.assembly" value="Some.Assembly" />
   </nhibernate>


So that I get this, why is it not loading this configuration? Or, does it already have the configuration loaded and I do not need to call the Configure method since I registered the configuration in web.config? If I peek inside the config variable, I do see the name value pairs loaded.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 26, 2006 1:57 pm 
Pro
Pro

Joined: Fri Nov 19, 2004 5:52 pm
Posts: 232
Location: Chicago, IL
I just have all my NHibernate settings in either app.config or web.config depending on whether the application is a console/Windows Forms application or a web application.

I think you only need to call Configuration.Configure() if you are using a hibernate.cfg.xml file. I'm not calling it at all. I'm just doing a Configuration.BuildSessionFactory() without first doing a Configure().


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 26, 2006 1:59 pm 
Newbie

Joined: Mon Jun 26, 2006 12:27 pm
Posts: 16
jemiller wrote:
I just have all my NHibernate settings in either app.config or web.config depending on whether the application is a console/Windows Forms application or a web application.

I think you only need to call Configuration.Configure() if you are using a hibernate.cfg.xml file. I'm not calling it at all. I'm just doing a Configuration.BuildSessionFactory() without first doing a Configure().


Thanks, that would make sense. I'll take the call out and see how far I can get now. If I can just get this up and running it will be great :^).


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 26, 2006 2:08 pm 
Regular
Regular

Joined: Wed Jun 21, 2006 3:13 pm
Posts: 110
I have this for my configuration section in my web config:

Code:
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.0">
    <session-factory>
      <property name="hibernate.dialect">NHibernate.Dialect.MsSql2000Dialect</property>
      <property name="hibernate.connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="hibernate.connection.connection_string">Server=(local);Trusted_Connection=true;initial catalog=mobyProject;</property>
      <property name="hibernate.show_sql">true</property>
      <property name="hibernate.connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
      <property name="hibernate.connection.isolation">ReadCommitted</property>
      <mapping assembly="mobyProject" />
    </session-factory>
  </hibernate-configuration>
</configuration>


and I have a simple singlton to manage initialization. Here's the only init call. It handles everything....

Code:
private DbSessionContext()
{
  sessionFactory = new Configuration().Configure().BuildSessionFactory();
}


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 26, 2006 3:32 pm 
Pro
Pro

Joined: Fri Nov 19, 2004 5:52 pm
Posts: 232
Location: Chicago, IL
I noticed that there appears to be two different ways that you can specify the properties in app/web.config (if you do a search for <configuration> at http://www.hibernate.org/hib_docs/nhibe ... ml_single/ you can see what I mean, one way only allows you to set properties). The way that benhyrman is using seems to be the better way to do it because you can specify the assemblies that you want mapped classes loaded from.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 26, 2006 3:53 pm 
Newbie

Joined: Mon Jun 26, 2006 12:27 pm
Posts: 16
Quote:
I have this for my configuration section in my web config:


I have it working now. Thanks for everybody's help.

Yes, I agree I like this way of doing the config better than the way I was doing it, which I had just found in several examples. That way also works when you call the Configure method which means you can leave that call in there which might give you a little more flexibility with the code being able to run either with configuration data included in your app's config or in the default xml file.

Thanks for the link to that documentation as well. Somehow I haven't managed to stumble on that yet and I've got it bookmarked now.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 10 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.