I need to process information from an XML-like file. Does anyone know some library/inbuild class (preferably c#) which might be useful to deal with that type of document (with not much effort) ?
Below is a piece of the XML :
<query>
<type id="excel" />
<ids>
<id value="47" />
<id value="2067" />
<id value="247" />
<id value="329" />
<id value="19" />
<id value="485" />
<id value="148" />
<id value="203" />
<id value="219" />
<id value="1503" />
<id value="7318" />
</ids>
<period value="Monthly" />
<start month="01" year="1990" />
<end month="12" year="2015" />
</query>
This appears to be a perfectly valid XML file.
There are System.Xml.XmlDocument class and System.Xml.Linq.XDocument class, both deal with parsing (and constructing) XML.
You can also build a class model and then use XmlSerializer class to deserialize the xml into a class hierarchical model instance.
Welcome to StackOverflow :D
There are 2 tools that should help you in dealing with it :
XSD.EXE will generate a schema and classes that you can add to your project
XSD2Code will generate classes from a schema as well as Serialize/Deserialize methods
Suggestion :
Use XSD.EXE to generate your schema then use XSD2Code to generate classes from that schema.
Both tools are free,
The first one you access it through the Developer Command Line :
xsd file.xml
The second one is a Visual Studio add-in : (tutorial on their site)
Do not forget to accept the answer if you are satisfied with it or ask for more details by editing your question.
Related
I have an entity framework model. Let's say we have an object Foo and an object Bar. They are related, so Foo has a navigation property to Bar, and vice versa.
Now, for my OData endpoint, I'd like to have two collections available for Foo, for instance declared like so:
var builder = new ODataConventionModelBuilder { Namespace = "Test" };
builder.EntitySet<Foo>("Fools");
builder.EntitySet<Foo>("Footballs");
builder.EntitySet<Bar>("Bars");
The idea here is that access to Fools would go through the FoolsController and access to Footballs would go through the FootballsController, so that I could return different sets of data in each endpoint.
Trying to do this, however, causes the following NotSupportedException error message:
Cannot automatically bind the navigation property 'FooThing' on entity type 'Foo' for the entity set or singleton 'Bars' because there are two or more matching target entity sets or singletons. The matching entity sets or singletons are: Fools, Footballs.
I sort of understand the issue, but if I know for a fact that only Footballs will have Bars, is there a way for me to help the system understand that Bars will only have Footballs?
The answer is absolutely yes.
There are many fluent APIs that you can call to set the binding manually, then to suppress the convention binding. For example:
HasManyBinding
HasRequiredBinding
HasOptionalBinding
HasSingletonBinding
...
Based on your information, you can call the following to make the binding manually:
builder.EntitySet<Bar>("Bars").HasRequiredBinding(b => b.FooThing, "Fools");
I also create a simple Foo and Bar class model to test. The below result shows the metadata:
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
<edmx:DataServices>
<Schema Namespace="WebApiTest" xmlns="http://docs.oasis-open.org/odata/ns/ed
m">
<EntityType Name="Foo">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Edm.Int32" Nullable="false" />
</EntityType>
<EntityType Name="Bar">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Edm.Int32" Nullable="false" />
<NavigationProperty Name="FooThing" Type="WebApiTest.Foo" Nullable="fals
e" />
</EntityType>
</Schema>
<Schema Namespace="Test" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EntityContainer Name="Container">
<EntitySet Name="Fools" EntityType="WebApiTest.Foo" />
<EntitySet Name="Footballs" EntityType="WebApiTest.Foo" />
<EntitySet Name="Bars" EntityType="WebApiTest.Bar">
<NavigationPropertyBinding Path="FooThing" Target="Fools" />
</EntitySet>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
As you can see, "HasRequiredBinding" can make the navigation property as non-nullable, while, "HasOptionBinding" can make it nullable.
Hope it can help. Thanks.
I'm using Nhibernate Envers and I want Envers to save audit info on a separate database to keep things cleaner/more maintainable.
I'm using this fluent configuration:
var enversCfg = new NHibernate.Envers.Configuration.Fluent.FluentConfiguration()
enversCfg.Audit(GetDomainEntities())
nhCfg.SetEnversProperty(ConfigurationKey.DefaultCatalog, "nhibernate_testAU")
but when I try to create the schema, I get a HibernateException (The specified schema name "nhibernate_testAU" either does not exist or you do not have permission to use it.)
for what it's worth, my backend is SQL Server 2005
In addition to actually creating the database, I specified the schema to "dbo".
c.SetEnversProperty(ConfigurationKey.DefaultSchema, "dbo");
c.SetEnversProperty(ConfigurationKey.DefaultCatalog, "MyCatalog_Audit");
Also, I have my own RevistionEntity class, so, I needed to add the catalog and schema to my hbm.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyAssembly" namespace="MyNamespace">
<class name="MyRevisionEntity" table="REVINFO" catalog="MyCatalog_Audit" schema="dbo">
<id name="Id" column="MyRevisionEntityId">
<generator class="identity"/>
</id>
<property name="AuditDate"></property>
<property name="UserName"></property>
<!--modifiedEntityNames-->
<set name="ModifiedEntityNames" table="REVCHANGES" catalog="MyCatalog_Audit" schema="dbo">
<key column="REV"/>
<element column="ENTITYNAME" type="string"/>
</set>
</class>
</hibernate-mapping>
HTH
Chuck
You need to manually create the catalog/database. AFAIK - NH's SchemaExport don't create database/catalog (or schemas) for you.
I have xml like this:
<?xml version="1.0" encoding="utf-8"?>
<session xmlns="http://winscp.net/schema/session/1.0" name="blah#blah.com" start="2011-10-03T15:09:30.481Z">
<ls>
<destination value="/incoming/monthly" />
<files>
<file>
<filename value="2.txt" />
<type value="D" />
<modification value="2011-09-14T12:58:26.000Z" />
<permissions value="rwxr-xr-x" />
</file>
<file>
<filename value="3.txt" />
<type value="D" />
<modification value="2011-01-03T22:04:55.000Z" />
<permissions value="rwxr-xr-x" />
</file>
</files>
<result success="true" />
</ls>
</session>
My representation of the following is:
<XmlRoot("session", Namespace:="http://winscp.net/schema/session/1.0")>
Class XMLSession
<XmlElement("ls/files/file")>
Public Property FileList As New List(Of XMLFile)
End Class
<XmlType("file")>
Class XMLFile
<XmlElement("filename")>
Public Property FileName As XMLValueAttribute
<XmlElement("type")>
Public Property TypeName As XMLValueAttribute
<XmlElement("permissions")>
Public Property Permissions As XMLValueAttribute
<XmlElement("modification")>
Public Property ModificationDate As XMLValueAttribute
End Class
Class XMLValueAttribute
<XmlAttribute("value")>
Public Property Value As String
End Class
Why is XMLSession.FileList.Count always 0. I hypothesize it has something to do with the declaration above it but I am not sure what is wrong with it. Maybe it can't accept a path, if not, how can I do it?
You can't describe multiple levels of XML with a single XmlElementAttribute. You need classes for each level.
If you don't want to build the classes by hand, you can get the tools to do it for you:
Assuming your XML is saved in data.xml:
xsd.exe data.xml
This will give you data.xsd which defines the XML.
xsd.exe /l:VB /n:SomeNamespace /c data.xsd
This will give you a codefile data.vb with your types defined, which you can add to your project.
Problem with this one is that there's some kind of bug, described here, which throws an error when you create a serializer around this new type. So you just need one manual tweak on the generated code, changing:
<XmlArrayItemAttribute("file", GetType(sessionLSFilesFile), IsNullable:=False)> _
'To
<XmlArrayItemAttribute("file", GetType(sessionLSFilesFile()), IsNullable:=False)> _
Need help with a simple NHibernate relationship...
Tables/Classes
Request
-------
RequestId
Title
…
Keywords
-------
RequestID (key)
Keyword (key)
Request mapping file
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="CR.Model" assembly="CR">
<class name="CR.Model.Request, CR table="[dbo].[Request]" lazy="true">
<id name="Id" column="[RequestID]">
<generator class="native" />
</id>
<property name="RequestorID" column="[RequestorID]" />
<property name="RequestorOther" column="[RequestorOther]" />
…
Keyword??
</class>
</hibernate-mapping>
How do I simply map multiple keywords to a request? I don't need another mapping file for the keyword class, do I?
It's be great if I could not only get the associated keywords, but add them too...
You'll need a set (or some other kind of collection mapping, but I think a set is the best-fit).
check this
I'm pretty new to Nhibernate, so apologies for a long - winded description
I suspect that changing the structure of the legacy DB is probably the best option, but I want to try and get NHibernate to deal with it.
Basically the structure is this an EndPoint has an address and a contact. Endpoint is stored in a table with a composite ID (Address ID, Contact ID).
I'm having a problem when cascade saving an address, which has a custom ID generator - address ID are of the form "ADR000234" to fit in with a legacy DB structure.
The custom ID generator includes a query, and when I save the address as part of an endpoint, I get a stack overflow. When debugging the cursor gets to line that evaluates the query( var maxAddressID..), then jumps back to start of the method, and keeps on doing this until it raises a stack overflow.
Here's my generator class
public class AddressIdGenerator : IIdentifierGenerator
{
public object Generate(ISessionImplementor session, object obj)
{
var castAsSession = (ISession)session;
var allAddresses = castAsSession.CreateQuery("select max(Code) from Address a");
var maxAddressID = (string)allAddresses.List()[0];
var previousNumber = int.Parse(maxAddressID.Substring(3, 6));
return GetNewId("ADR", previousNumber);
}
private string GetNewId(string prefix, int number)
{
return prefix + (number + 1).ToString().PadLeft(6, '0');
}
}
Here's my mapping foe the EndPoint CLass
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="DataClasses"
namespace="DataClasses">
<class name="EndPoint" table="[Addresses_Contacts]">
<composite-id>
<key-property name ="Address" column ="[Address ID]" type="string" />
<key-property name ="Contact" column ="[Contact ID]" type="string"/>
</composite-id>
<many-to-one name="Address" class="DataClasses.Address, DataClasses" cascade="save-update"/>
<many-to-one name="Contact" class="DataClasses.Contact, DataClasses" cascade="save-update"/>
</class>
</hibernate-mapping>
and the mapping for address:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DataClasses" namespace="DataClasses">
<class name="Address" table="[Lookup Addresses]" >
<id name="Code" column="ID" type="string">
<generator class="Nhibernate.AddressIdGenerator, Nhibernate" />
</id>
<property name="OrganisationName" column="[Name of Organisation]"/>
<property name="StreetAddress1" column="[Park/centre/estate]" />
<property name="StreetAddress2" column="[Street Name]" />
<property name="Town" column="[Town/City]" />
<property name="State" column="[Region/ State]" />
<property name="PostCode" column="[Postal/ Area Code]" />
<property name="District" column="[Local District]" />
<property name="Airport" column="[Airport code]" />
<many-to-one name="Country" class="DataClasses.Country, DataClasses" column ="[Country Code]"/>
</class>
</hibernate-mapping>
If I try to save and Address on its own, it works fine, the ID is generated with no problems.
Also if I remove the Address and Contact properties from the mapping (but not from the composite ID), and save the Address and Contact before saving the Endpoint, it's fine too.
It seems to me that when I'm doing the cascade save, for some reason it can't run other queries during the process, but rather than throwing an exception it's behaving strangely (restarting the method again and again). I haven't ever seen a C# method do this before. I'd love to know if anyone has an idea of how to fix this.
i'm thinking that the problem resides that you are doing an nh-query inside the Generator and you are querying the entity type you want to save.
The generator is called not when you call Save() but whenever there is a need to flush/commit the data. Now, Save() places the entity on a action-queue of things to do. When you call CreateQuery/CreateCriteria and request the result via List()/UniqueResult() nhibernate's engine detects that you made a Save() request on an entity and so will try to flush/commit the entity first (and thus call the generator) and then perform the query and thus start an infinite loop; The logic is such that since you called Save() and then you are querying that class type you will want the result set to include the Saved object.
So, replace your Nh-query with a native SqlCommand (there is a possibility CreateSqlQuery will work too) and i think your problem will be solved.
please update the owner of the relation in the EndPoint xml Mapping.
please mention inverse="true"in the many to one proper for address and contacts.
thanks