In ASP.NET Boilerplate I am changing language like
English
It works properly on my local machine, but not on test server.
Also when I'm clicking it locally, sometimes there is abp.message.error with null content.
I have a few questions about that:
1) What is this URL (/AbpLocalization...), looks lika a controller, but there is no such thing in my code?
2) How can I find and debug it?
3) What may happen on another server that crashes it (on test server clicking button reloads state, but does not change language)
Solved!
What caused the problem was the fact, that the database on test server did not have one table that was in local database, and what's more important: this table was included in model transferred through Entity Framework to database. After adding table to test server everything works fine.
ASP.NET Boilerplate is an application framework built from modules, one of them being Localization module. Since it's open source you can change default behaviors, although I should not recommend doing it without really good reason.
Localization is part of the core package and it's located here: GitHub
I recommend you to use documentation and configure it to your needs. You can find localization documentation here: documentation.
And lastly, you should check your running configuration in the test environment, which is possibly faulted in some way. Another reason for error may be an issue with your ABP version.
AbpLocalizationController is located here in source code
src/Abp.AspNetCore/AspNetCore/Mvc/Controllers/AbpLocalizationController.cs
And this is change culture code:
public virtual ActionResult ChangeCulture(string cultureName, string returnUrl = "")
{
if (!GlobalizationHelper.IsValidCultureCode(cultureName))
{
throw new AbpException("Unknown language: " + cultureName + ". It must be a valid culture!");
}
var cookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cultureName, cultureName));
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
cookieValue,
new CookieOptions {Expires = Clock.Now.AddYears(2)}
);
if (AbpSession.UserId.HasValue)
{
SettingManager.ChangeSettingForUser(
AbpSession.ToUserIdentifier(),
LocalizationSettingNames.DefaultLanguage,
cultureName
);
}
if (Request.IsAjaxRequest())
{
return Json(new AjaxResponse());
}
if (!string.IsNullOrWhiteSpace(returnUrl) && AbpUrlHelper.IsLocalUrl(Request, returnUrl))
{
return Redirect(returnUrl);
}
return Redirect("/"); //TODO: Go to app root
}
https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/src/Abp.AspNetCore/AspNetCore/Mvc/Controllers/AbpLocalizationController.cs
If you want to debug this code, fork the project from github repo and add it to your solution. Replace your abp dll references with this local project references.
Meanwhile you didn't mention what the error say. To learn it check out website logs.
Related
I am still rather inexperienced to Microsoft Azure iotedge (and stackoverflow - this being my first post) and how module twins work and have an issue regarding the deletion of obsolete properties from the reported part of my module twin.
I have migrated a couple of properties from one device to another within the module twin, however have not been able te remove the properties from the reported and I understand that setting them to null should do the trick (setting them to null and updating them in desired removes them only from the desired part of the twin). The obsolete properties are also not present in the module twin locally on the device
I have tried updating the reported - with a C# console app using the Microsoft.Azure package setting the obsolete properties to null - but this doesnt seem to work either.
await registryManager.UpdateTwinAsync(deviceId, moduleId, removeProperties, eTag);
with my string removeProperties being something like the following (updating desired using this route works like a charm)
{
{
"properties": {
"reported": {
"foo": {
"bar": null
}
}
}
}
Can Anybody suggest on a way to remove these properties?
You can't update the reported properties through the registry manager. However, it can be done using the device's identity. In the same way you wrote a console program to update the twin with the service SDK, you could do it with the device SDK (granted that the device is offline).
For instance if you have a file called twin.json:
{
"foo": {
"bar": null
}
}
You can update the reported properties like this:
var text = await File.ReadAllTextAsync("./twin.json");
var deviceClient = DeviceClient.CreateFromConnectionString("very-secret-connection-string");
var twinCollection = new TwinCollection(text);
await deviceClient.UpdateReportedPropertiesAsync(twinCollection);
I am using ASP.NET Core 2.1.519 and its Identity UI as a library.
The default behaviour of this library is to auto login a user after registration. I want to remove this behaviour because I don't want to allow logins until email confirmations.
So far, I was able to force email confirmation before allowing "manual" logins using a service configuration:
services.AddDefaultIdentity<IdentityUser>(opt =>
{
opt.Password.RequiredLength = 6;
opt.Password.RequireDigit = false;
opt.Password.RequireNonAlphanumeric = false;
opt.Password.RequireUppercase = false;
opt.Password.RequireLowercase = false;
opt.SignIn.RequireConfirmedEmail = true; //This did the trick
}).AddEntityFrameworkStores<ApplicationDbContext>();
But this rule seems to be bypassed by auto login triggered by the Registration functionality.
Whereas a possible way to fix this is to inherit and override Registration behaviour from this library, I was wondering if there was some built-in configuration (such as RequireConfirmedEmail showed above) to achieve this. So far, I have found nothing of the like...
Many thanks in advance for your time and help.
EDIT
As Tieson suggested in question comments, this behaviour seems to have been corrected on later .NET Core versions. As I said in my question, I was using version 2.1.519 while current stable one is 3.1.10 released on 2020-11-10. If you want to avoid all the code overhead that my original answer demanded, it would be wise to update your .NET Core version.
ORIGINAL ANSWER
Indeed it is possible to modify Identity Library's code by overriding it. How to do it is explained here.
Basically, you scaffold the library's code you want to override. Visual Studio provides a suitable way of doing this:
Right click your project -> Add -> New Scaffolded Item -> Identity
It also helps you select what functionalities you want to override:
In this case, Account/Register.
This generates all the necessary code for that functionality, inside your Areas folder. Then, all you have to do is go to Areas/Identity/Pages/Account/Register.cshtml.cs and modify OnPostAsync method, deleting the SignIn line after the email sending.
Voilá, mission completed. BUT, you got yourself a lot of files and code that you didn't want to, just to delete one single tiny little line...
I still would love to have a built in configuration for this.
I still would love to have a built in configuration for this.
If you compare it with built-in code of RegisterModel class in ASP.NET Core 3+, you would find it determine if auto login a user after registration based on configuration value of RequireConfirmedAccount option, like below.
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
You can achieve same in your ASP.NET Core 2.1 project by checking the configuration value of RequireConfirmedEmail option.
if (!_userManager.Options.SignIn.RequireConfirmedEmail)
{
await _signInManager.SignInAsync(user, isPersistent: false);
}
return LocalRedirect(returnUrl);
I still encounter this behaviour in .NET Core 5.0.8.
If you also set RequireConfirmedAccount to true, you get a "a confirmation email will be sent" message after registering, instead of just logging you in:
services.Configure<IdentityOptions>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.SignIn.RequireConfirmedEmail = true;
}
I've been trying to add an EventLog Provider for logging in my ASP.NET Application. I was able to add it to the 'Application' source, but there's a lot of information in that log and I'd like for it to be under it's own source. I've actually gotten 3 logs to be written to it's own source, but I have no idea how or why. This is what my code looks like right now:
CreateWebHostBuilder(args)
.ConfigureLogging( logging =>
{
logging.AddEventLog(
new Microsoft.Extensions.Logging.EventLog.EventLogSettings
{
SourceName = "MySweetApp",
MachineName = ".",
LogName = "MySweetApp",
Filter = (category, level) =>
{
if (category.EndsWith("Controller") || level >= LogLevel.Error)
{
return true;
}
return false;
},
});
})
.Build()
.Run();
I've already added a registry key there for this app (since the app doesn't have admin rights and can't add a source) along with the EventMessageFile of C:\Windows\Microsoft.NET\Framework64\v4.0.30319\EventLogMessages.dll. I've messed with different values of this including the non-64 framework folder and other v2 versions. There are no errors or warnings, and I can't find any logs that have anything related in them. I've also added a debug logger with .AddDebug() and it prints just fine the debug window.
I'm guessing it's something on the server side of things and not my code. Thanks in advance.
UPDATE: I can now re-create my app creating error logs in the eventlog. If I start my program by double-clicking the .exe, there is an authentication error that is thrown and gets sent to the log.
Found it. I still had a "Logging" section of my appsettings.json that was set default to warning. Deleted that section and everything started printing!
I have recorded a performance test using a perf/load test project in Visual Studio as per these instructions from Microsoft: https://msdn.microsoft.com/en-us/library/dn250793.aspx. I then turned it into a coded test by clicking "Generate Code".
Now I am trying to run the test, but it doesn't recognise some of the code it's written, like
request6Body.FormPostParameters.Add("AuthMethod", this.Context["$HIDDEN1.AuthMethod"].ToString());
(In this case it says there's no context parameter called "$HIDDEN1.AuthMethod").
I know that this is probably because the ADFS screen doesn't return the same headers etc. each time, but has anyone written code to get around this, and if so, how's it done?
Thanks!
For our tests, I developed a method which allows to use a simulated/fake login, which allows you to use the App without ADFS and without redirections. Of course, this should be disabled in production. Next time you record the test, you start straight away with the fake login.
We use ASP.NET MVC so I can only show you how that works in ASP.NET MVC.
Controller Action
[AllowAnonymous]
public ActionResult Impersonate([Bind(Prefix = "id")]string email)
{
Impersonalisator.ImpersonateByEMail(email, Request);
return RedirectToRoute("Default", new { action = string.Empty, controller = string.Empty });
}
(So you can execute: /Home/Impersonate/demouser#example.com
Impersonalisator.ImpersonateByEMail
public static void ImpersonateByEMail(string email, HttpRequestBase request)
{
// you don't need this if clause, or you introduce this appsetting in your web.config
if ("true" == ConfigurationManager.AppSettings["EnableImpersonate"])
{
var impersonatedIdentity = new ClaimsIdentity("ApplicationCookie");
impersonatedIdentity.AddClaim(new Claim(ClaimTypes.Email, email));
// Add other claims you might need
var owinContext = request.GetOwinContext();
owinContext.Authentication.SignOut("ApplicationCookie");
owinContext.Authentication.SignIn(impersonatedIdentity);
}
}
You can start logged in without going over ADFS, you don't want to have ADFS or other Authentication services in your tests anyway, e.g. in load tests you might "attack" those services and cause failures etc.
I've been trying to open a file in asp.net 5 and have not been having a lot of success.
In the past you used Server.MapPath or HostingEnvironment.ApplicationPhysicalPath. They are both gone in the OWIN based framework.
There is a HostingEnvironment class but it's in the System.Aspnet but it needs to be initialized by the hosting environment (it no longer has a static member for ApplicationPhysicalPath but I'm guessing the WebRoot member does that now. The problem is I can't find a reference to it anywhere.
I've also looked at Context.GetFeature<> but it doesn't seem to have any feature that would show the application path, just request and response related info. The code listing the features can be found here.
<snark>Is the ability to work with files a discontinued feature in ASP.NET?</snark>
There is also the possibility that I can't brain very well right now and missed something.
You can get it from the ApplicationBasePath property of Microsoft.Framework.Runtime.IApplicationEnvironment serivce.
Example: https://github.com/aspnet/Mvc/blob/9f1cb655f6bb1fa0ce1c1e3782c43a2d45ca4e37/test/WebSites/FilesWebSite/Controllers/DownloadFilesController.cs#L28
There are two approaches now:
using Microsoft.Extensions.PlatformAbstractions;
public Startup(IApplicationEnvironment appEnv)
{
// approach 1
var path01 = PlatformServices.Default.Application.ApplicationBasePath;
// approach 2
var path02 = appEnv.ApplicationBasePath;
}