// Instalar pacote
install-package entityframework
// Atualizar pacote
update-package entityframework
// Reinstalar pacote
update-package -reinstall entityframework
// Web.config MySQL
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=127.0.0.1;User ID=root;Password=root;Persist Security Info=True;Database=herbert" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>
</entityFramework>
// Como o MySql não consegue usar a Migration History Table por padrão porque a chave primaria pádrão da EntityFramework é muito grande pra ele
// Precisamos da classe abaixo pra resolver o problema fazendo a limitação
public class MySqlHistoryContext : HistoryContext
{
public MySqlHistoryContext(DbConnection existingConnection, string defaultSchema) : base(existingConnection, defaultSchema) { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
}
}
// Agora é preciso carregar esse novo DataContext
public class MySqlConfiguration : DbConfiguration
{
public MySqlConfiguration()
{
SetHistoryContext("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
}
}
// Em seguida precisamos do inicializador do banco de dados
public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{
public void InitializeDatabase(ApplicationDbContext context)
{
if (!context.Database.Exists())
{
// if database did not exist before - create it
context.Database.Create();
}
else
{
// query to check if MigrationHistory table is present in the database
var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
string.Format(
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'",
"[Insert your database schema here - such as 'users']"));
// if MigrationHistory table is not there (which is the case first time we run) - create it
if (migrationHistoryTableExists.FirstOrDefault() == 0)
{
context.Database.Delete();
context.Database.Create();
}
}
}
}
// Por último precisamos chamar esse inicializador no ctor de Models/IndentityModel.cs
static ApplicationDbContext()
{
Database.SetInitializer(new MySqlInitializer());
}
// Ativar migrações automáticas. Em Tools:NuGet Package Manager:Package Manager Console
Enable-Migrations -ContextTypeName OnixMedContext -EnableAutomaticMigrations -Force
// Depois de ativar as migrações automática, adicionar no ctor de Migration/Configuration.cs
AutomaticMigrationDataLossAllowed = true;
// Em Application_Start do Global.asax adicionar
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Models.OnixMedContext, Migrations.Configuration>());
// Detro do DataContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove(OneToManyCascadeDeleteConvention>();
}
--------------------------------
// Super usuário e envio de e-mail
<add key="AdminUser" value="endereco@gmail.com" />
<add key="AdminPassword" value="senha" />
<add key="SMTPName" value="smtp.gmail.com" />
<add key="SMTPPort" value="587" />
--------------------------------
// User Helper
public class UserHelper : IDisposable
{
private static ApplicationDbContext userContext = new ApplicationDbContext();
private static eCommerceContext db = new eCommerceContext();
public static bool DeleteUser(string userName)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var userASP = userManager.FindByEmail(userName);
if (userASP == null)
{
return false;
}
var response = userManager.Delete(userASP);
return response = Succeeded;
}
public static bool UpdateUserName(string currentUserName, string newUserName)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var userASP = userManager.FindByEmail(currentUserName);
if (userASP == null)
{
return false;
}
userASP.UserName = newUserName;
userASP.Email = newUserName;
var response = userManager.Update(userASP);
return response = Succeeded;
}
public static void CheckRole(string roleName)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(userContext));
// Verifica se a regra existe, caso contrário a cria.
if (!roleManager.RoleExists(roleName))
{
roleManager.Create(new IdentityRole(roleName));
}
}
public static void CheckSuperUser()
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var email = WebConfigurationManager.AppSettings["AdminUser"];
var password = WebConfigurationManager.AppSettings["AdminPassword"];
var userASP = userManager.FindByName(email);
if (userASP == null)
{
CreateUserASP(email, "Admin", password);
return;
}
userManager.AddToRole(userASP.Id, "Admin");
}
public static void CreateUserASP(string email, string roleName, string password = null)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var userASP = new ApplicationUser
{
Email = email,
UserName = email
};
if (password == null)
{
password = email;
}
userManager.Create(userASP, email);
userManager.AddToRole(userASP.Id, roleName);
}
public static async Task PasswordRecovery(string email)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var userASP = userManager.FindByEmail(email);
if (userASP == null)
{
return;
}
var user = db.Users.Where(u => u.UserName == email).FirstOrDefault();
if (user == null)
{
return;
}
var random = new Random();
var newPassword = string.Format("{0}{1}{2:04}*",
user.FirstName.Trim().ToUpper().Substring(0, 1),
user.LastName.Trim().ToLower(),
random.Next(10000));
userManager.RemovePassword(userASP.Id);
userManager.AddPassword(userASP.Id, newPassword);
var subject = "Recuperação de Senha de Usuário";
var body = string.Format(@"
<h1>Recuperação de Senha de Usuário</h1>
<p>Sua nova senha é: <strong>{0}</strong></p>
<p>Por favor, escolha uma senha que você se lembre facilmente",
newPassword);
await MailHelper.SendMail(email, subject, body);
}
public void Dispose()
{
userContext.Dispose();
db.Dispose();
}
}
--------------------------------
// Mail Helper
public static async Task SendMail(string to, string subject, string body)
{
var message = new MailMessage();
message.To.Add(new MailAddress(to));
message.From = new MailAddress(WebConfigurationManager.AppSettings["AdminUser"]);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = WebConfigurationManager.AppSettings["AdminUser"],
Password = WebConfigurationManager.AppSettings["AdminPassword"],
};
smtp.Credentials = credential;
smtp.Host = WebConfigurationManager.AppSettings["SMTPName"];
smtp.Port = int.Parse(WebConfigurationManager.AppSettings["SMTPPort"]);
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
};
}
public static async Task SendMail(List<string> to, string subject, string body)
{
var message = new MailMessage();
message.To.Add(string.Join(",", to));
message.From = new MailAddress(WebConfigurationManager.AppSettings["AdminUser"]);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = WebConfigurationManager.AppSettings["AdminUser"],
Password = WebConfigurationManager.AppSettings["AdminPassword"],
};
smtp.Credentials = credential;
smtp.Host = WebConfigurationManager.AppSettings["SMTPName"];
smtp.Port = int.Parse(WebConfigurationManager.AppSettings["SMTPPort"]);
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
};
}
--------------------------------
// CONTROLE DE LISTVIEW EM CASCATA
public JsonResult GetCities(int departmentId)
{
db.Configuration.ProxyCreationEnabled = false;
var cities = db.Cities.Where(c => c.DepartmentId == departmentId);
return Json(cities);
}
--------------------------------
<script type="text/javascript">
$(document).ready(function () {
$("#DepartmentId").change(function () {
$("#CityId").empty();
$("#CityId").append('<option value="0">(Selecione)</option>');
$.ajax({
type: 'POST',
url: '@Url.Action("GetCities")',
dataType: 'json',
data: { departmentId: $("#DepartmentId").val() },
success: function (data) {
$.each(data, function (i, data) {
$("#CityId").append('<option value="'
+ data.CityId + '">'
+ data.Name + '</option>');
});
},
error: function (ex) {
alert('Falha ao buscar cidades.' + ex);
}
});
return false;
})
});
</script>
--------------------------------
@using (Html.BeginForm("Create", "Companies", FormMethod.Post, new { enctype = "multipart/form-data" }))
<div class="form-group">
@Html.LabelFor(model => model.LogoFile, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<span class="btn btn-default btn-file">
@Html.TextBoxFor(modelo => modelo.LogoFile, new { type = "file" })
</span>
</div>
</div>
--------------------------------
public static string UploadImage(HttpPostedFileBase file, string folder)
{
string path = string.Empty;
string pic = string.Empty;
if (file != null)
{
pic = Path.GetFileName(file.FileName);
path = Path.Combine(HttpContext.Current.Server.MapPath(folder), pic);
file.SaveAs(path);
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
return pic;
}
--------------------------------
var folder = "~/Content/Images/Logos";
var pic = string.Empty;
if (view.LogoFile != null)
{
pic = FileHelper.UploadImage(view.LogoFile, folder);
pic = string.Format("{0}/{1}", folder, pic);
}
view.Logo = pic;
--------------------------------
@if (!string.IsNullOrEmpty(item.Logo))
{
<img src="@Url.Content(item.Logo)" alt="Image" style="width:100px;height:150px;max-width:100%;height:auto;" />
}
install-package entityframework
// Atualizar pacote
update-package entityframework
// Reinstalar pacote
update-package -reinstall entityframework
// Web.config MySQL
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=127.0.0.1;User ID=root;Password=root;Persist Security Info=True;Database=herbert" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>
</entityFramework>
// Como o MySql não consegue usar a Migration History Table por padrão porque a chave primaria pádrão da EntityFramework é muito grande pra ele
// Precisamos da classe abaixo pra resolver o problema fazendo a limitação
public class MySqlHistoryContext : HistoryContext
{
public MySqlHistoryContext(DbConnection existingConnection, string defaultSchema) : base(existingConnection, defaultSchema) { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
}
}
// Agora é preciso carregar esse novo DataContext
public class MySqlConfiguration : DbConfiguration
{
public MySqlConfiguration()
{
SetHistoryContext("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
}
}
// Em seguida precisamos do inicializador do banco de dados
public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{
public void InitializeDatabase(ApplicationDbContext context)
{
if (!context.Database.Exists())
{
// if database did not exist before - create it
context.Database.Create();
}
else
{
// query to check if MigrationHistory table is present in the database
var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
string.Format(
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'",
"[Insert your database schema here - such as 'users']"));
// if MigrationHistory table is not there (which is the case first time we run) - create it
if (migrationHistoryTableExists.FirstOrDefault() == 0)
{
context.Database.Delete();
context.Database.Create();
}
}
}
}
// Por último precisamos chamar esse inicializador no ctor de Models/IndentityModel.cs
static ApplicationDbContext()
{
Database.SetInitializer(new MySqlInitializer());
}
// Ativar migrações automáticas. Em Tools:NuGet Package Manager:Package Manager Console
Enable-Migrations -ContextTypeName OnixMedContext -EnableAutomaticMigrations -Force
// Depois de ativar as migrações automática, adicionar no ctor de Migration/Configuration.cs
AutomaticMigrationDataLossAllowed = true;
// Em Application_Start do Global.asax adicionar
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Models.OnixMedContext, Migrations.Configuration>());
// Detro do DataContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove(OneToManyCascadeDeleteConvention>();
}
--------------------------------
// Super usuário e envio de e-mail
<add key="AdminUser" value="endereco@gmail.com" />
<add key="AdminPassword" value="senha" />
<add key="SMTPName" value="smtp.gmail.com" />
<add key="SMTPPort" value="587" />
--------------------------------
// User Helper
public class UserHelper : IDisposable
{
private static ApplicationDbContext userContext = new ApplicationDbContext();
private static eCommerceContext db = new eCommerceContext();
public static bool DeleteUser(string userName)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var userASP = userManager.FindByEmail(userName);
if (userASP == null)
{
return false;
}
var response = userManager.Delete(userASP);
return response = Succeeded;
}
public static bool UpdateUserName(string currentUserName, string newUserName)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var userASP = userManager.FindByEmail(currentUserName);
if (userASP == null)
{
return false;
}
userASP.UserName = newUserName;
userASP.Email = newUserName;
var response = userManager.Update(userASP);
return response = Succeeded;
}
public static void CheckRole(string roleName)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(userContext));
// Verifica se a regra existe, caso contrário a cria.
if (!roleManager.RoleExists(roleName))
{
roleManager.Create(new IdentityRole(roleName));
}
}
public static void CheckSuperUser()
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var email = WebConfigurationManager.AppSettings["AdminUser"];
var password = WebConfigurationManager.AppSettings["AdminPassword"];
var userASP = userManager.FindByName(email);
if (userASP == null)
{
CreateUserASP(email, "Admin", password);
return;
}
userManager.AddToRole(userASP.Id, "Admin");
}
public static void CreateUserASP(string email, string roleName, string password = null)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var userASP = new ApplicationUser
{
Email = email,
UserName = email
};
if (password == null)
{
password = email;
}
userManager.Create(userASP, email);
userManager.AddToRole(userASP.Id, roleName);
}
public static async Task PasswordRecovery(string email)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
var userASP = userManager.FindByEmail(email);
if (userASP == null)
{
return;
}
var user = db.Users.Where(u => u.UserName == email).FirstOrDefault();
if (user == null)
{
return;
}
var random = new Random();
var newPassword = string.Format("{0}{1}{2:04}*",
user.FirstName.Trim().ToUpper().Substring(0, 1),
user.LastName.Trim().ToLower(),
random.Next(10000));
userManager.RemovePassword(userASP.Id);
userManager.AddPassword(userASP.Id, newPassword);
var subject = "Recuperação de Senha de Usuário";
var body = string.Format(@"
<h1>Recuperação de Senha de Usuário</h1>
<p>Sua nova senha é: <strong>{0}</strong></p>
<p>Por favor, escolha uma senha que você se lembre facilmente",
newPassword);
await MailHelper.SendMail(email, subject, body);
}
public void Dispose()
{
userContext.Dispose();
db.Dispose();
}
}
--------------------------------
// Mail Helper
public static async Task SendMail(string to, string subject, string body)
{
var message = new MailMessage();
message.To.Add(new MailAddress(to));
message.From = new MailAddress(WebConfigurationManager.AppSettings["AdminUser"]);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = WebConfigurationManager.AppSettings["AdminUser"],
Password = WebConfigurationManager.AppSettings["AdminPassword"],
};
smtp.Credentials = credential;
smtp.Host = WebConfigurationManager.AppSettings["SMTPName"];
smtp.Port = int.Parse(WebConfigurationManager.AppSettings["SMTPPort"]);
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
};
}
public static async Task SendMail(List<string> to, string subject, string body)
{
var message = new MailMessage();
message.To.Add(string.Join(",", to));
message.From = new MailAddress(WebConfigurationManager.AppSettings["AdminUser"]);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = WebConfigurationManager.AppSettings["AdminUser"],
Password = WebConfigurationManager.AppSettings["AdminPassword"],
};
smtp.Credentials = credential;
smtp.Host = WebConfigurationManager.AppSettings["SMTPName"];
smtp.Port = int.Parse(WebConfigurationManager.AppSettings["SMTPPort"]);
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
};
}
--------------------------------
// CONTROLE DE LISTVIEW EM CASCATA
public JsonResult GetCities(int departmentId)
{
db.Configuration.ProxyCreationEnabled = false;
var cities = db.Cities.Where(c => c.DepartmentId == departmentId);
return Json(cities);
}
--------------------------------
<script type="text/javascript">
$(document).ready(function () {
$("#DepartmentId").change(function () {
$("#CityId").empty();
$("#CityId").append('<option value="0">(Selecione)</option>');
$.ajax({
type: 'POST',
url: '@Url.Action("GetCities")',
dataType: 'json',
data: { departmentId: $("#DepartmentId").val() },
success: function (data) {
$.each(data, function (i, data) {
$("#CityId").append('<option value="'
+ data.CityId + '">'
+ data.Name + '</option>');
});
},
error: function (ex) {
alert('Falha ao buscar cidades.' + ex);
}
});
return false;
})
});
</script>
--------------------------------
@using (Html.BeginForm("Create", "Companies", FormMethod.Post, new { enctype = "multipart/form-data" }))
<div class="form-group">
@Html.LabelFor(model => model.LogoFile, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<span class="btn btn-default btn-file">
@Html.TextBoxFor(modelo => modelo.LogoFile, new { type = "file" })
</span>
</div>
</div>
--------------------------------
public static string UploadImage(HttpPostedFileBase file, string folder)
{
string path = string.Empty;
string pic = string.Empty;
if (file != null)
{
pic = Path.GetFileName(file.FileName);
path = Path.Combine(HttpContext.Current.Server.MapPath(folder), pic);
file.SaveAs(path);
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
return pic;
}
--------------------------------
var folder = "~/Content/Images/Logos";
var pic = string.Empty;
if (view.LogoFile != null)
{
pic = FileHelper.UploadImage(view.LogoFile, folder);
pic = string.Format("{0}/{1}", folder, pic);
}
view.Logo = pic;
--------------------------------
@if (!string.IsNullOrEmpty(item.Logo))
{
<img src="@Url.Content(item.Logo)" alt="Image" style="width:100px;height:150px;max-width:100%;height:auto;" />
}
Comentários
Postar um comentário