<appSettings>
<!-- Settings file for website! -->
<add key="DefaultCookieExpiryMins" value="30" />
</appSettings>
Why do I have to set everything as a string? Why can't I have different datatypes in there like int to help me stop having to cast everything?
This is why I prefer custom configuration sections over just putting key/value pairs in appSettings. See this MSDN article for more information on how to make your own configuration section. Once you have your own configuration section class, you should be able to access your settings as any data type you'd like.
I just use generics for things like this.
public static T GetConfigurationValue<T>(string keyName)
{
if (System.Configuration.ConfigurationManager.AppSettings[keyName] != null)
{
T result;
try
{
result = (T)Convert.ChangeType(System.Configuration.ConfigurationManager.AppSettings[keyName], typeof(T));
}
catch
{
return default(T);
}
return result;
}
throw new ArgumentException("A key with the name " + keyName + " does not exist in the current configuration.", keyName);
}
Usage: GetConfigurationValue<int>("DefaultCookieExpiryMins");
Related
i cant connect to sql 2012 in asp.net , c#
file: defalut.aspx -> page_Load
List<ozhatdata.tbl_diller> diller_result;
using (var ctx = new ozhatdata.bagDataContext())
{
diller_result = ozhatdata.DilIslemleri.GetAllLanguages(ctx);
}
int cnt = diller_result.Count ; // diller_result is null error
when i go to definition (F12) of the bagDataContext()
file: bag.designer.cs
public bagDataContext() :
base(global::ozhatdata.Properties.Settings.Default.ozhatprojeConnectionString15, mappingSource)
{
OnCreated();
}
when i go to definition (F12) of ozhatprojeConnectionString15
file: settings.designer.cs
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute( "Data Source=.\\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;"+
"User ID=sa;Password=123; ")]
public string ozhatprojeConnectionString15 {
get {
return ((string)(this["ozhatprojeConnectionString15"]));
}
}
later i learned there is app.config file this line was present in app.config
<add name="Settings.ozhatprojeConnectionString15"
connectionString="Data Source=LIVE2RISE\SQLEXPRESS;Initial Catalog=ozhatproje;Persist Security Info=True;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
i can connect to "user:sa pass:123" on "ms sql management studio"
!!!!error!!!!!!
System.NullReferenceException: Object reference not set to an instance of an object.
diller_result.count // this diller_result is null in debugger
line 36: for (int i = 0; i < diller_result.Count; i++)
Kaynak Dosya: c:\inetpub\wwwroot\site\Default.aspx.cs line : 36
im trying to figure out since yesterday.
please help me, thnks.
edit: after responce i tracked adn put a breakpoint
public static List<tbl_diller> GetAllLanguages(bagDataContext ctx = null)
{
try
{
//some stuf was here i deleted
}
catch (Exception ex)
{
string ms = ex.Message; // !!breakpoint
// the exception= coundt find stored procedure "dbo.getalllangs"
return null;
}
}
thank you. the problem is solved. it was caused by an evil try-cath duo.
i'll be more cautious with these "try catchs" from now on.
2nd time and Solution: this time eventhough i edit app.config, program uses old ConString from settings.designer.cs(i tracked it while debugging).
the program uses connString from setting.designer.cs too. app.config is not used/looked up/referred when Debugging
so we have to navigate in the solution>properties>settings.designer.cs edit connectionStrings there too.
i hope this helps anyone in future.
you can read this too:
Force regeneration of Settings.settings file after change in app.config
It seems that it is the call to ozhatdata.DilIslemleri.GetAllLanguagesthat did return a null value for diller_result.
You might want to check in that method what is causing it to return null.
What i want to do is, i want to check the Size for a sub-folder inside a specific folder for a bucket in Amazon S3 bucket using vb.
Is that possible to do, if so any link and help will be appriciated.
A little late to the party, but this works like a charm:
AmazonS3 client = AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.USEast1);
ListObjectsRequest request = new ListObjectsRequest();
request.WithBucketName(bucketName);
request.WithPrefix(folderPath);
long total = 0;
do
{
ListObjectsResponse response = client.ListObjects(request);
if (response != null && response.S3Objects != null)
total += response.S3Objects.Sum(s => s.Size);
if (response.IsTruncated)
{
request.Marker = response.NextMarker;
}
else
{
request = null;
}
} while (request != null);
Your Access Key and Secret Access Key should by convention be saved to your application configuration:
<configuration>
<appSettings>
<add key="AWSAccessKey" value="XXXXXXXXXXXXXXX"/>
<add key="AWSSecretKey" value="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"/>
</appSettings>
</configuration>
Hope that helps.
The article Beginning with Amazon S3 is a good starting point for you. The code bits referencing the listObject method are doing 99% of what you want (getting all files with a particular prefix). You just need to add the bits to interrogate the file size of each and add them up.
If you're able to get the bucket, then you already have all the wire up you need for this snippet to work:
using (s3Client)
{
long totalFileSize = 0;
try
{
ListObjectsRequest Lor = new ListObjectsRequest()
{
BucketName = "<Your Bucket Name>",
Prefix = "<Your Folder Path>",
///assuming your delimiter is a /
Delimiter = "/"
};
ListObjectsResponse response1 = s3Client.ListObjects(Lor);
foreach (S3Object s3Object in response1.S3Objects)
{
totalFileSize += s3Object.Size();
}
}
catch (AmazonS3Exception ex)
{
///do some error handling....
}
}
The only way is to enumerate through all the files on S3 you are looking at (e.g. with prefix /some/folder/ ) and add up all the sizes that come back. S3 does not know this information.
In VB you must be using some API, when you ask S3 to list the contents of a bucket with a prefix, the results come back about 1000 at a time, with size information for each file. So to add up the GB used for 25,000 files should only require 25 or so calls.
Good Day,
I have two connection strings defined in my web.config file.
<connectionStrings>
<add name="AppDb" connectionString="CONNECTION-STRING1"/>
<add name="LaptopDb" connectionString="CONNECTION-STRING2" />
</connectionStrings>
When I am working on my desktop, I want to use the connection string "AppDb". When I am working on my laptop, I want to use the connection string "LaptopDb". I don't want to comment out the line on the connection string everytime I work on a different machine.
I know that I can programatically do this. I'm just trying to figure out the best way.
Something like:
if (machineName == desktop)
use AppDb
else
use LaptopDb
but I don't like this approach. Is there something else I can test on?
Here's another couple of approaches you could consider:
You can use the configSource attribute to read the configuration for that element from another file, the contents of which can be different on each machine:
http://weblogs.asp.net/fmarguerie/archive/2007/04/26/using-configsource-to-split-configuration-files.aspx
Or you can use different build configurations and use XDT to transform the web.config file.
Really not too hard to do -- the trick is to use the System.Environment.MachineName to drive which string to pick and to get your connection string from a static property:
public static string ConnectionStringName
{
get
{
var customConnection = ConfigurationManager.ConnectionStrings[Environment.MachineName] != null;
var connectionStringName = customConnection ? Environment.MachineName : "DefaultDb";
return connectionStringName;
}
}
i want to give the values of username,password and APIKey in web.config which are coming from database.means whatever the admin set username,password,APIkey that has to be set in web.config.
how can i change this.Any idea.
thank you.
private void UpdateConfig(string strKey, string strValue)
{
Configuration objConfig =
WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings =
(AppSettingsSection)objConfig.GetSection("appSettings");
if (objAppsettings != null)
{
objAppsettings.Settings[strKey].Value = strValue;
objConfig.Save();
}
}
But it will restart your application domain every time you update the web.config file, so, updating the web.config frequently is not advisable.
Pls refer : Editing Web.config programatically
Is there a way of listing which roles have access to a given page via code?
Example, I have a Testpage.aspx, and I wanted to list the roles allowed for this page when a user accesses the page. The URLAuthorizationManager must be able to find this out somehow, so there must be a way it knows what roles are configured in the webconfig for a page. or URL.
Here is the webconfig limiting the roles allowed to view this page.
<location path="Testpage.aspx">
<system.web>
<authorization>
<allow roles ="admin,sales" />
</authorization>
</system.web>
</location>
If I could find a solution, it would return "admin", "sales". Any one know how I can do this? Thanks
You can use the following code inside the page where you want to obtain the information.
var section = (AuthorizationSection)
WebConfigurationManager.GetSection("system.web/authorization");
var rules = section.Rules;
var allowedRoles = rules
.OfType<AuthorizationRule>()
.Where(r => r.Action == AuthorizationRuleAction.Allow)
.Select(r => r.Roles).First();
The reason for the call to First() is that .NET configuration is hierarchical. Suppose you have the following web site hierarchy and configuration:
/Default.aspx
/Web.config (<allow roles="admin,user" />)
/SubDir/
/Test.aspx
/Web.config (<allow roles="admin,other" />)
and you call the code above from Test.aspx.cs, then the property AuthorizationSection.Rules contains three items corresponding to respectively the configuration from /SubDir/Web.config, Web.config and machine.config. So the first element contains the roles admin and other.
My problem was very similar except I needed the ability to iterate through all of the
directories and related subdirectories and display allowed roles for each web page and folder directory. I was unable to use Ronald Wildenberg's solution because we're using .Net 2.0 so we don't have the Linq functionality.
His solution gave me the roadmap I needed. I also found help from from Microsoft's French IIS Support Team, Managing Forms Authentication Programmatically. I didn't want to rewrite the config files like they posted, rather we needed the ability to show the allowed roles for all directories and pages in our application. Our application is small. It has a total of 15 directories and less than 100 pages so this runs pretty quickly. Your mileage my vary depending on the size of your web site.
I started from the root directory and recursively searched for all webconfigs. I added them with their path to a string list then iterated through the list and called my ListRoles function. This function opens the web config and gets the location collection. Then it looks for the "system.web/authorization" like Ronald did. If it finds an authorization section it loops through the rules and excludes any inherited rules and focuses on AuthorizationRuleAction.Allow with associated roles:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web.Configuration;
public void DisplayWebPageRoles()
{
//First walk the directories and find folders with Web.config files.
//Start at the root
DirectoryInfo baseDir = new DirectoryInfo(Server.MapPath("~/"));
//Do a little recursion to find Web.Configs search directory and subdirs
List<string> dirs = DirectoriesWithWebConfigFile(baseDir);
//Replace the folder path separator except for the baseDir
for (int i = 0; i < dirs.Count; i++)
{
dirs[i] = dirs[i].Replace(
baseDir.FullName.Replace("\\", "/"),
"/" + baseDir.Name + (i > 0 ? "/" : ""));
}
//Now that we have the directories, we open the Web.configs we
//found and find allowed roles for locations and web pages.
for (int i = 0; i < dirs.Count; i++)
{
//Display on page, save to DB, etc...
ListRoles(dirs[i]);
}
}
public List<string> DirectoriesWithWebConfigFile(DirectoryInfo directory)
{
List<string> dirs = new List<string>();
foreach (FileInfo file in directory.GetFiles("Web.config"))
{
dirs.Add(directory.FullName.Replace("\\","/"));
}
foreach (DirectoryInfo dir in directory.GetDirectories())
{
dirs.AddRange(DirectoriesWithWebConfigFile(dir));
}
return dirs;
}
private void ListRoles(string configFilePath)
{
System.Configuration.Configuration configuration =
WebConfigurationManager.OpenWebConfiguration(configFilePath);
//Get location entries in web.config file
ConfigurationLocationCollection locCollection = configuration.Locations;
string locPath = string.Empty;
foreach (ConfigurationLocation loc in locCollection)
{
try
{
Configuration config = loc.OpenConfiguration();
//Get the location path so we know if the allowed roles are
//assigned to a folder location or a web page.
locPath = loc.Path;
if (locPath.EndsWith(".js")) //Exclude Javascript libraries
{
continue;
}
AuthorizationSection authSection =
(AuthorizationSection)config
.GetSection("system.web/authorization");
if (authSection != null)
{
foreach (AuthorizationRule ar in authSection.Rules)
{
if (IsRuleInherited(ar))
{
continue;
}
if (ar.Action == AuthorizationRuleAction.Allow
&& ar.Roles != null
&& ar.Roles.Count > 0)
{
for (int x = 0; x < ar.Roles.Count; x++)
{
//Display on page, save to DB, etc...
//Testing
//Response.Write(
// configFilePath + "/web.config" + ","
// + configFilePath + "/" + locPath + ","
// + ar.Roles[x] + "<br />");
}
}
}
}
}
catch (Exception ex)
{
//Your Error Handling Code...
}
}
}
From French IIS support Team blog
private bool IsRuleInherited(AuthorizationRule rule)
{
//to see if an access rule is inherited from the web.config above
//the current one in the hierarchy, we look at two PropertyInformation
//objects - one corresponding to roles and one corresponding to
//users
PropertyInformation usersProperty = rule.ElementInformation.Properties["users"];
PropertyInformation rolesProperty = rule.ElementInformation.Properties["roles"];
//only one of these properties will be non null. If the property
//is equal to PropertyValueOrigin.Inherited, the this access rule
//if not returned in this web.config
if (usersProperty != null)
{
if (usersProperty.ValueOrigin == PropertyValueOrigin.Inherited)
return true;
}
if (rolesProperty != null)
{
if (rolesProperty.ValueOrigin == PropertyValueOrigin.Inherited)
return true;
}
return false;
}
Use the Roles.GetAllRoles() method
http://msdn.microsoft.com/en-us/library/system.web.security.roles.getallroles.aspx
and here is an example where they list all roles:
http://weblogs.asp.net/scottgu/archive/2005/10/18/427754.aspx