unable to get EF5.0 codefirst migration to make inital DB - asp.net

I am writting my first web application and am trying to learn EF 5.0 code first. I have spent the last two days on google and MSDN trying to figure out how to make this stuff work but none of it is treally geared to first time learners. So can someone please help me using code example with what I am doing wrong? When I run my app in debug no DB is created, when I try to configure migrations from VS2012's package manager I get an error saying "an error occurred while getting the provider information from the database." The blow is my "table".cs file, Context.cs and web.config. From what I can see from all the stuff I have read I am not missing anything.
table.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace FFCollection.DAL
{
public class Item
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int16 ItemID { get; set; }
[Required(ErrorMessage = "Item Name is required.")]
[Column("ItemName")]
public string Name { get; set; }
public Int16 RegionID { get; set; }
public virtual Region Region { get; set; }
}
}
Context.cs:
using System.Data.Entity;
namespace FFCollection.DAL
{
public class FullContext : DbContext
{
public FullContext() : base("FFCollection") { }
public DbSet<Item> Items { get; set; }
}
}
web.confg:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="CollectionDB"
connectionString="Data Source=192.198.0.2; Initial Catalog=FFColection; User ID=; Password=!" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<customErrors mode="Off" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
I know this place is supposed to be only for really experianced people that have years of experiance to ask questions but no where I turn is helping and I am lost so please I just really need some help on where to jump. If someon can help me figure out why the DB is not being made I can continue on with my experimtation of code first EF 5.0

Try this one:
<add name="FFColection"
connectionString="Data Source=192.198.0.2;
Initial Catalog=FFColection;
User ID=; Password=***;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient"/>
The constructor base("FFCollection") either takes the string argument as a full connection string or the name of a connection string in the config file. So it should be "FFColection" in the constructor and the name.
Maybe the address of the server is not enough. You may have to append the name of the sql server instance, like 192.198.0.2\sql2008 (check with Sql Server management studio on the data base machine).

The code was write the problem is that EF does not create the database until the first attempt to access it. So I had to add a bit of code in my index.aspx page to try to add an item to the DB. This caused it to create the database

Related

how connect both PostgreSQL and timescale databases into ASP.NET MVC web.config file

