1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle
.ActiveRecord
.Framework
.Internal
17 using System
.Collections
;
18 using System
.Reflection
;
22 /// Generate xml from assembly level attributes.
23 /// This is useful if we need to have type-less configuration, such as imports, named queries, etc.
25 public class AssemblyXmlGenerator
27 private StringBuilder xml
;
29 /// Create a new instnace
31 public AssemblyXmlGenerator()
37 /// Reset this generator and prepare to generate xml from new assembly.
41 xml
= new StringBuilder();
45 /// Generate XML from assembly attributes.
46 /// If it can't find relevant attributes, returns null.
48 public string[] CreateXmlConfigurations(Assembly assembly
)
50 object[] atts
= assembly
.GetCustomAttributes(true);
51 ArrayList namedQueries
= new ArrayList();
52 ArrayList imports
= new ArrayList();
53 ArrayList rawXml
= new ArrayList();
54 foreach (object attribute
in atts
)
56 if (attribute
is HqlNamedQueryAttribute
)
58 namedQueries
.Add(attribute
);
60 else if (attribute
is ImportAttribute
)
62 imports
.Add(attribute
);
64 else if (attribute
is RawXmlMappingAttribute
)
66 string[] result
= ((RawXmlMappingAttribute
)attribute
).GetMappings();
67 rawXml
.AddRange(result
);
70 xml
.Append(Constants
.XmlPI
);
71 xml
.AppendFormat(Constants
.XmlHeader
, "", "");
72 //note that there is a meaning to the order of import vs. named queries, imports must come first.
73 foreach (ImportAttribute attribute
in imports
)
75 AppendImport(attribute
);
77 foreach (HqlNamedQueryAttribute attribute
in namedQueries
)
79 AppendNamedQuery(attribute
, assembly
);
81 xml
.AppendLine(Constants
.XmlFooter
);
82 bool hasQueriesOrImportsToAdd
= namedQueries
.Count
!= 0 || imports
.Count
!= 0;
83 if (hasQueriesOrImportsToAdd
)
85 rawXml
.Insert(0,xml
.ToString());
88 return (string[])rawXml
.ToArray(typeof(string));
91 private void AppendImport(ImportAttribute attribute
)
93 xml
.AppendFormat("<import class=\"{0}\" rename=\"{1}\"/>", XmlGenerationVisitor
.MakeTypeName(attribute
.Type
), attribute
.Rename
);
96 private void AppendNamedQuery(HqlNamedQueryAttribute attribute
, Assembly assembly
)
98 if (attribute
.Name
== "" || attribute
.Query
== "")
100 throw new ActiveRecordException("Error generating XML for HqlNamedQuery in " + assembly
.FullName
+
101 ". Query must have both name and query.");
108 ", attribute
.Name
, attribute
.Query
);