custom config file in asp.net - asp.net

In my project I need store complex application settings and i dont want store it in db.
Application settings are available through administration ui to edit/change etc.
So, if i store settings in config, every time when configugration is changed, application is restart.
So second idea is loading external file from file (for example "AppSettings.conf") stored in project.
Question is pretty simple : Is possible load and save setting from external file without restarting application?
Thanks

yes, store the settings in an XML file, and you can read/write to/from an XML file just fine. But, you can't point any of the existing components stored in the web.config (such as the <authentication> or <authorization> elements) to that XML file... that won't work. Only your custom settings would.
HTH.

Finally decided to save/load application settings in db.

Rather than creating a custom config file, create a custom configuration section for the web.config:
Here's just an example:
public class SomeConfigurationSection: ConfigurationSection
{
[ConfigurationProperty("configurationData")]
public string ConfigurationData
{
get
{
return this["configurationData"] as string;
}
set
{
this["configurationData"] = value;
}
}
[ConfigurationProperty("otherConfigurationData")]
public int OtherConfigurationData
{
get
{
return Convert.ToInt32(this["otherConfigurationData"]);
}
set
{
this["otherConfigurationData"] = value;
}
}
}
EDIT
Another possible solution would be to use the Settings.setttings file under the Properties folder. I believe you can add, edit, and delete settings from here without an application restart:
//add a setting
Properties.Settings.Default.Context.Add("foo", "bar");
//edit a setting
Properties.Settings.Default.Context["foo"] = "bar";
//remove a setting
Properties.Settings.Default.Context.Remove("foo");
You can access this file under the Properties folder, or in the properties window of the web application (Properties > Settings).

Related

AjaxFileUpload file not inheriting folder permissions

I am successfully uploading a file using the AjaxFileUpload control from the AjaxToolkit. I had to give IUSR write permissions to the folder but after that there was no problem.
However, the files which are uploaded are not inheriting the permissions set on the folder, so they do not have IUSR listed. On my local machine this isn't much of a problem, but on the server it means a 401 is returned as IUSR read permission is needed on the file in order to read it.
From what I can see, the folder is set to apply permissions to files inside, which leads me to believe it is something to do with the way the file is saved to the folder. Does anyone know anything more about this?
UPDATE
OK so I found some more information about the problem. This article suggested that before the file is saved to the specified location, it is first held in a temporary location. The workaround they suggest (changing the temporary location to somewhere known and setting permissions on it) does not appear to work for the AjaxFileUpload. The rest of the project temporary files appear in there, but using the Process Monitor I can see that my temporary location is somewhere else entirely for the uploaded images:
If I set the permissions on this folder for IUSR then my problem is fixed. So the next question, will this location always exist? My guess is no. If so, how can I change it?
UPDATE 2
OK so I found there was some static methods on the control which are set to build the temporary directory:
public static string BuildTempFolder(string fileId)
{
return Path.Combine(AjaxFileUpload.BuildRootTempFolder(), fileId);
}
public static string BuildRootTempFolder()
{
string path = Path.Combine(Path.GetTempPath(), "_AjaxFileUpload");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return path;
}
One of the key lines is probably this: string path = Path.Combine(Path.GetTempPath(), "_AjaxFileUpload"); which seems to match with what I'd found in my process monitor. It seems that without rebuilding the project I'm stuck with their default settings, so I may look elsewhere for a different tool.
thanx chris
I had the same problem and I am not going to drop ajaxfileUpload control now , so I found workaround
1- download the source code from codeplex
2- open "source code directory"\Server\AjaxControlToolkit\AjaxFileUpload\AjaxFileUpload.cs and add static property name it UploadRootPath
public static string UploadRootPath
{
get;
set;
}
3- modify BuildRootTempFolder function :
public static string BuildRootTempFolder()
{
var rootTempFolder = "";
if (UploadRootPath == "")
{
rootTempFolder = Path.Combine(Path.GetTempPath(), TemporaryUploadFolderName);
}
else {
rootTempFolder = Path.Combine(UploadRootPath, TemporaryUploadFolderName);
}
if (!Directory.Exists(rootTempFolder))
Directory.CreateDirectory(rootTempFolder);
return rootTempFolder;
}
4- Build solution and use the new AjaxControlToolkit.dll in your project.
5- in your project set the directory where you want the temporary files to be saved in .
AjaxControlToolkit.AjaxFileUpload.UploadRootPath = Server.MapPath("~/Upload/Temp/");
I wish DevExpress guys do it in their next update , and I am sure they will do it in a decent way

