how to maintian the EF connection string at one place? - mysql

I have the following in my project solution,am trying to maintain the Database connection of Entity framework at one place so that if I have to switch the database to a different vendor(like MYSQL to MSSQL or vice-versa) I can just change the connection name at one place and doesn't have to change at all the places...I tried the following structure but running into an error,how to fix it?
Project#1
Dashboard.EntityFramework
-->bitDbConnection.cs
using
namespace Dashboard.EntityFramework
{
public class bitDbConnection
{
BitDatabaseEntities bitDB = new BitDatabaseEntities();
}
}
Project#2
Dashboard.Repository
-->Repository.cs
using Dashboard.EntityFramework
when I try use to bitDB variable I can the below error
Error:-
The name bitDB does not exist in current context

This probably isn't what you want but to get your code to work, write it like this:
namespace Dashboard.EntityFramework
{
public class bitDbConnection
{
public BitDatabaseEntities bitDB = new BitDatabaseEntities();
}
}
using Dashboard.EntityFramework
public class Repository
{
public void DoSomething()
{
var bitDB = new bitDbConnection().bitDB;
}
}
So, first make bitDB field public, and then use it...
edit for question in comments:
public class Repository
{
private BitDatabaseEntities bitDB = new BitDatabaseEntities().bitDB;
public void DoSomething()
{
var x = bitDB.ToString();
}
}

Related

Azure WebJob- QueueTrigger Staging and Production

I have an Azure WebJob that will be used for Staging and Production. The keys for the proper environments are set in the app.config file.
A ConfigManager class reads the properties from the app.config file.
public static string FirstQueue
{
get { return ConfigurationManager.AppSettings["FirstQueue"]; }
}
I would like the QueueTrigger to read the from the proper queue specified in the app.config file.
public static void ProcessFirstQueue([QueueTrigger(ConfigManager.FirstQueue)] string message)
{
//some function
}
However, the QueueTrigger doesn't seem to like this. I get "An attribute argument must be a constant expression, type of expression...." Any suggestions to set this up. I do not want to hard code values in the queue trigger.
Thanks
You can resolve the queue name at runtime using the
INameResolver
Here's an example to demonstrate this:
WebJob Code:
public class Program
{
private static void Main(string[] args)
{
var config =
new JobHostConfiguration("insert connection string")
{
NameResolver = new QueueNameResolver()
};
var host = new JobHost(config);
host.RunAndBlock();
}
public static void ProcessNotification([QueueTrigger("%queueKey%")] string item)
{
//Handle message
}
public static void ProcessPoison([QueueTrigger("%queueKeyPoison%")] string item)
{
//Handle poison message
}
}
Here's the QueueNameResolver class:
public class QueueNameResolver : INameResolver
{
//name = queueKey or queueKeyPoison
public string Resolve(string name)
{
//Use the name to get it from the app.config or somewhere else.
}
}
Hope this helps,

StructureMap3 How to configure constructor string injection for all types?

I have registered my types using
Scan(
scan => {
scan.TheCallingAssembly();
scan.WithDefaultConventions();
scan.With(new ControllerConvention());
});
But how do I specify for constructor injection with out having to specify the concrete type like this?
string connStr = "...";
For<IRepository().Use<MyRepository>().Ctor<string>("connectionString").Is(connStr);
You can create dedicated convention for registration of repositories.
public class RepositoryConvention : IRegistrationConvention
{
private const string ConnectionString = "your connection string";
public void Process(Type type, Registry registry)
{
if (type.IsConcrete() && type.GetInterfaces().Contains(typeof(IRepository)))
{
registry.For(typeof(IRepository))
.Use(type)
.CtorDependency<string>("connectionString")
.Is(ConnectionString);
}
}
}
or create dedicated type to provide with connection string. I bet you are getting it from web/app.config so adding abstraction for accessing it would be helpful anyway.
public interface IConfigurationSettingsReader
{
string ReadConnectionString(string name);
T ReadSetting<T>(string settingName);
}
Then you just add it as a dependency for your MyRepository and you don't need to add it explicitly in registration or use custom convention.
public class MyRepository : IRepository
{
private readonly string connectionString;
public MyRepository(IConfigurationSettingsReader settingsReader)
{
this.connectionString = settingsReader.ReadConnectionString("ConnStrName");
}
}
You can consider creating an abstract base repository class to be inherited by each repository to get rid of setup bolerplate.
Hope this helps!

what is the procedure for creating database in windows phone 8?

