How use MySQL membership in mvc4 code first application? - mysql

I am new in MVC with MySQL. I have code first application in MVC 4 with MySQL.
public class Category
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public virtual IEnumerable<Product> Products { get; set; }
}
public class Product
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public DateTime CreateDate { get; set; }
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
And in web.config:
<connectionStrings>
<add name="MyContext" connectionString="server=localhost; User Id=root; Pwd=mypass; Persist Security Info=True; database=catalogue" providerName="MySql.Data.MySqlClient " />
</connectionStrings>
So, this creates catalogue database in mysql. But i want also to use membership of mysql. To register, to create users and manage their roles.
For example, using default AccountModels of mvc4
I added this code to web.config:
<system.web>
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<clear />
<remove name="MySQLMembershipProvider" />
<add name="MySQLMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="/" description="MySQL default application" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="True" autogenerateschema="True" enablePasswordRetrieval="True" enablePasswordReset="True" requiresQuestionAndAnswer="False" requiresUniqueEmail="False" passwordFormat="Clear" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
</providers>
</membership>
<profile defaultProvider="MySQLProfileProvider">
<providers>
<clear />
<remove name="MySQLProfileProvider" />
<add name="MySQLProfileProvider" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="/" description="Profiles" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="False" autogenerateschema="True" />
</providers>
</profile>
<roleManager enabled="false" defaultProvider="MySQLRoleProvider">
<providers>
<clear />
<remove name="MySQLRoleProvider" />
<add name="MySQLRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="/" description="Project Roles" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="True" autogenerateschema="True" />
</providers>
</roleManager>
</system.web>
When run application I get this error:
Which step have I forgot? I cant use membership.
(Sorry for bad English)

If what you want is to use the Membership Provider that comes shipped with MVC4 Internet Templates of VS2010 or VS2012, with a database other than SQL Server Family, namely SQL Server, SQL Compact and Azure, I think that is not feasible, since MVC4 uses SimpleMembership provider, which is not Database Agnostic.
Have said that, that doesn't mean that you can't achieve what you want. I propose to use Microsoft ASP.NET Universal Providers Core Libraries. I recommend that you read this excellent Post
Now in this article the author, Scott Hanselman, mentions the following
Using these Universal "Default Profile Providers" means all you have to do is set the right connection string and your applications that use these services will work with SQL Server (plus Express), SQL Server Compact and SQL Azure with no code changes from you.
Hmmm and how about other SQL Standards?, well let's follow these steps,
1) Make sure to change the connection string first, and then with the Nuget Package Manager, install MySQL.Web, and MySQL.Data.
<connectionStrings>
<add name="MySQLConn" connectionString="Server=localhost;Database=dbname;Uid=dbuser;Pwd=dbpass;" />
</connectionStrings>
2) With the Nuget Package Manager find and install the "Microsoft ASP.NET Universal Providers Core Libraries" or run the following commands in the Package Manager Console,
Install-Package system.web.providers
Install-Package Microsoft.AspNet.Providers.Core
3) Go to Project Menu -> ASP.Net Configuration, you will see in the browser ASP Net Administration tool for your web project.
4) Then go to Provider Tab, Go to "Select a different provider for each feature (advanced)"
5) Make sure to select MySQL Membership Provider.
6) Then go Security Tab, and create some Roles and Users that you consider necessary for your project.
If for some reason you get an error here, try changing your web config, and replace Membership, Role and Profile with this
7) Enjoy!
I hope this helps
PS: I'm very new on this too, so I'm open to suggestion about the best Membership Provider for MVC4 that targets others SQL Databases.

As a side note, you can not use the same Account Controller, of the Internet Template of ASP Net MVC3 or MVC4 of VS2010 or VS2012. Though you have to implement that all by yourself.
You can use for example Security Guard if you want to quickly add MVC template for Login/Logoff/Role Administration/Create Users etc.
The method that I proposed is not a patch nor is hackerish, ASP Net Membership Provider were long implemented and promoted by Microsoft and MySQL added the functionality to the Net. Connector, and they even have posted about it. Here
So fear not, you can safely use this method, unless there is a strong argument against using ASP Net Membership Provider, that I'm not aware of.

This is taken from GridWizzard - you just need set enableSimpleMembership to false under appsettings, http://gridwizard.wordpress.com/2014/03/05/asp-net-mvc4-just-get-it-running-without-having-to-implement-membershiproleprovider/

Related

