Open RESX and change Access Modifier to Public.
Make sure that project builds without error. You can be misled that RESX cant be built while you have compile error.
Jun 7, 2018
May 27, 2018
RePost: ASP.NET Core debugging in production environment Windows Server
When you test on staging server errors are suppressed.
On you dev machine you can see error through Visual Studio.
Bottom line use DOTNET.EXE web.dll from command prompt as explained here to see errors.
Quite frustrating after you've spent decade seeing this very same error in your browser in custom errors mode.
https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/troubleshoot?view=aspnetcore-2.0
You should also consider understanding new environment modes in ASP.NET Core.
Again bottom line should be (not been able to make it work :( ) to add good old system environment variable:
ASPNETCORE_ENVIRONMENT
as explained here:
https://andrewlock.net/how-to-set-the-hosting-environment-in-asp-net-core/
Note!
If you require two environment modes to work on same server you'll have to use web.config and defined it inside for each web app separately.
On you dev machine you can see error through Visual Studio.
Bottom line use DOTNET.EXE web.dll from command prompt as explained here to see errors.
Quite frustrating after you've spent decade seeing this very same error in your browser in custom errors mode.
https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/troubleshoot?view=aspnetcore-2.0
You should also consider understanding new environment modes in ASP.NET Core.
Again bottom line should be (not been able to make it work :( ) to add good old system environment variable:
ASPNETCORE_ENVIRONMENT
as explained here:
https://andrewlock.net/how-to-set-the-hosting-environment-in-asp-net-core/
Note!
If you require two environment modes to work on same server you'll have to use web.config and defined it inside for each web app separately.
May 25, 2018
Razor tips & tricks (ASP.NET Core 2.0)
Some quick tips besides what you can quickly find on net...
@(xxxxxxxxxxx)
Anything you place in brackets will be printed:
So:
@(ViewBag.IsActive = true)
; will print True and assign value:
This saved my day many time:
@{Html.PartailView("xxxxxx");}
For some reason when mixing html and Razor PartialView method is not recognized so this solves problem.
For JS use :
<text>
$(document).ready();
</text>
Don't forget also:
@Html.Raw("class='mycssclass'")
And semicolon:
@:
@(xxxxxxxxxxx)
Anything you place in brackets will be printed:
So:
@(ViewBag.IsActive = true)
; will print True and assign value:
This saved my day many time:
@{Html.PartailView("xxxxxx");}
For some reason when mixing html and Razor PartialView method is not recognized so this solves problem.
For JS use :
<text>
$(document).ready();
</text>
Don't forget also:
@Html.Raw("class='mycssclass'")
And semicolon:
@:
May 8, 2018
JQuery how to prevent event handling (clicking etc.) more than once
You created some delegated event handler for DOM event:
$( "#dataTable tbody tr" ).on( "click", function() {
Problem is that when you click on control Click event occurs more than once.
Check your code. Probably inside page life on client side you perform above event click registration multiple times. Thus every click triggers Click events based on how much registrations has happened.
To avoid this use Off method.
Place it right before On tho cleary any previous event registration on SAME function like this:
$( "body" )
.off( "click", "#theone", flash )
$( "body" )
.on( "click", "#theone", flash )
http://api.jquery.com/off/
$( "#dataTable tbody tr" ).on( "click", function() {
Problem is that when you click on control Click event occurs more than once.
Check your code. Probably inside page life on client side you perform above event click registration multiple times. Thus every click triggers Click events based on how much registrations has happened.
To avoid this use Off method.
Place it right before On tho cleary any previous event registration on SAME function like this:
$( "body" )
.off( "click", "#theone", flash )
$( "body" )
.on( "click", "#theone", flash )
http://api.jquery.com/off/
May 7, 2018
RePost: Asp.Net Core 2.0 how to localize generic validation attribute messages
I want to localize client side validation messages that show as part of data annotations applied to model (Required, Compare etc) They are injected by MVC to JQuery validation engine.
Watch for this. Inspect DOM for your input control:
Bellow example works. Look for CustomValidationMetadataProvider.
What was frustrating is to distinct between:
- Validation Attribute Error Messages Localization
-Model Binding Error Messages Localization.
In example Model binding error messages are server side validation messages you'll get if you disable client side validation.
There is one more scenario to consider in this example. When you create data annotation without explicit error message like this:
[Required]
public string Name
I didn't care about that scenario.
https://blogs.msdn.microsoft.com/mvpawardprogram/2017/05/09/aspnetcore-mvc-error-message/
Watch for this !
Remove AddDataAnnotationsLocalization from ConfigureService. This will silently override your CustomValidationMetadataProvider and try to obtain localization from Shared folder.
Here is modification from above link of metaprovider for few standard Data annotations.
Here is quick snippet of standard referencing of JQuery Validation:
In View :
Watch for this. Inspect DOM for your input control:
If your data-val-required attr is empty like in above then your server side MVC validation messages configuration failed. It didn't provide any message. Hence JQuery validation will default to it's own hardcoded message "This field is required"
<input class="form-control input-validation-error" type="text" data-val="true" data-val-required id="Name" name="Name" value="" aria-required="true" aria-describedby="Name-error" aria-invalid="true">
Bellow example works. Look for CustomValidationMetadataProvider.
What was frustrating is to distinct between:
- Validation Attribute Error Messages Localization
-
In example Model binding error messages are server side validation messages you'll get if you disable client side validation.
There is one more scenario to consider in this example. When you create data annotation without explicit error message like this:
[Required]
public string Name
I didn't care about that scenario.
https://blogs.msdn.microsoft.com/mvpawardprogram/2017/05/09/aspnetcore-mvc-error-message/
Watch for this !
Remove AddDataAnnotationsLocalization from ConfigureService. This will silently override your CustomValidationMetadataProvider and try to obtain localization from Shared folder.
Here is modification from above link of metaprovider for few standard Data annotations.
public class CustomValidationMetadataProvider : IValidationMetadataProvider
{
private ResourceManager resourceManager; private Type resourceType;
public CustomValidationMetadataProvider(string baseName, Type type)
{
resourceType = type;
resourceManager = new ResourceManager(typeof(SiteResources));
}
public void CreateValidationMetadata(
ValidationMetadataProviderContext context)
{
AddRequiredForValueTypeIfMissing(context);
foreach (var attribute in context.ValidationMetadata.ValidatorMetadata)
{
ValidationAttribute tAttr = attribute as ValidationAttribute;
if (tAttr != null)
{
if (tAttr is RequiredAttribute ||
tAttr is EmailAddressAttribute ||
tAttr is StringLengthAttribute)
{
var name = tAttr.GetType().Name;
if (resourceManager.GetString(name) != null)
{
tAttr.ErrorMessageResourceType = resourceType;
tAttr.ErrorMessageResourceName = name;
tAttr.ErrorMessage = null;
}
}
}
}
}
private void AddRequiredForValueTypeIfMissing(ValidationMetadataProviderContext context)
{
if (context.Key.ModelType.GetTypeInfo().IsValueType &&
context.ValidationMetadata.ValidatorMetadata
.Where(m => m.GetType() == typeof(RequiredAttribute)).Count() == 0)
context.ValidationMetadata.ValidatorMetadata.
Add(new RequiredAttribute());
}
}
Here is quick snippet of standard referencing of JQuery Validation:
<environment include="Development">
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"
asp-fallback-src="~/lib/jquery-validation/dist/jquery.validate.min.js"
asp-fallback-test="window.jQuery && window.jQuery.validator"
crossorigin="anonymous"
integrity="sha384-Fnqn3nxp3506LP/7Y3j/25BlWeA3PXTyT1l78LjECcPaKCV12TsZP7yyMxOe/G/k">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"
asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive"
crossorigin="anonymous"
integrity="sha384-JrXK+k53HACyavUKOsL+NkmSesD2P+73eDMrbTtTk0h4RmOF8hF8apPlkp26JlyH">
</script>
</environment>
In View :
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Apr 20, 2018
Javascript / Jquery working with arrays
When accessing jquery selector that returns list of elements you can't access elements using standard array methods:
- find- map
- filter
Use only JQuery each.
var getCheckedInputIdList = function () {
var checked = $('#map input.mapFilterControl[type="checkbox"]:checked');
var checkedIdList = [];
checked.each(function () {
var filterItemValue = $(this)[0].id;
checkedIdList.push(filterItemValue);
});
return checkedIdList;
}
var doesExistForId = function (arr, findThis) {
return arr.find(function (element) {
return element && element.Id === findThis.Id;
})
}
Short-hand or Arrow functions ( C# lambda like)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Warning! Arrow functions don't support "this" or constructors ?
Reduce, Slice & Join in Action
"You are given an array strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.
#Example: longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"
n being the length of the string array, if n = 0 or k > n or k <= 0 return ""."
function longestConsec(strarr, k) {
return strarr.length > 0 && strarr.length >= k && k > 0
? strarr.reduce((longest, item, i) => {
var curr = strarr.slice(i, i + k).join('');
return curr.length > longest.length ? curr : longest;
}, strarr.slice(0,k).join(''))
: "";
}
console.log( longestConsec(["wlwsasphmxx","owiaxujylentrklctozmymu","wpgozvxxiu"], 2) );
Reduce must produce single result. Watch for initial value for acumulator! In above sample we had to explicitly calculate it by joining k elements. By default it will take myArray[0] for acumulator value.
Use it to iterate and calculate single result. Note how you don't have to care for "index out of range". Example shows how you iterate using reduce and again using slice inside on same array.
Slice DOESN'T take second index so for ...slice(0,1) you'll get only element[0] !
Join without params like this Join() will use ',' as delimiter. Use explicit Join('') for empty delimiter.
Mar 27, 2018
ASP.NET Entity Framework 6 Code First Migrations - basics (.NET 4.6.2 standard)
Create empty Web application with MVC (.NET 4.6.2)
Add Entity Framework as NuGet package.Create first model:
public class PersonRun in Package Manager Console:
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(24)]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
PM> enable-migrationsThis will create Migrations folder with Configuration class. Enable auto migrations by changing this:
AutomaticMigrationsEnabled = true;
Create Context class. Here you must register all your models for database:
public class AdresarContext : DbContextRun in PM console:
{
public AdresarContext() : base("Adresar")
{
}
public DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
}
PM> update-database -verboseThis should generate Database with table(s).
Let's add extra table with master detail relationship.
New class:
public class CityReference it in Person:
{
[Key]
public int Id { get; set; }
[StringLength(25)]
public string Name { get; set; }
public ICollection<Person> Persons { get; set; }
}
[Required]
public City City { get; set; }
Register it in Context:
public DbSet<City> Cities { get; set; }
Run update again:
PM> update-database -verbose
Subscribe to:
Posts (Atom)