I am developing an application in widows phone 8,in my application I have to create a database .how can I do this ,I am new to this.please help me out
Well, that depends on what backend you want, if you are going to store small amounts of data I would recommend that you create an xml file in local storage. If you are looking at something more complex, you can use Linq-to-SQL with SQL Server CE.
The code to generate such a database involves creating a DataContext class similar to this:
public class MyDbContext : DataContext
{
public const string MyDbConnString = "isostore:/MyDb.sdf";
public MyDbContext(string pConnString = MyDbConnString) : base(pConnString) { }
public Table<SomeClass1> table1;
public Table<SomeClass2> table2;
}
Then you would create the classes that will function as "tables" like this:
[Table(Name = "MyTable")]
public class SomeClass1
{
[Column(IsPrimaryKey = true, Name = "ID")]
public int Id { get; set; }
[Column(Name = "Name")]
public string Name { get; set; }
}
Lastly in the App.xaml.cs you would place code to create the database in the constructor:
public App()
{
// ... other code
CreateDatabase();
}
private void CreateDatabase()
{
using (var context = new MyDbContext())
{
if (!context.DatabaseExists())
{
context.CreateDatabase();
}
}
}
Note that if you want an in depth explanation of how the classes need to be set up, if you want to create foreign key references for example, you need to look at the MS documentation.
I would recommend starting here.

LinqToSql Calculated Field OnPropertyIDChanged

I have a partial class to extend one of my LinqToSql classes. In this partial class I have the following calculated field.
public bool IsInCluster
{
get
{
return Cluster != null;
}
}
In order for a grid column databound to this field to update automatically I have implemented the following partial method.
partial void OnClusterIDChanged()
{
SendPropertyChanged("IsInCluster");
}
However when I update the Cluster property as shown in the following code the OnClusterIDChanged method does not get called:
private void ExecCreateClusterCommand()
{
var cluster = new Cluster()
{
ID = Guid.NewGuid(),
MailService = AppState.CurrentMailService
};
App.DataContext.Clusters.InsertOnSubmit(cluster);
foreach (DeliveryPoint deliveryPoint in SelectedDeliveryPoints)
{
deliveryPoint.Cluster = cluster;
}
App.DataContext.SubmitChanges();
}
I have successfully used this technique with other non navigation properties related to calculated fields. Is there a way to make this work?
In your setter for Cluster, call OnClusterIDChanged, if the state has changed.
The only solution I could find for this was to create a public method in the DeliveryPoint class enabling me to call SendPropertyChanged for the required field (navigation property):
public void CallSendPropertyChanged(string propertyName)
{
SendPropertyChanged(propertyName);
}

How to prevent EF4.1 from creating a DB if it doesn't exist?

I'm using EF4.1 with MVC3 and I need an override to prevent EF from creating a db if it doesn't exist. Instead of creating a new db I would like to catch the error and report that the initial catalog (the database name) is invalid in the connect string.
However, during development I would like to allow for updates for new classes/properties to create according tables/cols in the database.
Is there a best practice or pattern here?
In my application i am completly disable context initializer and handle database mapping and schema manually.
For example :
public class AppDbContext : DbContext
{
public IDbSet<Account> Accounts { get; set; }
public AppDbContext() : base("connection_string")
{
Database.SetInitializer<AppDbContext>(null); // Important! Dont use entity framework initializer !important
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
/* Register custom mapping class */
modelBuilder.Configurations.Add(new AccountMapper());
base.OnModelCreating(modelBuilder);
}
}
And custom mapping :
public class AccountMapper : EntityTypeConfiguration<Account>
{
/// <summary>
/// Employee entity mapper
/// </summary>
public AccountMapper()
{
ToTable("accounts");
HasKey(x => x.Id);
...
}
}
I would suggest looking into the EF database initializer, specifically the IDatabaseInitializer interface.
If you just want it to stop creating the database when it doesn't exist, then just set the Initializer to null. But if you want to log the event or something along those lines then simply create your own IDatabaseInitializer - it's not hard.
You can then set the initializer Application_Start in your global.asax.cs like so:
Database.SetInitializer(new YourCustomInitializer());
As a bonus, here's an example IDatabaseInitializer that I use to run database migrations (using FluentMigrator)... it's extremely handy if I do say so myself!
public class MigrationsDbContextInitializer : IDatabaseInitializer<YourDbContext>
{
private static readonly ILog Logger = LogManager.GetLogger(typeof(MigrationsDbContextInitializer));
public void InitializeDatabase(YourDbContext context)
{
var announcer = new BaseAnnouncer(x => Logger.Info(x));
var runnerContext = new RunnerContext(announcer)
{
Database = "sqlserver2008",
Connection = context.Database.Connection.ConnectionString,
Target = "YourEntitiesNamespace",
PreviewOnly = false,
Task = "migrate"
};
new TaskExecutor(runnerContext).Execute();
}
}