The current configuration system does not support user-scoped settings

I'm trying to use a settings file to store the user preferences when he/she logins on the application.
I defined them as user (scope) but I am getting
System.Configuration.ConfigurationErrorsException: The current configuration system does not support user-scoped settings.
What may be a good solution?
When I had this problem, it turned out that I had a reference to a dll which had a Settings.settings (or Settings.Designer.cs) file.
What happens is that when editing the Setting.settings file, upon clicking the blank line at the bottom, a new line is added with template information and a default user setting instead of application setting. This is a nice feature but you could see how after changing the template and adding your new setting, then clicking below to lose focus a new template line is added and if you are not paying attention, you accidently add a user setting. Check if you have this file in a referenced dll and remove any user settings.
User-scoped settings are indeed not supported for a Web application. And they wouldn't work, User settings would have to be saved under the Users\<username>\... folder on the server.
You have a wide choice of web techniques:
persistent cookies
ASP.NET Membership profiles
your own Db
You can make Application scope settings writable by simply adding a setter to the property definition in Settings.Designer.cs. For instance:
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("AdminContext")]
public string DbContext
{
get { return ((string)(this["DbContext"])); }
set { this["DbContext"] = value; } }
The caveat is that the Settings.Designer.cs is auto-generated, and therefore if you use the designer UI, your setters will be overwritten.
This works in console and web applications.

asp.net: prevent files from bots

Application uses Forms authentication and has folders with excel files. Need to prevent
unauthorized, automated scripts or bots from accessing these folders. What would be best option to prevent this?
Have the authorization node of the lockElementsattribute value set in the
Web.config file.
Have a element added to the element in the Web.config
file.
3 Use (CAPTCHA) image control on each page of the application.
4 Use Robots.txt file implemented in the root directory of the application.
Have the Excel files mapped to the ASP.NET ISAPI filter.
Or are there better options? Httmodules?
You could protect the excel files by writing a custom httpmodule and validating that they are authed via the forms auth before giving them access to the file.
In addition I would use the robots.txt file as well to exclude them. Those that follow the rules will stop looking at that point. The rest will be taken care of with the custom httpmodule.
The most secure solution would be to store your files outside of the web-tree and then serve them up via a HttpHandler. The simplest handler to create in ASP.NET would be an .ashx Handler as outlined in this blog post.
Download File
Your handler would then check the user request to ensure the user is authenticated and then stream the file back. In simplified pseudo-C# code this would be something like:
public void ProcessRequest(HttpContext context)
{
string file = context.Request["file"];
if (user.IsAuthenticated())
{
OutputFile(file, context)
}
}
private void OutputFile(string file, HttpContext context)
{
string fileContent = LoadFileFromSecureDirectory(file);
Response.Output(fileContent);
}
Map the Excel files to the ASP.NET ISAPI filter and add a
<deny> element to the <authorization> element in web.config,

Configure IIS7 to server static content through ASP.NET Runtime

