OpenAccess ORm connection to database - c#

I'm new at Telerik & exploring as an option for ORM. I'm trying to do simple thing like writing a record to database using:
Database db = Database.Get("MyConnectionNameIUsedToGenerateClasses");
IObjectScope scope = db.GetObjectScope();
scope.Transaction.Begin();
LookUpType l = new LookUpType();
l.IsActive = true;
l.Name = "test";
scope.Add(l);
scope.Transaction.Commit();
It throws following error: The connection section with id 'MyConnectionNameIUsedToGenerateClasses' cannot be found in the configuration files traversed from '(OpenAccess internally generated. Is there anything I'm missing from the setup? Telerik did add connectionString to my web.config file with it generated classes. Please help. Thanks.

OpenAccess ORM should know of all the assemblies used by the application. The assemblies should be listed under the reference section within the configuration file:
Open the web.config file in the web application project;
Locate the references node;
Alter the references node so that it gets the following form:
<references>
<reference assemblyname="AssemblyName" configrequired="True" />
</references>
The configuration file format is described here.

As I mentioned in the comments above following code works & does my job:
Telerik.OpenAccess.Data.Common.OAConnection dbConnection = dbContext.Connection;
LookUpType l = new LookUpType();
l.IsActive = true;
l.Name = "test123";
LookUpType lkup = new LookUpType();
lkup.IsActive = true;
lkup.Name = "someTest";
dbContext.Add(new LookUpType[] { l, lkup });
dbContext.SaveChanges();

Related

Getting NHibernate.Hql.Ast.ANTLR.QuerySyntaxException: 'Vacancy is not mapped' after moving common code to a Common Project in the same solution