Web.config equivalent to “using static MyClass;” in <add namespace=“MyClass” />

In ASP.Net, you can add a namespace to all Razor views by adding the following code to the View folder’s Web.config:
<system.web.webPages.razor>
<namespaces>
<add namespace=“MyClass” />
</namespaces>
</system.web.webPages.razor>
This is equivalent to putting the statement “using MyClass;” at the top of a C# file.
However, how would I add a namespace to Web.config as a “static” class, where I can access the class’s methods directly within views without having to write out “MyClass.MyMethod();” for example?
You can already do this by putting the statement “using static MyClass;” at the top of a C# file (C# 6 is required, see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-static).
It just appends whatever it is you put as namespace. Just needs to append the static keyword to the namespace.
So as you pointed out <add namespace=“MyClass” /> is equivalent to using MyClass;
Change to <add namespace=“static MyClass” />, which is equivalent to using static MyClass;
In your case:
<system.web.webPages.razor>
<namespaces>
<add namespace=“static MyClass” />
</namespaces>
</system.web.webPages.razor>
should be what you're looking for

How to use two connection strings on development vs production

I have two connection strings in my Web.config.
<connectionStrings>
<add name="AuthContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=mokey;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="AuthContextMySQL" providerName="MySql.Data.MySqlClient" connectionString="database=mokey;persistsecurityinfo=True" />
</connectionStrings>
I can specify which one to use in code like this:
public class AuthContext : IdentityDbContext<IdentityUser>
{
public AuthContext()
: base("AuthContextMySQL")
{
}
}
How do I specify which one to use depending on development vs production?
You can use web.config transformations during your build step to add/update/delete sections of your web.config depending on the build configuration. See this article for a step by step guide.

Does EF fully support ANY cross-platform database?

For past few hours, I tried to "port" my current project from Sql Server to MySQL, I ended up with errors like:
The underlying provider does not support the type varchar(max) (or
uniqueidentifier, or something else)
I use POCO, and Code First - I thought, that one of the purposes of EF was to provide easy repository "switching", but it would seam that even basic types are not mapped correctly :/
I also tried SQlite but it is even in worst shape, and as far as I know, Postrage SQL support is also lacking.
So... question is - is there any cross-platform (preferably free) database out there that has real (SQL Server like) support in EF?
Thanks in advance.
Best regards.
Edit:
To by more specific about my approach:
I use POCO, and Code First, I want to automatically create the database if it doesn't exists, I don't use anything special inside my POCO classes, just standard .NET types. Example POCO looks like this:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
[StringLength(128)]
public string Name { get; set; }
[Required]
public int AgencyID { get; set; }
[Required]
public bool IsEnabled { get; set; }
#region NavigationProperties
[NavigationProperty]
public virtual Agency Agency { get; set; }
#endregion
Edit2:
My app.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<!--<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>-->
<defaultConnectionFactory type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
</entityFramework>
</configuration>
You seem to have SqlServer set as your defaultConnectionFactory in the app/wbeb.config file which results in EF using SqlServer types. You need to set the defaultConnectionFactory to a MySQL connection factory.
I struggled with this same error all night. The fix was counter-intuitive but so far so good... It does seem that the issue had to do with old migrations that were set up with LocalDB (SQL Server) yet even deleting the old migrations had no effect. I also spent lots of unnecessary time fiddling with my Web.config, Database Context, etc... I suggest trying the following before banging your head on the wall...
Delete the migrations folder
Try enabling migrations and adding your initial migration (in the PM type "enable-migrations" and then "add-migration init")
If you get the above error in the PM, delete the migrations folder again, then open up MySQL Workbench
Within MySQL Workbench, locate the Schema with the name you gave in your connectionString (will look like database=whateverYouCalledIt)
In that schema, open the tables and find "__migrationhistory"
Right click that table, click select rows, and delete any existing migration entries, then repeat step 2
For some reason this did the trick for me when deleting migrations in the solution explorer had no effect. Apparently, that didn't delete the migration history in the database...
And for the record to the OP, this worked just fine with ASP.net Identity and the MVC Auth system... I think SimpleMembership is now antiquated but then I'm not developing desktop apps...

Mvc-Mini-Profiler v1.7 on EF 4.1 Code-First project doesn't profile SQL

