ASP.NET Core MVC : ModelState error message - localization not working - asp.net-core-mvc

en-US:
zh-CN:
Why are [Display(Name = "LoginUserName")] and other data annotations not working?
This is my localization config
What could be the fix for me?

You can try the following two ways:
1. Use the old way of localizing data annotations:
[Display(Name = nameof(MyResources.LoginUserName),
ResourceType = typeof(MyResources))]
2. DataAnnotation localization can be configured in the startup file(Put in Program.cs in .NET 6):
services.AddMvc()
.AddViewLocalization(o=>o.ResourcesPath = "Resources")
.AddDataAnnotationsLocalization(o=> {
var type = typeof(ViewResource);
var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
var factory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
var localizer = factory.Create("ViewResource", assemblyName.Name);
o.DataAnnotationLocalizerProvider = (t, f) => localizer;
});
Here is a work demo, you can refer to it.
Hope this can help you.

Related

Exception : An existing connection was forcibly closed by the remote host

i'm working on a project that is based on web scraping with .NET Framework and Html-Agility-Pack tool.
At first, i made a method that parse the Category list from https://www.gearbest.com and it's totally working fine.
But now i need to parse the products from each category list item.
For example there is appliances category https://www.gearbest.com/appliances-c_12245/, but when i run the method it returns an error :
'The underlying connection was closed: An unexpected error occurred on a receive'
Here is my code :
public void Get_All_Categories()
{
var html = #"https://www.gearbest.com/";
HtmlWeb web = new HtmlWeb();
var htmlDoc = web.Load(html);
var nodes = htmlDoc.DocumentNode.SelectNodes("/html/body/div[1]/div/ul[2]/li[1]/ul/li//a/span/../#href");
foreach (HtmlNode n in nodes)
{
Category c = new Category();
c.Name = n.InnerText;
c.CategoryLink = n.GetAttributeValue("href", string.Empty);
categories.Add(c);
}
}
This is working pretty much fine.
public void Get_Product()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var html = #"https://www.gearbest.com/appliances-c_12245/";
HtmlWeb web = new HtmlWeb();
var htmlDoc = web.Load(html);
var x = htmlDoc.DocumentNode.SelectSingleNode("//*[#id=\"siteWrap\"]/div[1]/div[1]/div/div[3]/ul/li[1]/div/p[1]/a");
Console.WriteLine(x.InnerText);
Console.WriteLine("done");
}
But this method doesn't work and it returns that error.
How can i fix this please ?
P.S : I already saw some solutions about HTTPS handling but it didn't work for me, maybe because i don't understand it.
I would appreciate any help, thank you in advance.

DeleteDatabase is not supported by the provider, Oracle with Entity Framework

