nhibernate xml files are not getting mapped automatically - nhibernate

-----working Code
Configuration cfg = new Configuration().DataBaseIntegration(db =>
{
/// Connection String
}).AddFile(#"D:\Test_MVC_Web\NHibernet_DAL\Mapping\departments.hbm.xml");
-------
above code is working fine for me but currently mapping is done manually i have to mapped xml file automatically at the time of configuration
using (var session = _IUnitOfWork.Session)
{
IQuery query = session.GetNamedQuery("GetDepartmentDetails");
query.SetResultTransformer(Transformers.AliasToBean(typeof(departments)));
return query.List<departments>() as List<departments>;
}
when i run above above code its giving me error named query
because xml files are not getting mapped

departments.hbm.xml file should be Embedded Resource
departments.hbm.xml-->properties-->Build Action-->Embedded Resource

Related

Trouble getting a file from Azure container

I am trying to get a file from Azure container. I need to read its content.
The file has been uploaded to umbraco media, media are stored in our Azure container.
Its normal (umbraco) url would be like:
~/media/10890/filename.xls
I am trying to retrieve it like this:
var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["strorageconnstring"]);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("storagemedia");
The thing is - I am not sure how I am supposed to retrieve a particular file? I tried:
1.
CloudBlobDirectory dira = container.GetDirectoryReference("10890"); // file folder within media
var list = dira2.ListBlobs(useFlatBlobListing: true).ToList(); // Returns error saying "The requested URI does not represent any resource on the server."
However the 10890 folder within media storage exists and I can browse it with storage browser.
2.
CloudBlockBlob blobFile = container.GetBlockBlobReference("10890/filename.xls");
string text;
using (var memoryStream = new MemoryStream())
{
blobFile.DownloadToStream(memoryStream); // Throws "The specifed resource name contains invalid characters." error
var length = memoryStream.Length;
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
Any idea how to read the file? And what am I doing wrong?
Thank You Gaurav for providing your suggestion in comment section.
Thank You nicornotto for confirming that your issue got resolved by changing the container name reference in the below statement.
var container = blobClient.GetContainerReference("storagemedia");

Deploying SSRS RDL files from VB.Net - Issue with shared datasources

I am currently developing a utility to help automate our report deployment process. Multiple files, in multiple folders, to multiple servers.
I am using the reportservice2010.asmx web service, and I am deploying my files to the server - so most of the way there.
My issue is that I have shared data sets and shared data sources, which are deployed to individual folders, separate to the report folders. When the deployment occurs the web service looks locally for the data source rather than in the data source folder, giving an error like:
The dataset ‘CostReduction’ refers to the shared data source ‘CostReduction’, which is not
published on the report server. The shared data source ‘CostReduction’ must be published
before this report can run.
The data source/set has been deployed and the report functions correctly but I need to suppress these error messages as they may be hiding other actual errors.
I can hard code a lookup that checks if the data source/set exists and manually filter them via that, but it seems very in-efficient. Is there any way I can tell the web service where to look for these files or another approach that other people have used?
I'm not looking at changing the reports so the data source is read from
/DataSources/DataSourceName
as there are lots of reports and that's not how our existing projects are configured.
Many thanks in advance.
I realize you are using VB, but perhaps this will give you a clue if you convert it from C# to VB, using one of the translators on the web.
Hopefully this will give you a lead in the right direction.
When All the reports in a particular folder, referred to here as the 'parent folder', all use the same Shared Data source, I use this to set all the reports to the same shared Data Source (in this case "/DataSources/Shared_New")
using GetPropertiesSample.ReportService2010;
using System.Diagnostics;
using System.Collections.Generic; //<== required for LISTS
using System.Reflection;
namespace GetPropertiesSample
{
class Program
{
static void Main(string[] args)
{
GetListOfObjectsInGivenFolder_and_ResetTheReportDataSource("0_Contacts"); //<=== This is the parent folder
}
private static void GetListOfObjectsInGivenFolder_and_ResetTheReportDataSource(string sParentFolder)
{
// Create a Web service proxy object and set credentials
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
CatalogItem[] reportList = rs.ListChildren(#"/" + sParentFolder, true);
int iCounter = 0;
foreach (CatalogItem item in reportList)
{
iCounter += 1;
Debug.Print(iCounter.ToString() + "]#########################################");
if (item.TypeName == "Report")
{
Debug.Print("Report: " + item.Name);
ResetTheDataSource_for_a_Report(item.Path, "/DataSources/Shared_New"); //<=== This is the DataSource that I want them to use
}
}
}
private static void ResetTheDataSource_for_a_Report(string sPathAndFileNameOfTheReport, string sPathAndFileNameForDataSource)
{
//from: http://stackoverflow.com/questions/13144604/ssrs-reportingservice2010-change-embedded-datasource-to-shared-datasource
ReportingService2010 rs = new ReportingService2010();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
string reportPathAndName = sPathAndFileNameOfTheReport;
//example of sPathAndFileNameOfTheReport "/0_Contacts/207_Practices_County_CareManager_Role_ContactInfo";
List<ReportService2010.ItemReference> itemRefs = new List<ReportService2010.ItemReference>();
ReportService2010.DataSource[] itemDataSources = rs.GetItemDataSources(reportPathAndName);
foreach (ReportService2010.DataSource itemDataSource in itemDataSources)
{
ReportService2010.ItemReference itemRef = new ReportService2010.ItemReference();
itemRef.Name = itemDataSource.Name;
//example of DataSource i.e. 'itemRef.Reference': "/DataSources/SharedDataSource_DB2_CRM";
itemRef.Reference = sPathAndFileNameForDataSource;
itemRefs.Add(itemRef);
}
rs.SetItemReferences(reportPathAndName, itemRefs.ToArray());
}
}
To Call it I use this in the 'Main' Method:
GetListOfObjectsInGivenFolder_and_ResetTheReportDataSource("0_Contacts");
In this case "0_Contacts" is the parent folder, itself located in the root directory, that contains all the reports for which I want to reset their DataSources to the new Shared DataSource. Then that Method calls the other method "ResetTheDataSource_for_a_Report" which actually sets the DataSource for the report.

config nhibernate for oracle and sql in same application

i need to create switchable web.config file which can configure N Hibernate to work with either MS-SQL Server or Oracle
I'm having 2 configuration files and one web.config files
sqlcongif.config
oracleconfig.config
if i want only SQL config i need to point to sqlconfigure.config in web.config
or else only oracle i need to point oracleconfig.config
tried with child config and other web options .
i found that similar problem when we are having connection strings in web config files
is there any options we can do this ?
thanks in advance :)
This issue could be easily solved with a switch in code (Oracle or SQL server), at the place where we ask for a ISessionFactory.
We just have to pass the config name and the connection string key:
public ISessionFactory BuildFactory(
string configFileName
string connectionStringKey)
{
// full path to the config
var fullfileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory
, configFileName);
var document = System.Xml.Linq.XDocument.Load(fullfileName);
// NH configuration
var config = new NHibernate.Cfg.Configuration();
// feeded with all the setting in our config
using (var reader = document.CreateReader())
{
config.Configure(reader);
}
// read connection string from web.config
// ADVANTAGE: it could be even encrypted
var connectionStringFromWebConfig = ConfigurationManager
.ConnectionStrings[connectionStringKey].ConnectionString;
// use that web.config connection string
config.SetProperty("connection.connection_string", connectionStringFromWebConfig);
// create factory
NHibernate.ISessionFactory factory = config.BuildSessionFactory();
return factory;
}
And then we can call it like
var factory = BuildFactory("config/sqlconfigure.config", "sqlServerConnection")

How to verify if NHibernate hbm.xml are matching with a particular SQL schema?

I had an ASP.NET MVC web application, using NHibernate as ORM on SQL Server 2008 R2. When we deployed to the server, we can update our database any time (some are ad-hoc changes).
The problem is when the database schema change, the application crashed because NHibernate .hbm.xml files are no longer matching with the DB schema.
How do I verify that my current *.hbm.xml file are matching with the database schema ? And how to detect the mismatch early in ASP.NET MVC ?
You can do the checking when application runs, could be in the global asax.
protected void Application_Start()
{
}
The connection string is the key to get the expected schema.
<property name="connection.connection_string">Server=.;Initial Catalog=TheExpectedSchema; ..</property>
First read the expected schema by reading it from nhibernate config and retrieve it from Initial Catalog part (if the database is oracle, probably use the User ID part).
NHibernate.Cfg.Configuration config = ...;
var conStr = config.Properties["connection.connection_string"];
var match = Regex.Match(conStr, "Initial Catalog *= *([^;]*) *");
var expectedSchema = match.Groups[1].Value;
Then read the actual schema by reading it from *.hbm.xml file.
<hibernate-mapping schema="TheActualSchema"
If the files are put under App_Data directory, read each file and use xml document to get the schema.
var appDataDir = new DirectoryInfo(HttpContext.Server.MapPath("~/App_Data"));
var files = appDataDir.GetFiles("*.hbm.xml");
foreach (var file in files)
{
var doc = new XmlDocument();
doc.Load(file.FullName);
var actualSchema = doc.DocumentElement.GetAttribute("schema");
if (actualSchema != expectedSchema)
{
// Proper handling here (an example would be throwing exception).
throw new Exception(string.Format("Expected schema: {0}, actual schema {1}", expectedSchema, actualSchema));
}
}

When creating a T4 template, how can the app config and other file resources be utilized?

I have a T4 template that I am trying to create that will code gen lookup values from a database via Nhibernate. My problem is my data access layer uses the path of the Nhibernate configuration in order to compile the configuration upon startup (a static constructor).
I don't know how to make t4 "see" this file path so that when my code gen runs it can get this configuration file. Nor do I know how to make t4 "see" my configuration manager class; which contains the app setting that lists the path to the nhibernate xml file.
I have two configuration files, one for SQL Server and one for sqlite. The configuration file needs to be in the root directory of the executing assembly in order to nhibernate to compile the configuration.
It seems like my template won't be able to use the high level business layer to select the data from the database, rather I may have to copy all the nhibernate configuration code into the template as well (ugh).
My DB wrapper:
private class DBSingleton
{
static DBSingleton()
{
string path = ConfigurationManager.AppSettings["DBConfigFileFullPath"];
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(path);
cfg.AddInputStream(HbmSerializer.Default.Serialize(System.Reflection.Assembly.GetAssembly(typeof(Plan))));
instance = cfg.BuildSessionFactory();
}
internal static readonly ISessionFactory instance;
}
And my template:
<#
System.Diagnostics.Debugger.Launch();
string path = Host.ResolvePath(#"..\DB.UnitTest\App.config");
System.Configuration.ConfigurationManager.AppSettings.Add(
"DBConfigFileFullPath", path);
//System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(path); //Path to your config file
//System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
ReferenceValueBL bl = new ReferenceValueBL();
List<ReferenceValue> refVals = bl.Select(); <- problem occurs here
foreach(ReferenceValue rv in refVals)
{
Write("Public ");
Write(rv.ReferenceValueCode.GetType().Name);
Write(" ");
Write(rv.ReferenceValueCode);
Write(" = ");
Write(rv.ReferenceValueCode);
}
#>
My problem occurs when the bl variable tries to call select(). That's when the DBSingleton is initialized. It throws an error saying the app setting is null. If I hard code the relative file path in the DB class to just be ./Dbconfig.xml it still throws an error because the executing assembly doesn't have that file in it's local directory.
How do other people handle getting t4 to use app/web config files without reading from the config file within the template and then injecting a connection string into the DAL? I don't have that luxury. The file has to be either placed in a readable location or t4 has to know to look somewhere.
How do other people handle getting t4 to use app/web config files without reading from the config file within the template and then injecting a connection string into the DAL?
You could perhaps convert your text template into runtime text template by setting Properties | Custom Tool to "TextTemplatingFilePreprocessor".
Afterwards the entire code generation process would be encapsulated within standard class which will have TransformText method which produces the resulting string - you can then write it into file of your liking.
Nice thing is that the template class is partial, so you can add implementation of some custom methods. Something like this perhaps:
public partial class RuntimeTextTemplate1
{
public string TransformText(string someParameter)
{
// Do something with someParameter, initialize class field
// with its value and later use this field in your t4 file.
// You also have access to ConfigurationManager.AppSettings here.
return TransformText();
}
}
Also, this:
foreach(ReferenceValue rv in refVals)
{
Write("Public ");
Write(rv.ReferenceValueCode.GetType().Name);
Write(" ");
Write(rv.ReferenceValueCode);
Write(" = ");
Write(rv.ReferenceValueCode);
}
Could be rewritten as:
foreach(ReferenceValue rv in refVals)
{
#>
Public <#= rv.ReferenceValueCode.GetType().Name #> <#= rv.ReferenceValueCode #> = <#= rv.ReferenceValueCode #>
<#+
}