I'm creating another application which shares common entities so I moved the entities and mappings across to this new Common Project. I've changed the namespaces, added the project dependencies and added reference to this new common project but I'm getting the not mapped error. Is there steps I'm missing like adding a reference to it in the startup file or something?
ModelMapper
private ISessionFactory ConfigureNHibernate() {
var cfg = new Configuration();
cfg.DataBaseIntegration(db => {
db.ConnectionString = Configuration.GetConnectionString("MyConnection");
db.Dialect<MsSql2012Dialect>();
db.BatchSize = 500;
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
cfg.AddAssembly("MyProject.Common");
return cfg.BuildSessionFactory();
}
So it looks like the problem is here.
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
cfg.AddAssembly("MyProject.Common");
Assembly.GetExecutingAssembly() isn't going to be your new mapping project assembly.
I always create my domain model in a separate project and pass it in to the nhibernate initializer.
So I've got property on my NhibernateInitializer that takes the mapping assembly
private Assembly MappingAssembly
{
get { return _mappingAssembly ?? (_mappingAssembly = Assembly.Load(_mappingAssemblyName)); }
}
That loads my mapping assembly.
Then when it time to configure them in my mapper the code is
_mapper.AddMappings(MappingAssembly.GetExportedTypes());

How to get the machine configuration filename in .NET Core

I am porting an application from .NET Framework to .NET Core (Standard).
Within the application, we have the following code
public LogMessageListenerFromConfig()
: this(AppDomain.CurrentDomain.BaseDirectory.ConfigurationFile, LoggingSection.DefaultName)
{ }
public LogMessageListenerFromConfig(string section)
: this(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, section)
{ }
public LogMessageListenerFromConfig(string filename, string section)
{
// todo: set up a file watcher and refresh the listeners (etc.) when it changes.
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filename };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
_section = LoggingSection.Section(configuration, section);
Refresh();
}
This appears to be compatible with .NET Core apart from the following statement
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
There is no SetupInformation on an AppDomain anymore. Fair enough I read that it would cause issues etc. However, how else can I get the application configuration file name in a utility class?
Please be aware that this class will be used in both console and asp.net (core) applications.
Any help appreciated
Stephen
Same problem if you are porting a library to .Net Standard. Solution is this;
install this nuget package system.configuration.configurationmanager then you can use:
var conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var configFilePath = conf.FilePath;

Unable to convert project as VSProject

We have created solution like the one below and added the default project after creating solution. Please refer code below
Type visualStudioType = Type.GetTypeFromProgID("VisualStudio.DTE.12.0", true);
DTE env = Activator.CreateInstance(visualStudioType, true) as DTE;
ServiceProvider serviceProvider = new ServiceProvider(env as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
DTE dte = (DTE)serviceProvider.GetService(typeof(DTE));
Object obj = System.Activator.CreateInstance(visualStudioType, true);
EnvDTE80.DTE2 dte8Obj = (EnvDTE80.DTE2)obj;
Solution2 soln = (Solution2)dte8Obj.Solution;
1.I get exception like below, When create project solution.
2.After create project, We cannot able to convert project as VSProject. Its showing exception like below.
Please give solution for resolve above mention issues .
Your code can be simplified to:
Type visualStudioType = Type.GetTypeFromProgID("VisualStudio.DTE.12.0", true);
EnvDTE80.DTE2 dte2 = Activator.CreateInstance(visualStudioType, true) as EnvDTE80.DTE2;
EnvDTE80.Solution2 soln = dte2.Solution as EnvDTE80.Solution2;
Regarding the error locating EnvDTE version 7.0.3300.0 see:
Error When EnvDTE Is Used with VSLangProj Assemblies

How to publish EF code first database to azure

I'm having trouble publishing my Entity Framework database to azure.
I'm working with .NET framework 4.5 and EF 6.1.3. The way my project is set up is as follows and using a code first approach:
Class library for the domain entities(database entities)
Class library for the DTOs
Class library for a repository where I do all the CRUD operations with Entity
Web api project for just the web services(there's no presentation, just restful controllers).
My web services project has references to the repository library and the DTOs library and I never created the database explicitly because EF created it for me using SQL server express I believe, I set up the web.config as follows:
<connectionStrings>
<add name="Database" connectionString="Server=(localdb)\v11.0;Database=Database;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
In my project the database is created along with all the tables and relationships. I added some initial migrations in the repository library like this
namespace Project.Repository.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Project.Repository.ProjectContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(Project.Repository.ProjectContext context)
{
Guid userId = new Guid();
Guid restaurantId = new Guid();
context.Users.AddOrUpdate(
u => u.Id, new Domain.Security.User { Id = userId, Age = 18, Description = "I like restaurants", Email = "user#gmail.com", Password = "12345", Username = "someuser" }
);
context.Restaurants.AddOrUpdate(
r => r.Id,
new Domain.Restaurants.Restaurant
{
Id = restaurantId,
Name = "mcdonalds",
Description = "best restaurant",
FacebookUrl = "www.facebook.com",
GoogleUrl = "www.google.com",
InstagramUrl = "www.instagram.com",
TwitterUrl = "www.twitter.com",
Votes = 3.5f,
UsersWhoLike = new List<Domain.Security.User>() { context.Users.FirstOrDefault(u => u.Id == userId) }
}
);
context.SaveChanges();
}
}
}
When I set to publish the project to my azure websites the webservices publish allright but the database doesn't or at least whenever I call the restaurants service with website/api/restaurants which is the route for getting a list of restaurants it says.
{"Message":"An error has occurred."}
My azure database connection string is setup like this:
Data Source=tcp:someidentifier.database.windows.net,1433;Initial Catalog=Database;Integrated Security=False;User ID=Database#someidentifier;Password=xxxxxx;Connect Timeout=30;Encrypt=True
I don't know what is happening and I don't know if azure is actually seeding the database, what did I left out or what could be my mistakes?
First of all, go to your asp.net webconfig and set this value to Off:
<system.web><customErrors mode="Off"/></system.web>
You'll get an informative Yellow Screen of Death and have a chance of figuring out what's actually wrong. If the YoD is unclear, post it on your answer.
To can see exceptions in azure portal go to your web app -> Tools -> Troubleshoot -> Live HTTP traffic, select Analyze.

Tricking / Forcing Enterprise Library and EF to use a different config file

I am building a plug-in for another system, which causes it not to use app/exe.config. I am using Enterprise Library Logging 5.0 and EF5. How do I let these use a different config file ? I solved the problem for these two tool sets individually, but is there a generic way, should I use another tool which also reads the config files ?
My solution for EF5 is :
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "MyConfig.config";
Configurationn config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
string connString = config.ConnectionStrings.ConnectionStrings["MyConnectionName"].ConnectionString;
MyDbContext c = new MyDbContext(connString );
which uses the following custom constructor :
public MyDbContext(string nameOrconnectionString)
: base(nameOrconnectionString)
{
}
For Enterprise Library 5 :
FileConfigurationSource fcs = new FileConfigurationSource("MyConfig.config");
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(fcs);
This is what I was looking for :
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", #"SomeDirectory\blabla.config");

Categories

Resources