I'm using Model-First approach and Oracle database.
Update2: Fixed Now
On including seed data, I'm getting this error "DeleteDatabase is not supported by the provider"
UPDATE1 If I change seed data type from
public class MySeedData : DropCreateDatabaseAlways<ToolContext> to
public class MySeedData : DropCreateDatabaseIfModelChanges<ToolContext>
this error is replaced by another error:
Exception Model compatibility cannot be checked because the DbContext instance was not created using Code First patterns. DbContext instances created from an ObjectContext or using an EDMX file cannot be checked for compatibility
Seed Data
public class MySeedData : DropCreateDatabaseAlways<ToolContext>
{
protected override void Seed(ToolContext context)
{
base.Seed(context);
var category = new List<CategoryValue>
{
new CategoryValue{Id=1, Name = "Associate"},
new CategoryValue{Id =2, Name = "Professional"},
new CategoryValue{Id=3, Name = "Master"},
new CategoryValue{Id = 4, Name = "Product"},
new CategoryValue{Id = 5, Name = "Portfolio"}
};
category.ForEach(cert => context.CategoryValues.Add(cert));
context.SaveChanges();
}
}
Web.Config
<connectionStrings>
<add name="LMSPriorToolContext"
connectionString="metadata=res://*/Models.LMSPriorToolModel.csdl|res://*/Models.LMSPriorToolModel.ssdl|res://*/Models.LMSPriorToolModel.msl;
provider=Oracle.DataAccess.Client;
provider connection string="DATA SOURCE=DEV;PASSWORD=1234;PERSIST SECURITY INFO=True;USER ID=abc""
providerName="System.Data.EntityClient" />
</connectionStrings>
Application_Start()
Database.SetInitializer<ToolContext>(new SeedData());
Main.cs: EXCEPTION RAISED IN THIS FILE I know when you first try to access database, seed data method or scripts are executed.
using (var dbContext = new ToolContext())
{
var items = dbContext.CategoryValues;
foreach(CategoryValue category in **items**) // **Getting error here**
{
Console.WriteLine(category.Name);
}
}
REFERENCES Seems like I'm missing something here as there is nothing related to Oracle or ODAC
Stack Trace
at System.Data.Common.DbProviderServices.DbDeleteDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
at System.Data.Objects.ObjectContext.DeleteDatabase()
at System.Data.Entity.Internal.DatabaseOperations.DeleteIfExists(ObjectContext objectContext)
at System.Data.Entity.Database.Delete()
at System.Data.Entity.DropCreateDatabaseAlways`1.InitializeDatabase(TContext context)
at System.Data.Entity.Database.<>c__DisplayClass2`1.<SetInitializerInternal>b__0(DbContext c)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass8.<PerformDatabaseInitialization>b__6()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
Please suggest what I'm missing here.
Way of seeding data using DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges is not supported in Model-First approach.
Change seed data class to:
public class ToolSeedData : IDatabaseInitializer<ToolContext>
{
public void InitializeDatabase(ToolContext context)
{
var category = new List<CategoryValue>
{
new CategoryValue{Id=1, Name = "Associate"},
new CategoryValue{Id =2, Name = "Professional"},
new CategoryValue{Id=3, Name = "Master"},
new CategoryValue{Id = 4, Name = "Product"},
new CategoryValue{Id = 5, Name = "Portfolio"}
};
category.ForEach(cert => context.CategoryValues.Add(cert));
context.SaveChanges();
}
Possible error if you don't use it:
DeleteDatabase is not supported by the provider
Exception Model compatibility cannot be checked because the DbContext instance was not created using Code First patterns.
DbContext instances created from an ObjectContext or using an EDMX
file cannot be checked for compatibility
Microsoft link Seeding database does not work
Hope this helps someone else.

Using the Netflix Odata service with WP71

I'm trying to use the Netflix Odata service with WP71 but it aint working. What's wrong with this code?
private const string NETFLIX_CATALOG_URI = "http://odata.netflix.com/v2/Catalog/";
public ObservableCollection<Title> SearchByTitle(string searchKey)
{
NetflixCatalog catalog = new NetflixCatalog(new Uri(NETFLIX_CATALOG_URI));
var query = catalog.Titles.Where(t => t.Name.Contains(searchKey));
DataServiceCollection<Title> titles = new DataServiceCollection<Title>(catalog);
titles.LoadAsync(query);
return titles;
}
If you look at the HTTP request generated from your Linq, you will notice that the format is not supported by Netflix. It will work if you change it to:
var query = catalog.Titles.Where(t => t.Name.StartsWith(searchKey));
But, of course, it is not exactly the search you want... and I am looking for the answer on that too.

How can I test custom ValidationAttribute classes in MVC 3

I have a custom validator attribute which I am trying to unit test. In my unit test I am doing the following.
var testModel = new TestModel();
var testContext = new ValidationContext(testModel, null, null);
var attribute = new MyCustomAttribute();
attribute.Validate(testModel, testContext);
When calling attribute.Validate it correctly calls my IsValid method but attribute.Validate is void so obviously doesn't return anything. Any ideas on how I can get a hook into the ValidationResult would be greatly appreciated.
After doing some reading on the ValidationAttribute.Validate Method it looks like if it fails validation it will throw a ValidationException, so this kind of answers my question.
You can invoke the validation the same way MVC does using the ModelValidator. Something like this (your mileage here may vary, can't remember all the calls off the top of my head, will try to replace with working code later):
var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
var validator = ModelValidator.GetModelValidator(modelMetadata, base.ControllerContext);
var result = validator.Validate(instance)

How to set the System.Web.WebPages.WebPage.Model property

I am planning on creating a custom route using ASP.NET Web Pages by dynamically creating WebPage instances as follows:
IHttpHandler handler = System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath("~/Default.cshtml");
How can I supply an object to the underlying WebPage object so that it can become the web pages's "Model"? In other words I want to be able to write #Model.Firstname in the file Default.cshtml.
Any help will be greatly appreciated.
UPDATE
By modifying the answer by #Pranav, I was able to retrieve the underlying WebPage object using reflection:
public void ProcessRequest(HttpContext context)
{
//var page = (WebPage) System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath(this.virtualPath);
var handler = System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath(this.virtualPath);
var field = handler.GetType().GetField("_webPage", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var page = field.GetValue(handler) as System.Web.WebPages.WebPage;
var contextWrapper = new HttpContextWrapper(context);
var pageContext = new WebPageContext(contextWrapper, page, context.Items[CURRENT_NODE]);
page.ExecutePageHierarchy(pageContext, contextWrapper.Response.Output);
}
Unfortunately this is not reliable as it does not work in Medium Trust (BindingFlags.NonPublic is ignored if application is not running in full trust). So while we have made significant progress, the solution is not yet complete.
Any suggestions will be greatly appreciated.
The Model property of a WebPage comes from the WebPageContext. To set a Model, you could create a WebPageContext with the right parameters:-
var page = (WebPage)WebPageHttpHandler.CreateFromVirtualPath("~/Default.cshtml");
var httpContext = new HttpContextWrapper(HttContext.Current);
var model = new { FirstName = "Foo", LastName = "Bar" };
var pageContext = new WebPageContext(httpContext, page, model);
page.ExecutePageHierarchy(pageContext, httpContext.Response.Output);
The model instance should now be available as a dynamic type to you in your page.

Resources