I searched high an low and still cannot find a definite answer.
How do I configure IIS 7.0 or a Web Application in IIS so that ASP.NET Runtime will handle all requests -- including ones to static files like *.js, *.gif, etc?
What I'm trying to do is as follows.
We have kind of SaaSy site, which we can "brand" for every customer. "Branding" means developing a custom master page and using a bunch of *.css and other images.
Quite naturally, I'm using VirtualPathProvider, which operates like this:
public override System.Web.Hosting.VirtualFile GetFile(string virtualPath)
{
if(PhysicalFileExists(virtualPath))
{
var virtualFile = base.GetFile(virtualPath);
return virtualFile;
}
if(VirtualFileExists(virtualPath))
{
var brandedVirtualPath = GetBrandedVirtualPath(virtualPath);
var absolutePath = HttpContext.Current.Server.MapPath(brandedVirtualPath);
Trace.WriteLine(string.Format("Serving '{0}' from '{1}'",
brandedVirtualPath, absolutePath), "BrandingAwareVirtualPathProvider");
var virtualFile = new VirtualFile(brandedVirtualPath, absolutePath);
return virtualFile;
}
return null;
}
The basic idea is as follows: we have a branding folder inside our webapp, which in turn contains folders for each "brand", with "brand" being equal to host name. That is, requests to http://foo.example.com/ should use static files from branding/foo_example_com, whereas http://bar.example.com/ should use content from branding/bar_example_com.
Now what I want IIS to do is to forward all requests to static files to StaticFileHandler, which would then use this whole "infrastructure" and serve correct files. However, try as I might, I cannot configure IIS to do this.
II7 already does that if the application pool's Managed Pipeline Mode is set to Integrated which is the default. In Integrated mode, ASP.NET handles all requests including those for static objects.
If you have to leave your application pool in Classic Mode then you need to use the same techniques you would use in IIS 6 to explicitly create handlers for the various static extensions.
Additional Information Based on Comments: I think your missing piece is creating an HttpHandler to handle the other extensions (.js, .css, etc.). Without this, then ASP.NET will use the default handling for these types of files. You would create a reference to you handler in your web.config. This article is an example of creating an HttpHandler for static files.
Kudos to everyone, but the problem was in totally different space.
VirtualPathProvider cannot be used in a pre-compiled web site. I'm furious.

Displaying an image on a ASP.NET (3.5) webpage, from a database

I'm new to ASP.NET. I'm developing a site with ASP.NET 3.5 (VS 2008), and all I want to do is this:
Upload a image to the server (I'm doing this through FileUpload control)
Save the bytes (byte[]) in the database in some table
When user calls a page, say, Index.aspx?id=10, then I go a table, pull the relevant row which has id=10, the one of the cells has the image in the byte[] format
I now want to show this image on the webpage which has other things as well.
I can't seem to figure out how to do this - the image control only expects a URL and I don't want to save the image on the disk..
Any ideas please?
-Rick
You need to create a class that implements the IHttpHandler interface. Something like this should suffice:
public class ImageHttpHandler : IHttpHandler
{
//code omitted
public bool IsReusable
{
get
{
return (false);
}
}
public void ProcessRequest(HttpContext context)
{
//GetImageUrl is implemented elsewhere
var imageURL = GetImageUrl(context.Request.Params["URL"]);
//GetImageContentFromDatabase returns a structure with MIMEType and Content properties
var imageData = GetImageContentFromDatabase(imageURL);
if(imageData != null)
{
context.Response.ContentType = imageData.MIMEType;
context.Response.BinaryWrite(imageData.Content);
}
else
{
context.Response.StatusCode = 404;
}
}
}
You can place this class within your App_Code directory or, if you want to generalize this behavior, a separate assembly.
You can then reference this handler in your web.config file like so:
<system.web>
<httpHandlers>
<add verb="GET" path="*.imgx" type="ImageHttpHandler"/>
</httpHandlers>
</system.web>
This implies that all get requests for files with extension imgx should be directed to the class ImageHttpHandler.
This will work well with Cassini (the Visual Studio Development Web Server), but you will need to make an additional change to your IIS website/virtual directory.
Go to the IIS MMC snap-in and access the properties of this directory. You need to find the Configuration button which is housed within the "Virtual Directory" or "Home Directory" tabs. Once there, add imgx as an application extension, set the executable to be aspnet_isapi.dll. This is located, on my machine, at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727. Choose "All verbs" for simplicity, and uncheck "Verify that file exists."
The hyperlinks you define in your web pages should use the imgx extension. Depending on your needs, you can define your links as "myimage.imgx" or "GetImage.imgx?id=XXX." This depends on your needs and how you intend to retrieve the content of the image from the database.
Take a look at that : asp.net store image in sql and retrieve for aspimage

Resources