SimpleMembershipProvider MinRequiredPasswordLength always returns 0 despite it being defined as 6 in Web.config membership provider section - web-config

I switched to SimpleMembershipProvider in an ASP.NET MVC 4 app. Everything else is working great but there's this problem...
When I try this code:
var password = Membership.GeneratePassword(Membership.MinRequiredPasswordLength, 0);
MinRequiredPasswordLength is always 0. The settings defined in the membership provider's Web.config section are not being read.
Here's the Membership default provider Web.config section:
<membership defaultProvider="AspNetSqlMembershipProvider">
<providers>
<clear />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="DefaultConnection"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/Acad" />
</providers>
</membership>
Here's the debug info I get:
Any hints?
Is the SimpleMembershipProvider so simple that it doesn't even use the Web.config section?
Solution for the moment
To overcome the SimpleMembershipProvider current limitation, I used this code to grab the value defined in Web.config:
MembershipSection membershipSection = (MembershipSection)WebConfigurationManager.GetSection("system.web/membership");
var defaultProvider = membershipSection.DefaultProvider;
ProviderSettings providerSettings = membershipSection.Providers[defaultProvider];
var minRequiredPasswordLength = int.Parse(providerSettings.Parameters["minRequiredPasswordLength"]);

I switched to SimpleMembershipProvider in an ASP.NET MVC 4 app.
Erm, from the relevant section you have shown in your web.config this doesn't seem to be the case at all. You are sill using the AspNetSqlMembershipProvider.
If you want to switch to the SimpleMembershipProvider make sure that you have properly configured it:
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider"
type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"
/>
</providers>
</membership>
This being said the SimpleMembershipProvider doesn't support setting those properties via web.config. It doesn't even use it. If you want such functionality you will have to implement it yourself.

You can inherit from SimpleMembershipProvider and override MinRequiredPasswordLength:
public class YoursSimpleMembershipProvider : SimpleMembershipProvider
{
private const int MIN_REQUIRED_PASSWORD_LENGTH = 6;
private const int MIN_REQUIRED_NON_ALPHANUMERIC_CHARACTERS = 0;
public override int MinRequiredPasswordLength
{
get
{
return MIN_REQUIRED_PASSWORD_LENGTH;
}
}
}

I found if I put minRequiredPasswordLength="3" in web.config,like this:
<membership defaultProvider="SimpleMembershipProvider" >
<providers>
<clear/>
<add name="SimpleMembershipProvider"
type="WebMatrix.WebData.SimpleMembershipProvider,WebMatrix.WebData"
minRequiredPasswordLength="3"
/>
</providers>
</membership>
That no effect.
I find the secret in MODEL.If you create an Internet application template,in AccountModels.cs there is a "RegisterModel",just like this:
public class RegisterModel
{
[Required]
[Display(Name = "用户名")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "密码")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "确认密码")]
[Compare("Password", ErrorMessage = "密码和确认密码不匹配。")]
public string ConfirmPassword { get; set; }
}
In the Password property has a StringLength->MinimumLength .
I think that is!
Some features removed in SimpleMembershipProvider,See here:http://sharifhkhan.com/programming/features-removed-in-simplemembershipprovider/
Hope this help you.

Related

Evaluating object with List property

