I have followed many tutorials here on LINQ to XML http://www.dotnetcurry.com/showarticle.aspx?ID=564
The terminology for the XML documents is confusing.
Could someone please help me to write the code snippet that would extract the "Name" value from this xml based on a condition for example.
I need colSDate and colAcqDate because Visible is True but not colSeqNo because it does not have the Visible property or it is set to False.
<XtraSerializer version="1.0" application="View">
<property name="#LayoutVersion" />
<property name="ActiveFilterEnabled">true</property>
<property name="Columns" iskey="true" value="286">
<property name="Item1" isnull="true" iskey="true">
<property name="Name">colSeqNo</property>
</property>
<property name="Item2" isnull="true" iskey="true">
<property name="Visible">true</property>
<property name="VisibleIndex">0</property>
<property name="Name">colSDate</property>
</property>
<property name="Item3" isnull="true" iskey="true">
<property name="Visible">true</property>
<property name="VisibleIndex">1</property>
<property name="Name">colAcqDate</property>
</property>
</property>
<property name="ActiveFilterString" />
<property name="GroupSummarySortInfoState" />
<property name="FindFilterText" />
<property name="FindPanelVisible">false</property>
</XtraSerializer>
I am trying to write some reasonably performing data access code but the absurd requirements are making it difficult. Any help is extremely appreciated. Thanks in advance.
Here is one way to do it, using LINQ to XML:
Dim result = From d In xml.Descendants("property")
Where d.Attribute("name").Value = "Visible" AndAlso
d.Value = "true"
From e As XElement In d.Parent.Elements
Where e.Attribute("name").Value = "Name"
Select e.Value
or using XPath (not sure if you want vb or c# code, not a huge dif):
Dim x As XmlNodeList = ' ... pardon the break here, want to get it all in window.
d.SelectNodes(".//property[#name='Visible'][.='true']/../property[#name='Name']")
Related
I am having some problem configuring NHibernate to retrieve data in my MVC 4 application.
To keep things simple I have configured all code in the Index method.
Here is code for my Category controller :
and here is my configuration in web.config :
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Data Source=.;Initial Catalog=UsingNH;uid=myuid;Password=mypwd
</property>
<property name="adonet.batch_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="use_outer_join">true</property>
<property name="command_timeout">60</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
</property>
</session-factory>
</hibernate-configuration>
Mapping file for Category is
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="nhibernate-mapping-2.2" namespace="UsingNHibernate.Models" assembly="UsingNHibernate">
<class name="Category" table="Categories" lazy="false">
<id name="Id" columnId="Id" unsaved-value="0">
<generator class="native" />
</id>
<property name="Name">
<column name="Name" data-type="varchar(50)" not-null="true" />
</property>
</class>
</hibernate-mapping>
and the Category table schema is
CREATE TABLE [dbo].[Categories](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
The problem is that the program compiles and runs well but does not return any category.
The code
var lst = (List<Category>)criterion.List<Category>();
returns 0 items (verified in debugger).
Is there any problem in my configuration or Mapping files?
Comment if additional info is required.
Thanks.
If no mappings are defined, nhibernate will simply fail silently and return an empty list if you query a list of entities.
I guess you do not copy over the mapping files to your bin directory. Mark the mapping files to be copied (via properties).
I changed the Build Action Property of the hbm mapping file to Embedded Resource,
then I can get the data.
(It's same way as the OP's comment, but I post it as an answer to be easier noticed.)
I am using Spring.Net for IOC and AOP. It seems Spring.Net does not support multiple AutoProxyCreators. I have following classes:
[Facade]
public abstract class AbstractFacade{
}
[TransactionSupportFacade]
public abstract class AbstractTransactionSupportFacade{
}
Some classes are inherited from above classes, I have following xml configuration:
<object type="Spring.Aop.Framework.AutoProxy.AttributeAutoProxyCreator , Spring.Aop">
<property name="AttributeTypes">
<list>
<value>Common.Attributes.TransactionSupportFacadeAttribute, Common</value>
</list>
</property>
<property name="InterceptorNames">
<list>
<value>JUTransactionInterceptor</value>
</list>
</property>
<property name="CheckInherited">
<value>true</value>
</property>
</object>
<object type="Spring.Aop.Framework.AutoProxy.AttributeAutoProxyCreator , Spring.Aop">
<property name="AttributeTypes">
<list>
<value>Common.Attributes.FacadeAttribute, Common</value>
</list>
</property>
<property name="InterceptorNames">
<list>
<value>IdentifyServiceAspect</value>
<value>PushIdentityAspect</value>
<value>AuthenticationAdvice</value>
<value>ValidationAspect</value>
<value>ServiceCallResultWrapperAspect</value>
</list>
</property>
<property name="CheckInherited">
<value>true</value>
</property>
</object>
the problem raises here, only one of these AttributeAutoProxyCreators work at the same time, please help me to solve this problem.
How to write correct connection string for Nhibernate using SQL Server 2012?
Should I write also database name?
Error:
I get error with wrong „initial catalog”
Wrong connection string for NHibernate (I copy this connection string from my server):
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlServerCeDriver</property>
<property name="connection.connection_string">Data Source=RAFAL-KOMPUTER\MSSQLSERVER4;Initial Catalog=rafal;Integrated Security=True</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
I copy connection string from this part:
I am trying also this but does not help.
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=RAFAL-KOMPUTER\MSSQLSERVER4;Initial Catalog=rafal;Integrated Security=True</property>
I don`t know how correct configure for SQL Server 2012
The first snippet should not work, while the driver is for CE (Compact edition).
The second one looks better, and even more it is working for me. (see more here http://www.connectionstrings.com/sql-server-2012). The most important thing, is to have correct settings of the Provider name (check here: https://stackoverflow.com/a/8150792/315850). Try this adjusted snippet (just to be sure that all parts are set correctly)
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<!-- to profit from features in 2012, use its dialect -->
<property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<!-- the simplest connection string -->
<property name="connection.connection_string">Data Source=RAFAL-KOMPUTER\MSSQLSERVER4;Database=rafal;Trusted_Connection=True;</property>
We have to be sure that correct driver is used (not CE or any other then NHibernate.Driver.SqlClientDriver which means System.Data.SqlClient)
Double check that your 1) SQL server and named instance is: RAFAL-KOMPUTER\MSSQLSERVER4 and 2) the Database name is: rafal and 3) your login has access rights to it, this must work
just replace : SqlServerCeDriver by SqlClientDriver as below :
Replace : <property name="connection.driver_class">NHibernate.Driver.SqlServerCeDriver</property>
By: <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
I have a simple app that uses a sqlite db in my data layer, nothing major. I have populated a few records for UI testing, but I can't pull the data back at all.
The thing is that my my unit tests are able to CRUD without fail, but I'm concerned that something isn't right when I simply want to select all records from a table like to populate a gridview.
I'm using NHibernate for the first time in a loooooong time so I can't tell if this s setup issue or something else.
Base selection method:
protected IList<T> SelectMultipleInternalALL()
{
// create session and select.
using (ISession session = NBHelper.OpenSession())
return session.CreateCriteria<T>().List<T>();
}
Helper class:
public class NBHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure();
configuration.AddAssembly(Assembly.GetCallingAssembly());
new SchemaExport(configuration).Execute(false, true, false);
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
Table config:
<class name="UserData" table="User">
<id name="Id" type="System.Int32" column="Id" >
<generator class="native"/>
</id>
<property name="Email" />
<property name="FirstName" />
<property name="LastName" />
<property name="Notes" />
<property name="Favorite" type="boolean" />
<bag name="Addresses" inverse="true" cascade="all" generic="true">
<key column="UserId" />
<one-to-many class="AddressData"/>
</bag>
<bag name="Tags" inverse="true" cascade="all" generic="true">
<key column="WhatId" />
<one-to-many class="TagData"/>
</bag>
NHibernate config:
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SQLiteDriver</property>
<property name="connection.connection_string">
Data Source=C:\Documents and Settings\bryang\Desktop\AddressBook\AddressBook.DAL\addressbook.s3db
</property>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="query.substitutions">true=1;false=0</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name="show_sql">true</property>
The database location is totally valid, but I get no records. I think the issue might be in the CreateCriteria() call but my unit tests are 100% able to insert and read back the data. I'm missing something and I can't figure out what.
EDIT
I was also running into a lazy loading exception from my one-to-many relationships. I made the collection columns lazy="false" which cleared up the error. A side-effect is that now I return data everywhere, but it's unit test data from somewhere and when I open the sqlite db I still only see where my small set of data was created. Where is this data being held on to? I'm not managing my ISession manually, and I'm even flushing after simple things like a select. Where on earth is this data coming from?
At this point I'll take some data over none, but it makes no sense to me if the db file I'm looking at has nothing in it. Thanks,
Bryan
First of all, change the Driver to the newer version of the driver, the SQLiteDriver is for the old finstar driver, and it has some quirks with the newer version of SQL Lite. Also, your database path needs to be changed, you can't reference a path with spaces without putting "'s around it. If you put your database in the same directory as your executable, you can just use the db name. This configuration works great for me :
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property>
<property name="connection.connection_string">Data Source=core.db3;Version=3</property>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="query.substitutions">true=1;false=0</property>
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name="show_sql">true</property>
I have a tree structure mapped to the data base in a table like this:
UID numeric(18, 0)
NodeUID varchar(50)
Text nvarchar(50)
TreeLevel int
ParentUID varchar(50)
OrderInLevel int
IsLeaf bit
It is an old table and I cannot change it so bear with me...
The NodeUID is a GUID.
the ParentUID column is mapped to the NodeId of a different row.
A root node has a value of "0" in its ParentUID column.
I am trying to map the Tree with NHibernate like this:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="BasicFW.Core.Domain.NavigationTree.UsersNavigationTreeNode, BasicFW.Core" table="bDoxTreeNodes" lazy="false" schema="bDox.dbo">
<id name="NodeUId">
<column name="NodeUID"/>
<generator class="assigned"/>
</id>
<property name="Text">
<column name="Text"/>
</property>
<property name="TreeLevel">
<column name="TreeLevel"/>
</property>
<property name="IsLeaf">
<column name="IsLeaf"/>
</property>
<many-to-one name="Parent" class="BasicFW.Core.Domain.NavigationTree.UsersNavigationTreeNode, BasicFW.Core" column="ParentUID" not-found="ignore"/>
<bag name="Children" lazy="false" order-by="OrderInLevel ASC" cascade="all-delete-orphan" inverse="true">
<key column="ParentUID"/>
<one-to-many class="BasicFW.Core.Domain.NavigationTree.UsersNavigationTreeNode, BasicFW.Core" />
</bag>
</class>
</hibernate-mapping>
The thing is that when I try to update a node ( and a root node in specifies ) the Parent property is null and so NHibernate try`s to Update the ParentUID column to null, and so it failles since to column will not accept null.
thanks
Can you create a trigger for that table? If yes, you could perhaps create a trigger that fires before update/insert. Something like:
create trigger TreeNode_before before insert, update
on TreeNode
referencing NEW as _new
for each row
begin
if _new.ParentUID is null then
set _new.ParentUID = '0';
end if;
end;
Edit: An alternative would be using an interceptor. I have not used that myself but according to the following question it should work in your case, too.
Edit: fixed the link.
NHibernate write value = NULL when ID < 0
I have found the correct mapping that worked, here is the mapping for my tree.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="BasicFW.Core.Domain.NavigationTree.UsersNavigationTreeNode, BasicFW.Core" table="TreeNodes" lazy="false" >
<id name="NodeID">
<column name="NodeUID"/>
<generator class="assigned"/>
</id>
<property name="Text">
<column name="Text"/>
</property>
<property name="TreeLevel">
<column name="TreeLevel"/>
</property>
<property name="ParentID" >
<column name="ParentUID" />
</property>
<property name="IsLeaf">
<column name="IsLeaf"/>
</property>
<many-to-one name="Parent" class="BasicFW.Core.Domain.NavigationTree.UsersNavigationTreeNode, BasicFW.Core" column="ParentUID" not-found="ignore" update="false" insert="false"/>
<bag name="Children" lazy="false" order-by="OrderInLevel ASC" inverse="true" cascade="all-delete-orphan">
<key column="ParentUID"/>
<one-to-many class="BasicFW.Core.Domain.NavigationTree.UsersNavigationTreeNode, BasicFW.Core"/>
</bag>
</class>
</hibernate-mapping>
I have disabled the update and insert in the Parent property.