Checking CustomErrors turned on in Code - c#

Is it possible to check weather custom errors is turned on or off in the code on web application runtime.

I've figured out how to do it it's in...
HttpContext.Current.IsCustomErrorEnabled

You can use WebConfigurationManager.OpenWebConfiguration to obtain the configuration for the website, then use that to get the custom errors block:
Configuration configuration =
WebConfigurationManager.OpenWebConfiguration(null);
CustomErrorsSection customErrorsSection =
configuration.GetSection("system.web/customErrors") as CustomErrorsSection;
Response.Write(customErrorsSection.Mode.ToString());

OpenWebConfiguration(null) or HttpContext.Current.IsCustomErrorEnabled(true) gave me false information, this however worked great
Copy paste:
public static CustomErrorsMode GetRedirectMode()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
return ((CustomErrorsSection)config.GetSection("system.web/customErrors")).Mode;
}

Related

Unable to dynamically send the Active Directory group name on authorize attribute

I want to assign Active Directory group name dynamically as an attribute to authorize filter.
Currently we have 2 Active Directory groups, one is for DEV and other is for Prod. However if I have access to dev while debugging in local, I need to have access to the action method. If the AD group is prod, I should not have have access to the action method.
I tried using constants in static class classA
public const string DevActiveDirectoryName = "DevdirectoryName";
public const string ProdActiveDirectoryName = "ProddirectoryName";
My action method is like this:
[Authorize(Roles = ClassA.DevActiveDirectoryName)]
public async task<Iactionresult>GetMemberID()
{
}
The only problem with above solution is if I want to deploy to prod, I need to change code and deploy it. Instead if I can pass value dynamically to attribute that would solve my problem. I have tried many ways. Please suggest the best solution for this case. Is there any workaround for this kind of problem? I appreciate your help.
In order to be able to change the group name for different environments, you need to use configuration settings instead of constants. There are many options on how to provide configuration settings to an ASP.NET Core application. This link gives an overview.
If your application uses the default host builder, it will read configuration settings from a variety of sources, e.g. appsettings.json. You can add a setting to this file (if it does not exist yet, add it to the project), e.g.:
{
"ADGroupName": "ProddirectoryName"
}
For your dev-environment there is a dedicated file appsettings.dev.json that you can use to hold your dev settings:
{
"ADGroupName": "DevdirectoryName"
}
When protecting the controller with an Authorize attribute, you need to provide a constant value to the constructor. As the configuration setting can be changed later, it is (obviously) not constant.
Therefore, you have to set up a policy with a constant name in the ConfigureServices method in Startup.cs:
var adGroupName = Configuration.GetValue<string>("ADGroupName");
services.AddAuthorization(options =>
{
options.AddPolicy("ADGroupPolicy", policy =>
{
// This requirement checks for the group
policy.RequireRole(adGroupName);
});
});
For the controller, you need to add the policy name to the Authorize attribute:
[Authorize("ADGroupPolicy")]
public async task<Iactionresult>GetMemberID()
{
}
You can add an entry in your <appSettings> of your web.Config file and use ConfigurationManager to look up the value that should be assigned to a variable ActiveDirectoryName.
<appSettings>
<add key="ActiveDirectoryName" value="DevdirectoryName" />
... // other keys
</appSettings>
and in your code, you could look up what you have in your web.Config file (Dev for development and Prod for production servers (you dont need to deploy new web.config when deploying new code unless you make changes to it.
public const string ActiveDirectoryName = ConfigurationManager.AppSettings["ActiveDirectoryName"];
If you are using Visual Studio, web.config have two different configs (web.debug.config / web.release.config). You can use debug for development and Release that works on production.
This will stay constant and only your config files are changed,
[Authorize(Roles = ClassA.ActiveDirectoryName)]
public async task<Iactionresult>GetMemberID()
{
}

Modify Custom Section in App.config

I have the following custom section in my config file:
<TestSettings>
<EmailAddress></EmailAddress>
</TestSettings>
I tried to modify this section on runtime with the following method:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var testSettings = ConfigurationManager.GetSection("TestSettings") as NameValueCollection;
if (testSettings != null)
{
testSettings["EmailAddress"] = emailAddress;
config.Save();
ConfigurationManager.RefreshSection("TestSettings");
}
But the GetSection method returns null.
What is the simplest way to solve this?
Thank you.
So you running this from a test assembly. Re-read the method name:
ConfigurationManager.OpenExeConfiguration
Do you see it?
ConfigurationManager.OpenExeConfiguration
For a solution have a look at this answer.

Getting error while changing Appsettings value in Web config from code behind

I used the below code to change the appsetting key value in the web configuration of the application.
private void ChanngeDefaultPassword(string password)
{
try
{
var objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
objConfig.AppSettings.Settings["DEFAULT_PASSWORD"].Value = password;
objConfig.Save();
}
catch (Exception ex)
{
}
}
I am getting error stating
Attempted to perform an unauthorized operation.
This error is thrown in the step to save the configuration changes.
I think you might also need to set AllowLocation in file machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "AllowLocation" is false, it cannot be configured in individual elements.
Changing the web.config file generally causes an application restart.
If you really need your application to edit its own settings, then you should consider a different approach such as databasing the settings or creating an XML file with the editable settings.
For details, see Stack Overflow question How do you modify the web.config appSettings at runtime?.
This article on MSDN may have the answer you're looking for: UnauthorizedAccessException when saving AppSettings data to a Local Intranet file share.
I think here you don't need to write AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
You can save settings directly using objConfig.
Try this code:
private void ChanngeDefaultPassword(string password)
{
try
{
System.Configuration.Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
objConfig.AppSettings.Settings["DEFAULT_PASSWORD"].Value = password;
objConfig.Save();
}
catch (Exception ex)
{
}
}

get reference to the ASP.NET web.config customErrors section

I'm trying to obtain a reference to the web.config customErrors section. When I use the following code I always get a null. I don't have this problem when I get a reference to a custom section that I've created so I'm a bit dumbfounded why this won't work.
CustomErrorsSection customErrorSection =
ConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
I've also tried this:
CustomErrorsSection customErrorSection =
WebConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
I've also tried this:
CustomErrorsSection customErrorSection =
WebConfigurationManager.GetWebApplicationSection("customErrors") as CustomErrorSection;
EDIT:
ARGH! Such is the case with most things I figured out the answer right after asking the question.
This works for me:
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/");
CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
Or more simply like this:
CustomErrorsSection customErrors = (CustomErrorsSection) WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");
This also works:
CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
So I guess I understand now why I had the problem in the first place. I had incorrectly thought that I could get a reference to the customErrors section by trying to GetSection("customErrors") but I had failed to tell it what root section it lived in and I was basing my attempts on the fact that I knew how to get a custom section when I failed to realize that my custom section was the root of the section so I did not have to prepend something like system.Web/ in front of it when I called GetSection().
Try this:
var configuration = WebConfigurationManager.OpenWebConfiguration("~/Web.config");
// Get the section.
CustomErrorsSection customErrors =
(CustomErrorsSection)configuration.GetSection("system.web/customErrors");
More on the subject here: CustomError Class

PhluffyFotos does not work on Azure SDK 1.3

I have tried PhluffyFotos example on Azure SDK 1.2 and it works perfect. Today I have installed on another (clen) computer Azure SDK 1.3 and I have also want to try PhluffyFotos on it but it does not work. I have problem with this part:
if (!Roles.GetAllRoles().Contains("Administrator"))
{
Roles.CreateRole("Administrator");
}
It seems it somehow does not load the custom RoleProvider (TableStorageRoleProvider). Do you have any idea what it could be?
I get the following error: "The Role Manager feature has not been enabled.", because of the following exception "'System.Web.Security.Roles.ApplicationName' threw an exception of type 'System.Configuration.Provider.ProviderException'".
Can someone test this example and see what is the problem? http://phluffyfotos.codeplex.com/
Firsty I have the "SetConfigurationSettingPublisher" problem with this example, but I have successfully resole it.
EDIT:
I have look deeper into it and I am sure there are a problem with Role provider. Somehow the Roles class do not read config file. Have anyone any idea why?
I have the exact same problem with my own project. I verified with Fusion logs that the assembly which contains the custom providers dont even load. so it seems the problem is somehow related to the web.config settings being ignored.
To run PhluffyFotos example on Azure SKD 1.3 you have to the following:
Change reference Microsoft.WindowsAzure.StorageClient from 1.0 to 1.1
Move "GetConfigurationSettingValue" to the Global.asax "Application_Start" event.
Move Role related initialization to the Global.asax "Application_BeginRequest" event, but you have to ensure that it executes only once. Example:
private static object gate = new object();
private static bool initialized = false;
protected void Application_BeginRequest()
{
if (initialized)
{
return;
}
lock (gate)
{
if (!initialized)
{
// We need to check if this is the first launch of the app and pre-create
// the admin role and the first user to be admin (still needs to register).
if (!Roles.GetAllRoles().Contains("Administrator"))
{
Roles.CreateRole("Administrator");
}
if (!Roles.GetUsersInRole("Administrator").Any())
{
Roles.AddUserToRole(RoleEnvironment.GetConfigurationSettingValue("DefaultAdminRoleUser"), "Administrator");
}
initialized = true;
}
}
}
I posted a version of the code with the fixes suggested by Peter to rapidshare here:
http://rapidshare.com/files/434649379/PhluffyFotos.zip
For those who don't want to fuss around fixing the dependencies etc.
Cheers,
Daniel

Categories