I try to evaluate this rule
<?xml version="1.0" encoding="utf-8"?>
<codeeffects
xmlns="http://codeeffects.com/schemas/rule/41"
xmlns:ui="http://codeeffects.com/schemas/ui/4">
<rule id="PerformCalculation" webrule="5.0.9.6" utc="2020-11-23T13:13:42.3010" type="domain_product.Configs.WorkflowEngine.MicroflowModel, domain-product, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" eval="false">
<definition>
<if>
<clause>
<rule id="40494eaf-4de0-4b3b-85b9-1c73473c2660" operator="doesNotExist">
<property name="e536c617_2636_47e8_93bb_66bb6c7fe3c0" />
</rule>
</clause>
<then>
<set>
<property name="775e6e9c_154f_45b3_9360_3d0a154ee19d" />
<value>test1</value>
</set>
</then>
</if>
</definition>
<format>
<lines />
</format>
</rule>
<rule id="40494eaf-4de0-4b3b-85b9-1c73473c2660" webrule="5.0.9.6" utc="2020-11-23T13:13:42.3010" type="transformify_template_api_factory_product.Domain.Model_cb958c7f_3681_40c5_573c_08d88fb1664f, DynamicAssembly.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" eval="true">
<definition>
<condition type="equal">
<property name="Godini" />
<value type="numeric">50</value>
</condition>
</definition>
<format>
<lines />
</format>
</rule>
</codeeffects>
The classes are
public class Model_710e265b_d07c_4c1b_573d_08d88fb1664f
{
[Field(DisplayName = "Ime")]
public string Ime { get; set; }
[Field(DisplayName = "Prezime")]
public string Prezime { get; set; }
[Field(DisplayName = "Godini")]
public int Godini { get; set; }
}
public class MicroflowModel
{
[Field(DisplayName = "Variables -> Persons")]
public List<Model_710e265b_d07c_4c1b_573d_08d88fb1664f> e536c617_2636_47e8_93bb_66bb6c7fe3c0{ get; set; }
[Field(DisplayName = "Variables -> var1")]
public string 775e6e9c_154f_45b3_9360_3d0a154ee19d { get; set; }
}
The class Model_710e265b_d07c_4c1b_573d_08d88fb1664f is a part of an assembly called 'DynamicAssembly.dll' that is not loaded into the app-domain, but the class exists.
The class MicroflowModel is a part of a dynamically created assembly, and is generated with TypeBuilder.
When evaluating objects without List properties, the evaluation process is ok.
When evaluating objects with lists from the 'DynamicAssembly.dll' assembly (like in the example), the Evaluator constructor fails with this Message:
Value cannot be null. (Parameter 'type')
and StackTrace:
at System.Linq.Expressions.Expression.Validate(Type type, Boolean allowByRef)
at System.Linq.Expressions.Expression.Parameter(Type type, String name)
at CodeEffects.Rule.Core.ExpressionBuilderBase.BuildRule(XElement element)
at CodeEffects.Rule.Core.ExpressionBuilderBase.Build(XElement element)
at CodeEffects.Rule.Core.ExpressionBuilderBase.BuildIfRule(XElement element)
at CodeEffects.Rule.Core.ExpressionBuilderBase.Build(XElement element)
at CodeEffects.Rule.Core.ExpressionBuilderBase.Build(IEnumerable`1 elements)
at CodeEffects.Rule.Core.ExpressionBuilderBase.GetSafeExpressionBody(XElement rule, Boolean addSourceNullCheck)
at CodeEffects.Rule.Core.ExpressionBuilder.GetPredicateExpression(XElement rule)
at CodeEffects.Rule.Core.Evaluator.CompileRule(XElement rule)
at CodeEffects.Rule.Core.EvaluatorBase..ctor(Type sourceType, String rulesetXml, EvaluationParameters parameters, IFlexDataProvider provider)
at CodeEffects.Rule.Core.Evaluator..ctor(Type sourceType, String rulesetXml, EvaluationParameters parameters)
at ...
Please help
You need to make that class available. The ExpressionBuilder must be able to load the type referenced in the internal rule (id="40494eaf-4de0-4b3b-85b9-1c73473c2660") using Type.GetType(), so as to build an expression tree.
Internally it calls
Type ruleType = Type.GetType("transformify_template_api_factory_product.Domain.Model_cb958c7f_3681_40c5_573c_08d88fb1664f, DynamicAssembly.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
Since it can't find it, the result is null and the next call to Expression.Parameter() fails.

I can't run migration (with .net core 3.0 and entity framework)

My .Net Core version is 3.0.100-preview6-012264. You can ask me why I use the preview version. The main reason is useful work with GRPC (scaffolding for this). Now I would like to use entity framework in my project. I have the following .csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Protobuf Include="Protos\dashboard.proto" GrpcServices="Server" Generator="MSBuild:Compile" />
<Protobuf Include="Protos\users.proto" GrpcServices="Client" Generator="MSBuild:Compile" />
<Protobuf Include="Protos\anal.proto" GrpcServices="Client" Generator="MSBuild:Compile" />
<Content Include="#(Protobuf)" />
<None Remove="#(Protobuf)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="DimaRabbitLogger" Version="1.3.3" />
<PackageReference Include="Grpc.AspNetCore.Server" Version="0.1.22-pre1" />
<PackageReference Include="Google.Protobuf" Version="3.8.0" />
<PackageReference Include="Grpc.Tools" Version="1.21.0" PrivateAssets="All" />
<PackageReference Include="Grpc.Core" Version="1.21.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0-preview6.19304.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0-preview6.19304.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0-preview6.19304.10" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.0.0-preview5" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="System.Runtime.Serialization.Json" Version="4.3.0" />
</ItemGroup>
</Project>
And couple of very simple models:
Model Application:
public class Application
{
int ApplicationId { get; set; }
public string PackageName { get; set; }
public List<WorkspaceApplication> WorkspaceApplications { get; set; }
Model Workspace:
public class Workspace
{
public int WorkspaceId { get; set; }
public string Name { get; set; }
public List<WorkspaceApplication> WorkspaceApplications { get; set; }
}
Class for many-to-many relationship:
public class WorkspaceApplication
{
public int ApplicationId { get; set; }
public Application Application { get; set; }
public string WorkspaceId { get; set; }
public Workspace Workspace { get; set; }
}
And my application context:
public class ApplicationContext : DbContext
{
private readonly string _connectionString;
public DbSet<Workspace> Workspaces { get; set; }
public DbSet<Application> Applications { get; set; }
public ApplicationContext(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("DashboardDb");
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_connectionString, b => b.MigrationsAssembly("Dashboard"));
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<WorkspaceApplication>()
.HasKey(x => new {x.WorkspaceId, x.ApplicationId});
modelBuilder.Entity<WorkspaceApplication>()
.HasOne(x => x.Workspace)
.WithMany(x => x.WorkspaceApplications)
.HasForeignKey(x => x.WorkspaceId);
modelBuilder.Entity<WorkspaceApplication>()
.HasOne(x => x.Application)
.WithMany(x => x.WorkspaceApplications)
.HasForeignKey(x => x.ApplicationId);
}
}
I run the following console command:
dotnet ef migrations add FirstMigration
and have this error message:
Could not execute because the specified command or file was not found.
Possible cause:
* You have incorrectly typed builtin dotnet.
* You planned to run .NET Core, but dotnet-ef does not exist.
* You wanted to run the global tool, but the PATH specified in the PATH could not find the executable file with the dotnet prefix, which has this name.
This works nice with .Net Core 2.2. Where is the problem?
Starting with 3.0 the dotnet ef is not part of the .NET SDK anymore.
Old behavior
Before 3.0, the dotnet ef tool was included in the .NET Core SDK and was readily available to use from the command line from any project without requiring extra steps.
New behavior
Starting in 3.0, the .NET SDK does not include the dotnet ef tool, so before you can use it you have to explicitly install it as a local or global tool.
To install it, you can run this:
dotnet tool install --global dotnet-ef --version 3.0.0-*
Then you should be able to run normal ef-core commands like dotnet ef migrations add ...
Don't forget to add the path to dotnet tools in the PATH variable of your OS. For example if you use linux ubuntu and zsh as shell you have to add the following int your .zshrc file:
export PATH=$PATH:$HOME/.dotnet/tools

Connection string could not be found running azure function and entity framework

I've have an Asp.Net MVC app in one project and I moved my db context file used to connect to Entity Framework into it's own project, so that I can access EF from both my Asp.Net MVC app and my Azure Function apps. But running the Azure Function throws an exception when trying to get the connection string.
No connection string named 'YogaBandyDatabase' could be found in the application config file.
I tried putting the connection string into the app.config file for the .DataLayer project and I tried putting the connection string into the local.settings.json file and I tried putting the connection string into the portal under application settings connection strings but I'm still getting this exception.
QUESTION - where is it looking for the connection string, it says the application config file? Which one? the one from the .DataLayer project? Did I put it in correctly to the app.config file?
Here is my project structure
Here is the error in the context file
Here is my context file in the .DataLayer project
namespace YogaBandy2017.Context
{
public class YogabandyContext : IdentityDbContext<ApplicationUser>
{
public YogabandyContext()
: base("name=YogaBandyDatabase")
{
}
public YogabandyContext(string connectionString)
: base(connectionString)
{
}
public static YogabandyContext Create()
{
return new YogabandyContext();
}
public DbSet<YogaBandyError> YogaBandyErrors { get; set; }
public DbSet<YogaProfile> YogaProfiles { get; set; }
public DbSet<YogaClass> YogaClasses { get; set; }
public DbSet<YogaSpaceEvent> YogaSpaceEvents { get; set; }
public DbSet<ReportImage> ReportImages { get; set; }
public DbSet<ReportProfile> ReportProfiles { get; set; }
public DbSet<ReportSpace> ReportSpaces { get; set; }
public DbSet<YogaSpace> YogaSpaces { get; set; }
public DbSet<YogaSpaceFollower> YogaSpaceFollower { get; set; }
public DbSet<YogaProfileFollower> YogaProfileFollower { get; set; }
public DbSet<RegisteredStudent> RegisteredStudents { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
}
}
Here is the local.settings.json file with the connection string (maybe syntax is incorrect)
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "the string",
"AzureWebJobsDashboard": "",
"yogabandy2017_RootManageSharedAccessKey_SERVICEBUS": "the string"
},
"ConnectionStrings": {
"YogaBandyDatabase": "the string"
}
}
Here is the connection string in the app.config file for the .DataLayer project
<?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>
<connectionStrings>
<add name="YogaBandyDatabase" connectionString="my string" providerName="System.Data.SqlClient" />
<add name="YogaBandyErrorDatabase" connectionString="my string" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
This one is a little tricky. Log into the Azure portal and navigate to your Function. Click on the Application Settings link on the Overview tab for your Function. Place your EF connection string under the Connection Strings section.

Conflict "add-migration" and "update-database" result for entity framework code base migration

I tried to run code base entity framework migration. And I always get this error (except the initial migration) when run "add-migration" command: Unable to generate an explicit migration because the following explicit migrations are pending: [201607141552034_Add_storeId_firstname_to_customer]. Apply the pending explicit migrations before attempting to generate a new explicit migration. However, if I try to run "update-database -Verbose -ConnectionStringName "ZzaDbConnectionString", I get an very confusing/conflict error: No pending explicit migrations. I tried to delete the migration file then use add-migration to create it again. It only work once. The next time (for example, if I want to add a column to my table), I got the same error. Any suggestion why the problem? Thanks.
EDIT: add code and configuration.
This is Entity class.
namespace Zza.Entities
{
public class Customer
{
public Guid Id { get; set; }
[MaxLength(50)]
public string FullName { get; set; }
}
}
This is Context class:
namespace Zza.Data
{
public class ZzaDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
}
This is console class:
namespace TestEFMigration
{
public class Program
{
static void Main(string[] args)
{
CreateDataBase();
}
private static void CreateDataBase()
{
var context = new ZzaDbContext();
context.Database.Initialize(false);
}
}
}
context class's app.config
<add name="ZzaDbConnectionString"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite‌​;MultiSubnetFailover=False"
providerName="System.Data.SqlClient" />
Console's app.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="ZzaDbConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
iceheart

The type was not mapped

Im trying to run a simple program according to all tutorial I could find.
This is my test code:
Program.cs:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF5WithMySQLCodeFirst
{
class Program
{
static void Main(string[] args)
{
using(var context = new DatabaseContext())
{
var defaultForum = new Forum { ForumId = 1, Name = "Default", Description="Default forum to test insertion." };
context.Forums.Add(defaultForum);
context.SaveChanges();
}
Console.ReadKey();
}
public class Forum
{
public int ForumId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class DatabaseContext : DbContext
{
public DbSet<Forum> Forums { get; set; }
}
}
}
This is the web.config:
<?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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
When I execute the code, in using(var context = new DatabaseContext()) line, I get the following error:
The type 'EF5WithMySQLCodeFirst.Program+Forum' was not mapped. Check
that the type has not been explicitly excluded by using the Ignore
method or NotMappedAttribute data annotation. Verify that the type was
defined as a class, is not primitive, nested or generic, and does not
inherit from EntityObject.
Please ignore the name MySQL since I am not trying yet to connect it to MySQL but for it
to work with localdb. I searched around and can't get the solution for problem yet.
I think it's failing because your Forum class is nested inside your Program class. Like the error message says, entity types can't be nested. Try moving it outside so that it's a top-level class within the namespace.