EF7 change connectionstring at runtime - runtime

In the previous versions of EF we were able to alter the dbcontext connection string as below :
context.Database.Connection.ConnectionString = "the new connectionstring";
How can we do this with EF7?
Thank you

I found the solution :
https://github.com/aspnet/EntityFramework/wiki/Configuring-a-DbContext#config-from-external-code
Context Code
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
Application code
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer(#"Server=.\SQLEXPRESS;Database=Blogging;integrated security=True;");
var context = new BloggingContext(optionsBuilder.Options);
Thank you

Related

how to fix Error No DataBase Provider when Everything is okay

When I want to Insert A New Object into the db bellow Error Occured:
No database provider has been configured for this DbContext
Services:
private IConfiguration config;
public Startup(IConfiguration config) => this.config = config;
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlServer().AddDbContext<DataContext>(options => options.UseSqlServer(config["ConnectionStrings:MainConnection"]));
services.AddMvc();
}
DataContext:
public class DataContext:DbContext
{
public DataContext() { }
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<Request> Request { get; set; }
public DbSet<AdminAccept> AdminAccept { get; set; }
public DbSet<Payment> Payment { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
base.OnConfiguring(builder);
}
}
Insert command :
public async Task <int> SaveToStorageAsync()
{
using (DataContext context=new DataContext())
{
context.Request.Add(this);
return await context.SaveChangesAsync();
}
}
however migrations and database created succefully
I solved it finally.
everything is okay but use of using expression cause an error.(I wonder why)
to solving it first of all I removed a using and declare a DataContext as parameter:
public async Task<int> SaveToStorageAsync(DataContext context)
{
context.Request.Add(this);
return await context.SaveChangesAsync();
}
after it initiate constructor in the main controller :
DataContext context;
public HomeController(DataContext context)
{
this.context = context;
}
and finally call function by sending context as a parameter.
hopped you used in your scenarios and good luck
Since you register the DataContext with the constructor receiving a DbContextOptions<DataContext> option.You also need to pass that when you create a DataContext
var optionsBuilder = new DbContextOptionsBuilder<DataContext >();
optionsBuilder.UseSqlServer("Your connection string");
using (DataContext context = new DataContext (optionsBuilder.Options))
{
context.Request.Add(this);
return await context.SaveChangesAsync();
}
I suggest that you could use dbContext by DI in controller which is a more recommended way in asp.net core:
public class StudentsController : Controller
{
private readonly DataContext _context;
public StudentsController(DataContext context)
{
_context = context;
}
public async Task <int> SaveToStorageAsync()
{
_context.Request.Add(this);
return await context.SaveChangesAsync();
}
}
The two ways are included in below link:
https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext#configuring-dbcontextoptions

Dynamo DB .Net Object Persistence Model Not working When Hosted to AWS Lambda

I am using the .Net object persistence model to store item into Dynamo DB. It is working fine on my machine, but when I publish the project to AWS lambda service nothing is storing into database.
Please help.
I fix the issue by setting "IgnoreValue" to true in DynamoDBContextConfig. Remove the context.SaveAsync(model) from the code. below is the working code sample.
[DynamoDBTable("User")]
public class UserModel
{
[DynamoDBHashKey]
public int ID { get; set; }
[DynamoDBRangeKey]
public string Class { get; set; }
[DynamoDBProperty]
public string Name { get; set; }
}
After initializing above model below is code to insert item into DynamoDB.
public async Task InsertRecord(UserModel model)
{
try
{
using( var context = new DynamoDBContext(client, new DynamoDBContextConfig { ConsistentRead = true, SkipVersionCheck = true,IgnoreNullValues=true }))
{
var dataContext = context.CreateBatchWrite<UserModel>();
dataContext.AddPutItem(model);
await dataContext.ExecuteAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.StackTrace.ToString());
}
}

How do I wrap Hinging with a HingeProcess?

I'm missing something. I seem to be registering ok, but my resolve blows up with the following exception.
{"The type Test.Interfaces.IProcess`1 is an open generic type. An open generic type cannot be resolved.\r\nParameter name: t"}
How do I wrap Hinging with a HingeProcess, I thought registerInstance took care of this?
public interface IProcess<T> where T : class
{
Expression<Func<T, bool>> Expression { get; set; }
T Entity { get; set; }
}
public class HingingProcess<T> : IProcess<T> where T : class
{
public Expression<Func<T, bool>> Expression { get; set; }
public T Entity { get; set; }
public HingingProcess(T entity)
{
Entity = entity;
}
}
container.RegisterType(typeof(IProcess<>), typeof(HingingProcess<>), "HingeProcess",
new InjectionConstructor(new GenericParameter("T", "entity")));
Hinging a = new Hinging();
container.RegisterInstance<Hinging>("entity", a);
var pp = container.Resolve(typeof(IProcess<>), "HingeProcess", new ParameterOverrides[] { });
Thought maybe this would work, but fails to register.
container.RegisterType<object, Hinging>("hinge");
container.RegisterType(typeof(IProcess<>), typeof(HingingProcess<>), "HingeProcess",
new InjectionConstructor(new GenericParameter("entity", "hinge")));
You have to specify the type of the IProcess while resolving
var container = new UnityContainer();
container.RegisterType(typeof(IProcess<>), typeof(HingingProcess<>), "HingeProcess",new InjectionConstructor(new GenericParameter("T", "entity")));
Hinging a = new Hinging();
var pp = container.Resolve(typeof(IProcess<Hinging>), "HingeProcess", new ParameterOverride("entity", a));