I created a project "SmartHome" using the ASP.NET MVC. I used two types of databases;
PostgreSQL
TIMESCALE
Here, I integrate the TIMESCALE with the PostgreSQL.
I connected the PostgreSQL with ASP.NET MVC and it is working fine. the connection string as below.
<add name="SmartHomeContext"
connectionString="Server=127.0.0.1;Port=5432;Database=smarthome;
User Id=postgres;Password=postdata;" providerName="Npgsql" />
here database names of;
PostgreSQL = smarthome
TIMESCALE = smarthomeData
My problem is " How TIMESCALE database connect to work with same "SmartHome" database in the ASP.NET MVC ? "
I tried the connection string for TIMESCALE as below.
<add name="SmartHomeContext"
connectionString="Server=127.0.0.1;Port=5432;Database=smarthomeData;
User Id=postgres;Password=postdata;" providerName="Npgsql" />
but it shows the below error:
"The entry 'SmartHomeContext' has already been added."
Please help me or guide me, I am very new to do this.
Above error ("The entry 'SmartHomeContext' has already been added.") was solved and the connection also done. the steps are followed as below;
Web.config file : add a another connection string for TIMESCALE database as "SmartHomeContext1". In the below code snippet, third connection string.
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=
(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-SmartHome-
20181019034449.mdf;Initial Catalog=aspnet-SmartHome-20181019034449;Integrated
Security=True" providerName="System.Data.SqlClient" />
<add name="SmartHomeContext"
connectionString="Server=127.0.0.1;Port=5432;Database=smarthome;User
Id=postgres;Password=postdata;" providerName="Npgsql" />
<add name="SmartHomeContext1"
connectionString="Server=127.0.0.1;Port=5432;Database=smarthomeData;User
Id=postgres;Password=postdata;" providerName="Npgsql" />
</connectionStrings>
create "timescalecontext.cs" file in the Model as attached image.
timescalecontext.cs in the Models folder in visual studio
already I created a table in the database "smarthomeData" as attached image.
timescale database
then, code the "timescalecontext.cs" file as below.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace SmartHome.Models
{
public class timescalecontext : DbContext
{
public timescalecontext() : base("name=SmartHomeContext1")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
}
public System.Data.Entity.DbSet<SmartHome.Models.DeviceReading> DeviceReadings { get; set; }
public System.Data.Entity.DbSet<SmartHome.Models.Event> Events { get; set; }
}
}
since the controller file already created before make the above connection, change the code matched with the Dbcontext as below:
namespace SmartHome.Controllers
{
public class DeviceReadingsController : Controller
{
private timescalecontext db = new timescalecontext();
after all that, It worked. Hope, this will be helpful.

ProfileCommon.GetProfile(string)' hides inherited member '.UserProfile.GetProfile(string)'. Use the new keyword if hiding was intended

I am using aspnet membership profile and Inherited the profileBase class to a class name UserProfile, where I have defined the method GetProfile. Everything working fine But while build getting the above warning.
Please help how to remove the warning.
Below the sample codes.
public static UserProfile GetProfile(string userName)
{
return (UserProfile)Create(userName);
}
public static UserProfile GetProfile(string username, bool authenticated)
{
return (UserProfile)Create(username, authenticated);
}
public static UserProfile Current()
{
return ((UserProfile)(HttpContext.Current.Profile));
}
<!-- Profile configuration -->
<profile enabled="true" defaultProvider="EFProfileProvider" inherits="Jan.DB.Provider.UserProfile" automaticSaveEnabled="true">
<providers>
<clear/>
<add name="EFProfileProvider" type="Jan.DB.Provider.EFProfileProvider" connectionStringName="JanEntities" applicationName=""/>
</providers>
</profile>
While migrating from simple membership to Identity we had made some mistake. Although we have removed all the membership related codes. One thing we have done is how profile is handled. I mean in idenity customization we have used the old UserProfile.cs of membership with some customization. But as we are using
in web.config so at runtime Asp.net memebrship automatically creates the ProfileCommon.cs and for that we are getting that warning.
so can avoid that warning by cleaning of the customization and moved to how identity handles the profile information.

Trouble connecting to an MSSQL server using ASP.NET 5, Docker, and Ubuntu

I thought it would be a fun project to play around with an ASP.NET 5 site, in a Docker container, on a Ubuntu server. I've got a simple MVC site running and now I'd like to return data from an MSSQL server but when I run the container, it stops immediately.
The guide I used to build my docker image can be found here: http://blogs.msdn.com/b/webdev/archive/2015/01/14/running-asp-net-5-applications-in-linux-containers-with-docker.aspx
Are there logs that I can view to tell me why my docker image stopped working?
Is it possible to connect to an MSSQL server using ASP.NET 5 within a Docker container on a Linux server?
My Web.Config is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=<mssql_server_fqdn>; Initial Catalog=<db_name>; User ID=<username>; Password=<password>" />
</connectionStrings>
<system.web>
</system.web>
</configuration>
My Model is as follows:
using System;
using System.Data.Entity;
namespace TestMvc.Models
{
public class Car
{
public string Make { get; set; }
}
public class DefaultConnection : DbContext
{
public DbSet<Car> Cars { get; set; }
}
}

Custom Role Provider not called. What am I doing wrong?

So I'm trying to create a Hello World custom Role Provider-solution in ASP.NET MVC 4.
Basically I've set authentication mode="Windows" in web.config along with defining a role provider like this:
<roleManager enabled="true" defaultProvider="MyRoleProvider">
<providers>
<clear />
<add name="MyRoleProvider" type="MyProject.Code.MyRoleProvider" />
</providers>
</roleManager>
Then I've decorated the About controller method like this:
[Authorize(Roles = "SomeRole")]
public ActionResult About()
{ /* ... */ }
The custom RoleProvider-class looks like this:
namespace MyProject.Code {
public class MyRoleProvider : RoleProvider
{
public override bool IsUserInRole(string username, string roleName)
{
if (roleName == "SomeRole" && username = "Administrator") return true;
return false;
}
public override string[] GetRolesForUser(string username)
{
return new string[] { "SomeRole" };
}
/* a bunch of other overridden methods simply throwing not implementedException */
}
}
Now the thing is I've put a breakpoint on every single executable line of code in MyRoleProvder but none are hit. I have tested that breakpoints elsewhere are hit so the debugger is not the problem. Why isn't my code in the role provided executed? I was expecting IsUserInRole and/or GetRolesForUser to be executed when I navigate to the About-page. Am I wrong? Have I configured something wrong?
Full web.config for reference
edit: The user is redirected to the login page when the about page is clicked. I now realize this is due to the user actually is not authenticated yet. Authorization naturally happens after authentication. Is IISExpress not providing Windows identity?
As this is the first result in a google search i want to give a solution, maybe for others:
To use the windows identity in IIEExpress you have to activate it in your applicationhost.config , which is located in
[SolutionDir].vs\config\applicationhost.config
there you can find the xml tag
<configuration>
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="false">
change enabled="false" to enabled="true"
and you can use windows authenticatuion in IISExpress
I think your type declaration is incomplete, you should include both the full name and the assembly name.
type="MyProject.Code.MyRoleProvider, MyProject"
You might also need to set Version, Culture and PublicKeyToken if your assemblies are place in the GAC
Hope this helps

Mysql syntax error while creating Database for Entity Framework

I'm playing around with asp.net for the first time. I want to use it with a MySQL database because this is what is offered by my hosting service and I don't want to upgrade/change services. I'm using visual web developer 2010 express. I created an MVC 4 project from the default template. The template created the ASP.NET Simple Membership objects which is what I'm trying to get working. The project builds and runs correctly when using the default database connection string. When I change the web.config file to point to MySQL I get the following error when I attempt to navigate to any of the pages in the account folder.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'IDENTITY,
RoleName nvarc' at line 2
When I open the MySQL work bench and connect to the local server I notice that the database has been created. If I drop the DB and run the app again it gets recreated. I'm note sure if it was created correctly or if the entire database was created but there is something there.
Obviously there is an issue with the SQL syntax that is created by the Entity Framework. Do I need to add something to the web.config file to tell it what syntax it should use when creating the queries?
I've been searching for an answer to this for the past two days. any help pointing in the right direction would be appreciated.
I'm using mysql server version 5.5.27. and connector 6.5.4.0
here is the mysql part of my web.config file:
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient"/>
<add name="MySQL Data Provider"
invariant="MySql.Data.MySqlClient"
description=".Net Framework Data Provider for MySQL"
type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-MyWebPage-20120817115958;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
<add name="myDatabaseConnection" connectionString="server=localhost;Port=3306;uid=root;pwd=****;database=myDatabase;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
Edit adding code
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("LocalMySqlServer", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
public class UsersContext : DbContext
{
public UsersContext()
: base("LocalMySqlServer")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
Try to modify the source of the SMP and remove the syntax specific to ms sql server.
The role provider is still defaulting to the standard ASP one which is expecting a SQLServer DB on the end of the connection, "Identity" is SQLServerese for "autoinc".
You can set the default providers in the web.config like this:-
<configuration>
<system.web>
<profile defaultProvider="MySQLProfileProvider"></profile>
<roleManager defaultProvider="MySQLRoleProvider"></roleManager>
</system.web>
</configuration>

Resources