I setup MiniProfiler.MVC3 - 1.7 package in my project yesterday. The Controller and view profiling is working fine, but the peice I'm really interested in is the SQL Profiling. I have not been able to get this to work. I'm using EF Code First with a SQL 2008 database.
I have followed all the suggestions in this post ..
mvcminiprofiler-on-ef-4-1-code-first-project-doesnt-profile-sql
In the miniprofiler.cs i have my SQL connection setup as...
var factory = new SqlConnectionFactory(ConfigurationManager.ConnectionStrings["CMDBMVC3"].ConnectionString);
My Web.config db connection is...
<add name="CMDBMVC3" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI; AttachDBFilename=|DataDirectory|CMDB_MVC3.mdf;Initial Catalog=CMDB_MVC3;Trusted_Connection=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
If I put a breakpoint on the mini-profiler line it points to the correct db connection. I'm not sure what else to do at this point. I would appreciate any direction on how to get the SQL profiling working.
I use EF Code first and the mini profiler within my Context constructor I create a new connection factory and pass this to the ProfiledDbConnectionFactory method this returns a profiled connection that you can then set as the DefaultConnectionFactory of the context.
public MyConext()
{
var factory = new ConnectionFactory();
var profiled = new MvcMiniProfiler.Data.ProfiledDbConnectionFactory(factory);
Database.DefaultConnectionFactory = profiled;
}
The connection Facotry just returns a new sql connection
public class ConnectionFactory :IDbConnectionFactory
{
public DbConnection CreateConnection()
{
var cnn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["SomeConnection"].ToString());
return cnn;
}
You also need to add the ProfiledDBProvider to the web config file. Make sure the version number is correct for you.
<system.data>
<DbProviderFactories>
<remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
<add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider"
description="MvcMiniProfiler.Data.ProfiledDbProvider"
type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler, Version=1.7.0.0, Culture=neutral, PublicKeyToken=b44f9351044011a3" />
</DbProviderFactories>
</system.data>
This works fine for me in both MVC and asp.net webforms using the Miniprofiler nuget package. I'd also check out the new MVC version of the nuget package that auto configs profiling as part of a global action filter.

How to send email in HTML format with Microsoft Enterprise Library?

I know how to send mails using the Microsoft Enterprise Library 2.0 using a text formatter. But these emails are always in plain text. Is there any way with entlib 2.0 to send these mails in HTML format?
Well that is funny, I am now writing my own answer.
What I did was use the source code of entlib.
Within
Microsoft.Practices.EnterpriseLibrary.Logging and
Microsoft.Practices.EnterpriseLibrary.Logging.TraceListenerData
I found the classes that I needed.
Copy EmailMessage.cs to EmailMessageHTML.cs
Copy EmailTraceListener.cs to EmailHTMLTraceListener.cs
Copy EmailTraceListenerData.cs to EmailHTMLTraceListenerData.cs
Put these classes in your own new Library Project.
Within EmailMessageHTML change all constructors to match the new classname and than ADD following line to the method:
protected MailMessage CreateMailMessage()
{
.....
message.IsBodyHtml = true;
.....
return message;
}
After that, I had to use this new EmailMessageHTML class in EmailHTMLTraceListener (change EmailMessage to EmailMessageHTML) and also use this EmailHTMLTraceListener in the new EmailHTMLTraceListenerData.cs file.
Compile this new project and than use this in your config as follows (example)
<loggingConfiguration
name="Logging Application Block"
tracingEnabled="true"
defaultCategory=""
logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add toAddress="your#emailgoes.here"
fromAddress="yourserveraddress#goes.here"
subjectLineStarter=""
subjectLineEnder="My HTMLemailLogger"
smtpServer="localhost" smtpPort="25"
formatter="Text Formatter"
listenerDataType="MYLibrary.HTMLEmailLogger.EmailHTMLTraceListenerData,
MYLibrary.HTMLEmailLogger, Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=null"
traceOutputOptions="None"
type="MYLibrary.HTMLEmailLogger.EmailHTMLTraceListener,
MYLibrary.HTMLEmailLogger,
Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=null"
name="EmailHTML TraceListener"/>
</listeners>
</loggingConfiguration>
and add a valid category to log this to of course:
<add switchValue="All" name="OutOfBalanceBooking">
<listeners>
<add name="Database Trace Listener"/>
<add name="EmailHTML TraceListener"/>
</listeners>
</add>
Of course you need some HTML document to than log with EntLib. I leave that as an exercise for the reader.
And indeed! I get a nice HTML email now for every outofbalance booking that customers make on the site...