MvvmCross plugin for setting up Alarms

I want to write a cross mobile platform app that sets up the alarm by specifying the required parameters like Date and Time. I just want to set up only one time and not repeatedly.
I was unable to find any readily available plugin in mvvmcross or in Xamarin ?
Please help
Since there is no existing plugin within MVVMCross, you may want to write your own plugin. You can find the documentation here:
https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins
Because you'd like to specify a few parameters, you'd want to see the following section:
https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#writing-a-configurable-plugin
Overall this is what you might do:
General Interface
public interface IAlarm
{
void SetupAlarm();
}
public class PluginLoader
: IMvxPluginLoader
{
public static readonly PluginLoader Instance = new PluginLoader();
public void EnsureLoaded()
{
var manager = Mvx.Resolve<IMvxPluginManager>();
manager.EnsurePlatformAdaptionLoaded<PluginLoader>();
}
}
Android Implementation
public class DroidAlarmConfiguration
: IMvxPluginConfiguration
{
public AlarmLength { get; set;}
}
public class DroidAlarm : IAlarm
{
public TimeSpan AlarmLength { get; set; }
public void SetupAlarm()
{
//ALARM IMPLEMENTATION HERE. NOTE THIS IS SOME JAVA SYNTAX!!!!
var globals = Mvx.Resolve<Cirrious.CrossCore.Droid.IMvxAndroidGlobals>();
var alarm = globals.ApplicationContext
.GetSystemService(Context.ALARM_SERVICE)
as AlarmManager;
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
alarmLength, alarmIntent);
}
}
public class Plugin
: IMvxPlugin
{
private _alarmLength = **Your Value Here**;
public void Configure(IMvxPluginConfiguration configuration)
{
if (configuration == null)
return;
var droidConfiguration = (DroidAlarmConfiguration)configuration;
_alarmLength = droidConfiguration.AlarmLength;
}
public void Load()
{
var instance = new DroidAlarm();
instance.AlarmLength = _AlarmLength;
Mvx.RegisterSingleton<IAlarm>(instance);
}
}
Setup.cs - To set the values in one core place for all android/ios/windows
protected override IMvxPluginConfiguration GetPluginConfiguration(Type plugin)
{
if (plugin == typeof(Yours.Alarm.Droid.Plugin))
{
return new Yours.Alarm.Droid.DroidAlarmConfiguration()
{
AlarmLength = **YOUR VALUE HERE**
};
}
return null;
}
You would then follow the same Droid step for iOS and Windows Phone. I hope this helps!

Session not saved in ServiceStack

I want to use the session feature but without athentication.
I already added Plugins.Add(new SessionFeature()) to AppHost.cs and I have the following code
public class CustomService : Service
{
public CustomResponse Any(CustomRequest pRequest)
{
var CustomSession = base.Session.Get<CustomType>("MySession");//try to get the session
if (CustomSession == null)
{
//create a new session
CustomSession = new CustomType{MyId=1};
base.Session["MySession"] = CustomSession;
//base.Session.Set("MySession", CustomSession); //also tried this, to save the session.
this.SaveSession(CustomSession, new TimeSpan (0,20,0)); //Save the Session
}
}
}
The problem I'm having is that base.Session.Get<CustomType>("MySession") is always null.
Am I missing something on the implementation of sessions?
You will need to save your session using base.SaveSession(). See here near the bottom there is a section title 'Saving in Service'.
public class MyAppHost : AppHostBase
{
public MyAppHost() : base("MyService", typeof(CustomService).Assembly)
{
}
public override void Configure(Container container)
{
Plugins.Add(new SessionFeature());
}
}
public class CustomType : AuthUserSession
{
public int MyId { get; set; }
}
[Route("/CustomPath")]
public class CustomRequest
{
}
public class CustomResponse
{
}
public class CustomService : Service
{
public CustomResponse Any(CustomRequest pRequest)
{
var CustomSession = base.SessionAs<CustomType>();
if (CustomSession.MyId == 0)
{
CustomSession.MyId = 1;
this.SaveSession(CustomSession, new TimeSpan(0,20,0));
}
return new CustomResponse();
}
}
Update:
There is a Resharper issue with extension methods, see here, which seems to affect SaveSession().
Work Arounds:
ServiceExtensions.SaveSession(this, CustomSession); ReSharper may prompt to reformat and it will work.
Ctrl-Alt-space to reformat
RequestContext.Get<IHttpRequest>().SaveSession(CustomSession) can save the
session.

Resources