I'm using NHibernate mapping by code and I'm creating the session factory in this way:
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
const bool executeScript = false;
var configuration = new Configuration();
configuration.DataBaseIntegration(c =>
{
c.Dialect<MsSql2005Dialect>();
c.ConnectionString =
ConfigurationManager.ConnectionStrings["ShopConnectionString"]
.ConnectionString;
c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
});
configuration.AddMapping(domainMapping);
_sessionFactory = configuration.BuildSessionFactory();
I need to get the corresponding HBM files.
How can I achieve that?
Two ways:-
//This will write all the XML into the bin/mappings folder
mapper.CompileMappingForEachExplicitlyAddedEntity().WriteAllXmlMapping();
be careful of this method above as your asp.net app will recycle as changes are detected in your bin folder, another way is:-
var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
//you could add a breakpoint here!
var mappingXml = mapping.AsString();
Use the AsString() extension method:
domainMapping.AsString()
It will give you the xml which you can save into a file. You can call that method e.g. before you build the SessionFactory.
Related
In my asp.net core 3.1 project I have setup a custom sql provider which is working great. In my Startup I want to load only the values from the SQLConfigurationProvider into a separate dictionary for use throughout my app. I can see that the configuration object contains a collection of providers as per below screenshot. However I cannot find a way to access only the SQLConfigurationProvider and get the subsequent values. Is this possible?
What you can do is very simple. Once you build your ConfigurationRoot
IConfigurationRoot configRoot = config.Build();
What you can do is to enumerate to a List only the providers you want:
var providers = configRoot.Providers.Where(
p => (p.GetType().Name == "AzureAppConfigurationProvider") ||
(p.GetType().Name == "AzureKeyVaultConfigurationProvider")).ToList();
Then, recreate a new temporary ConfigurationRoot using only the selected providers:
var tempRoot = new ConfigurationRoot(new List<IConfigurationProvider>(providers));
Then, in order to get the values you can do the following:
tempRoot.AsEnumerable().ToDictionary(a => a.Key, a => a.Value)
This way you will get a Dictionary with the key/value pairs of the configuration.
Note: When you initialize a new ConfigurationRoot from the providers, the SDK triggers again the loading of the configuration which might introduce delays (especially if the configuration is retrieved from a cloud service). If you don't want something like that then you probably have to go with the solution suggested by Brando.
According to your description, I suggest you could firstly use Configuration.Providers to get the SQLConfigurationProvider.
But the ConfigurationProvider's data property is protected, so we should write a extension method to get the value and set it into a directory.
More details, you could refer to below codes:
Create a extension class:
public static class ConfigurationProviderExtensions
{
public static HashSet<string> GetFullKeyNames(this IConfigurationProvider provider, string rootKey, HashSet<string> initialKeys)
{
foreach (var key in provider.GetChildKeys(Enumerable.Empty<string>(), rootKey))
{
string surrogateKey = key;
if (rootKey != null)
{
surrogateKey = rootKey + ":" + key;
}
GetFullKeyNames(provider, surrogateKey, initialKeys);
if (!initialKeys.Any(k => k.StartsWith(surrogateKey)))
{
initialKeys.Add(surrogateKey);
}
}
return initialKeys;
}
}
Then you could add below codes to get the provider and get the value..
// Replace the EnvironmentVariablesConfigurationProvider to your provider
var re = ((ConfigurationRoot)Configuration).Providers.FirstOrDefault(x=>x.GetType() == typeof(EnvironmentVariablesConfigurationProvider));
var directory = new Dictionary<string, string>();
foreach (var key in re.GetFullKeyNames(null, new HashSet<string>()).OrderBy(p => p))
{
if (re.TryGet(key, out var value))
{
directory.Add(key, value);
}
}
Result:
I have created a Roslyn Analyzer project which generates a nuget package and DLL of it. I want to use that DLL in a standalone code analysis project. How can i do that? For example i have following code:
MSBuildLocator.RegisterDefaults();
var filePath = #"C:\Users\user\repos\ConsoleApp\ConsoleApp.sln";
var msbws = MSBuildWorkspace.Create();
var soln = await msbws.OpenSolutionAsync(filePath);
var errors = new List<Diagnostic>();
foreach (var proj in soln.Projects)
{
var analyzer = //Here i want to load analyzer from DLL present locally.
var compilation = await proj.GetCompilationAsync();
var compWithAnalyzer = compilation.WithAnalyzers(analyzer.GetAnalyzersForAllLanguages());
var res = compWithAnalyzer.GetAllDiagnosticsAsync().Result;
errors.AddRange(res.Where(r => r.Severity == DiagnosticSeverity.Error).ToList());
}
I have tried following
var analyzer = new AnalyzerFileReference("Path to DLL", new AnalyzerAssemblyLoader());
But here AnalyzerAssemblyLoader shows error as it is inaccessible to to its protection level (class is internal).
Kindly suggest me if we can do this.
the .WithAnalyzers() option will allow you to pass an instance of an analyzer. If you're referencing the DLL locally, you can just create the analyzer like you would any other object and pass it to the compilation.
var analyzer = new MyAnalyzer();
var compilation = await proj.GetCompilationAsync();
var compWithAnalyzer = compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer));
If you're not referencing the assembly, but want to load it at runtime, you can use the usual System.Reflection based methods to get an instance of the analyzer:
var assembly = Assembly.LoadFrom(#"<path to assembly>.dll");
var analyzers = assembly.GetTypes()
.Where(t => t.GetCustomAttribute<DiagnosticAnalyzerAttribute>() is object)
.Select(t => (DiagnosticAnalyzer) Activator.CreateInstance(t))
.ToArray();
compWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzers));
Is there any 'easy' way to rename models in RavenDb when the database already has existing data? I have various models which were originally created in another language, and now I would like to rename them to English as the codebase is becoming quite unmaintainable. If I just rename them, then the data won't be loaded because the properties don't match anymore.
I would like the system to automatically do it on first load. Is there any best way how to approach this? My solution would be:
Check if a document exists to determine if the upgrade has been done or not
If upgrade has not been done, execute patch scripts to update fields
Update document to know that the upgrade has been done
I'd recommend you create new documents from the old documents.
This can be done pretty easily using patching via docStore.UpdateByIndex.
Suppose I had an old type name, Foo, and wanted to rename it to the new type name, Bar. And I wanted all the IDs to change from Foos/123 to Bars/123.
It would look something like this:
var patchScript = #"
// Copy all the properties from the old document
var newDoc = {};
for (var prop in this) {
if (prop !== '#metadata') {
newDoc[prop] = this[prop];
}
}
// Create the metadata.
var meta = {};
meta['Raven-Entity-Name'] = newCollection;
meta['Raven-Clr-Type'] = newType;
// Store the new document.
var newId = __document_id.replace(oldCollection, newCollection);
PutDocument(newId, newDoc, meta);
";
var oldCollection = "Foos";
var newCollection = "Bars";
var newType = "KarlCassar.Bar, KarlCassar"; // Where KarlCassar is your assembly name.
var query = new IndexQuery { Query = $"Tag:{oldCollection}" };
var options = new BulkOperationOptions { AllowStale = false };
var patch = new ScriptedPatchRequest
{
Script = patchScript,
Values = new Dictionary<string, object>
{
{ nameof(oldCollection), oldCollection },
{ nameof(newCollection), newCollection },
{ nameof(newType), newType }
}
};
var patchOperation = docStore.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName", query, patch, options);
patchOperation.WaitForCompletion();
Run that code once at startup, and then your app will be able to work with the new name entities. Your old entities are still around - those can be safely deleted via the Studio.
I'm trying to write code to convert a WCF wsHttpBinding to customBinding, using the method described on WSHttpBinding.CreateBindingElements Method
.
Binding wsHttpBinding = ...
BindingElementCollection beCollection = originalBinding.CreateBindingElements();
foreach (var element in beCollection)
{
customBinding.Elements.Add(element);
}
Once I have generated the custom binding, I want to generate an XML representation for that new custom binding. (The same XML representation that's found in an application's .config file).
Is there a way to do that?
(I'm aware of the tool referenced in this answer: https://stackoverflow.com/a/4217892/5688, but I need something I can call within an application and without depending on a service in the cloud)
The class I was looking for was System.ServiceModel.Description.ServiceContractGenerator
Exemple to generate a configuration for an instance of any kind of Binding:
public static string SerializeBindingToXmlString(Binding binding)
{
var tempConfig = Path.GetTempFileName();
var tempExe = tempConfig + ".exe";
var tempExeConfig = tempConfig + ".exe.config";
// [... create empty .exe and empty .exe.config...]
var configuration = ConfigurationManager.OpenExeConfiguration(tempExe);
var contractGenerator = new ServiceContractGenerator(configuration);
string bindingSectionName;
string configurationName;
contractGenerator.GenerateBinding(binding, out bindingSectionName, out configurationName);
BindingsSection bindingsSection = BindingsSection.GetSection(contractGenerator.Configuration);
// this needs to be called in order for GetRawXml() to return the updated config
// (otherwise it will return an empty string)
contractGenerator.Configuration.Save();
string xmlConfig = bindingsSection.SectionInformation.GetRawXml();
// [... delete the temporary files ...]
return xmlConfig;
}
This solution feels like a hack because of the need to generate empty temporary files, but it works.
Now I'll have to look for a way to have a fully in-memory instance of a System.Configuration.Configuration (maybe by writing my own implementation)
Added missing code parts:
// [... create empty .exe and empty .exe.config...]
// [... delete the temporary files ...]
public static string SerializeBindingToXmlString(Binding binding)
{
var tempConfig = System.IO.Path.GetTempFileName();
var tempExe = tempConfig + ".exe";
var tempExeConfig = tempConfig + ".exe.config";
using(System.IO.FileStream fs = new System.IO.FileStream(tempExe, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
{
}
using (System.IO.FileStream fs = new System.IO.FileStream(tempExeConfig, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
{
fs.SetLength(0);
using (System.IO.StreamWriter sr = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8)) {
sr.WriteLine("<?xml version= \"1.0\" encoding=\"utf-8\" ?>");
sr.WriteLine(#"<configuration />");
}
}
var configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(tempExe);
var contractGenerator = new System.ServiceModel.Description. ServiceContractGenerator(configuration);
string bindingSectionName;
string configurationName;
contractGenerator.GenerateBinding(binding, out bindingSectionName, out configurationName);
var bindingsSection =System.ServiceModel.Configuration.BindingsSection.GetSection(contractGenerator.Configuration);
// this needs to be called in order for GetRawXml() to return the updated config
// (otherwise it will return an empty string)
contractGenerator.Configuration.Save();
string xmlConfig = bindingsSection.SectionInformation.GetRawXml();
System.IO.File.Delete(tempExeConfig);
System.IO.File.Delete(tempExe);
return xmlConfig;
}
This question was asked before but the answers all show how to export the hbm files from fluentnhibernate. We are using S#arpArchitecture which wraps fluent. I am able to export the schema but what I really want is the xml files to troubleshoot errors. I've done this using FNH before but adding S#arp to the mix has complicated things where I cannot figure it out.
I've found this question asked on several forums, but I can't find one that shows how to get the mapping files.
Here is how I do it in one of my projects:
[TestMethod]
public void CreateSchema()
{
var mappingOutput = ConfigurationManager.AppSettings["xmlMappingOutputDirectory"];
var sqlOutput = ConfigurationManager.AppSettings["sqlOutputDirectory"];
Configuration cfg = new Configuration().Configure();
var persistenceModel = new PersistenceModel();
persistenceModel.AddMappingsFromAssembly(Assembly.Load("ProjectName.Data"));
persistenceModel.Configure(cfg);
persistenceModel.WriteMappingsTo(mappingOutput);
new SchemaExport(cfg).SetOutputFile(sqlOutput).Create(true, false);
}
You will need to set the two keys in the your app config or provide values directly for them.
http://wiki.fluentnhibernate.org/Fluent_configuration#Exporting_mappings
In the Mappings call, you can do the following:
.Mappings(m =>
{
m.FluentMappings
.AddFromAssemblyOf<YourEntity>()
.ExportTo(#"C:\your\export\path");
m.AutoMappings
.Add(/* ... */)
.ExportTo(#"C:\your\export\path");
})
As it turns out that only works if you're not using automapping. Here's the solution if you're using automapping:
public void CanGenerateMappingFiles()
{
DirectoryInfo directoryInfo = new DirectoryInfo("../../../../db/mappings");
if (!directoryInfo.Exists)
directoryInfo.Create();
Configuration cfg = new Configuration().Configure();
var autoPersistenceodel = new AutoPersistenceModelGenerator().Generate();
autoPersistenceodel.Configure(cfg);
autoPersistenceodel.AddMappingsFromAssembly(Assembly.Load("TrackerI9.Data"));
autoPersistenceodel.WriteMappingsTo(directoryInfo.FullName);
}
You'll have to make sure that your configuration is set up correctly and that you choose an appropriate location for the directory, but otherwise this should work. It did for me.