Accessing httpRuntime maxRequestLength programmatically - asp.net

I've looked around and have yet found a way to sync between the config section for file size and the max I am allowing. Is it even possible?
Is it just best practice to allow very large file sizes in the web.config file and then enforce smaller sizes in your implementations?

Try something like this:
HttpRuntimeSection section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
So then you get section.MaxRequestLength

Related

ASP.NET - Determine max file upload size at runtime

I have several places on my site where I have helptext telling users what the maximum allowed file upload size is. I would like to be able to have this be dynamic, so that if I change the request limits in the web.config file, that I don't have to go and change the form instructions in a bunch of places. Is this possible using ConfigurationManager or something?
Since you didn't give any further Details: As pointed out here, you have 2 options to set a size Limit for your whole Application.
Depending on that you need to approach this a little differently:
If you use <httpRuntime maxRequestLength="" /> you can get the Info through WebConfigurationManager
//The null in OpenWebConfiguration(null) specifies that the standard web.config should be opened
System.Configuration.Configuration root = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
var httpRuntime = root.GetSection("system.web/httpRuntime") as System.Web.Configuration.HttpRuntimeSection;
int maxRequestLength = httpRuntime.MaxRequestLength;
In Priciple you should be able to do the same with <requestLimits maxAllowedContentLength="" />. But the system.webServer-Section in WebConfigurationManager is declared as IgnoreSection and can't be accessed. It may be possible to change this behaviour in application.config or similiar of IIS. But since (in my case) even the .SectionInformation.GetRawXml() failed, I tend to declare this a lost case.
My Solution in this case would be to access the Web.config-File manually:
var webConfigFilePath = String.Format(#"{0}Web.config", HostingEnvironment.MapPath("~"));
XDocument xml = XDocument.Load(System.IO.File.OpenRead(webConfigFilePath));
string maxAllowedContentLength = xml.Root
.Elements("system.webServer").First()
.Elements("security").First()
.Elements("requestFiltering").First()
.Elements("requestLimits").First()
.Attributes("maxAllowedContentLength").First().Value;
Another Solution to this is proposed by #Roman here using Microsoft.Web.Administration.ServerManager for which you need the Microsoft.Web.Administration Package

Serving large Videofiles fails

I'm using the Echo Framework's static filehandler for serving uploaded files out of my upload directory.
e := echo.New()
e.Static("/uploads","uploads")
This works fine for smaller video files. I've tested it with a 20MB videofile, which works fine. Larger files, for example a 50MB testfile, do not work. The underlying TCP connection gets closed before the whole file is being served.
Does anyone know if there is a filesize limit or a timer that can be set to prevent this?
you are looking for echo.File(). This method serves, longer files, like yours because the underlying net/http package used in http.FileServer() and echo.File() are the same. You can add something like this
echo.File("route","filepath",middleware).
You can also use the same functionality which is associated with echo.Context by the same name c.File(). Here the function definition is shorter and has an example in echo webpage https://echo.labstack.com/cookbook/file-download.

Is this possible to limit the file size when uploading the file size in asp?

In my Asp page i want to limit the file size uploaded by the client at the time of immediately choosing the file name.for example,I want to limit file size up to 2MB only.So, after user choosing the file name, i have to check the file size.If it is less than 2MB then no issue.Otherwise, i have to display the error message...
Is it possible?
You can use the maxRequestLength attribute of the httpRuntime element in the web.config as explained here : http://msdn.microsoft.com/en-us/library/e1f13641(v=vs.100).aspx

web.config, configSource, and "The 'xxx' element is not declared" warning

I have broken down the horribly unwieldy web.config file into individual files for some of the sections (e.g. connectionStrings, authentication, pages etc.) using the configSource attribute.
This is working fine, but the individual xml files that hold the section 'snippets' cause warnings in VS.
For example, a file named roleManager.config is used for the role manager section, and looks like this:
<roleManager enabled="false">
</rolemanager>
However I get a blue squiggle under the roleManager element in VS, and the following warning: The 'roleManager' element is not declared
I guess this is something to do with valid xml and schemas etc. Is there an easy way to fix this? Something I can add to the individual files?
Thanks
P.S. I have heard that it is bad practice to break the web.config file out like this. But don't really understand why - can anyone illuminate me?
Searching a workaround to this matter using Custom Config Files, I found this solution. Dont know if is the correct one.
The problem is that VS cant find a schema to validate your .config (xml). If you are using "native" configuration elements or when you create your custom .config files you must set to every xml document a schema.
By default (in VS9 for example) all xml files use \Microsoft Visual Studio 9.0\Xml\Schemas\DotNetConfig.xsd
but you can add more schemas to use.
Before assigning a schema you must create it.
To create a new Schema based on your own custom.config:
open your custom config file
in menubar XML->Create Schema
save it
To assign your schema:
open your custom config file
in properties panel: click on the browse button [..]
set the 'Use' column to your recently created schema
you can assign as many you want. or have one schema for all your different custom .config files
(Sorry, but my English is not so good)
I think that you get the blue squiggles since the schema of your web.config file doesn't declare these custom config sections that you've 'broken out' into individual files.
In investigating this, I see that some of my solutions have the same issue, but the config sections that are provided from microsoft DON'T have the squiggles. eg: we have extracted the appsettings and connectionstrings out into their own files, and they don't get the squiggles, but our custom ones do.
I tried to view the microsoft schema at schemas.microsoft.com/.netconfiguration/v2.0, but I get a 404 when trying to download it.
What I'm trying to say is if you get a copy of the MS schema and alter it to include your external config files, you should be able to get rid of the dreaded squiggles!
HTH,
Lance

stupid caching in asp.net

i use such code
string.Format("<img src='{0}'><br>", u.Avatar);
u.Avatar-it's like '/img/path/pic.jpg'
but in this site i can upload new image instead old pic.jpg. so picture new, but name is old. and browser show OLD picture (cache). if i put random number like /img/path/pic.jpg?123 then works fine, but i need it only ufter upload, not always. how can i solve this?
string imgUrl = _
string.Format("<img src='{0}?{1}'><br>", _
u.Avatar, _
FunctionThatLookupFileSystemForItsLastModified(u.Avatar).Ticks.ToString());
Instead of linking to the images directly, consider setting up a generic HTTP handler to serve the images.
MSDN: HTTP Handlers and HTTP Modules Overview
Stack Overflow: How to use output caching on .ashx handler
Append DateTime.Now.Ticks to the image url:
string imgUrl =
string.Format("<img src='{0}?{1}'><br>", u.Avatar,DateTime.Now.Ticks);
EDIT: I don' think this best practice are even a practice I would use. This is just a suggestion given the limited information given in case the Random implementation isn't truly Random.
Read your post again,,, sorry for general answer.
To workaround it do following
On Application_Start create a Dictionary with uploaded images save it on Application object, set it to null. Once you upload an image add it to this Dictionary. Wrap every place avatars appear on your website with function that evaluates image in Dictionary if found return imagename.jpg?randomnumber and then delete it from a Dictionary else return just an imagename.jpg.
This is going to be heavy because you will need to check each image in Dictionary but this will do exactly what you need.
You can set cache dependancy using the System.Web.Caching.CacheDependency namespace.
This can set the dependancy on the file uploaded, and will release the cache for that file automatically when the file changes.
There are lots of articles and stuff on MSDN and other places so I will not go into details on all that level of detail.
You can do inserts, deletes and other management of cache using the tools available.
(and this does not require you to change the file names or tack on stuff - it knows by the file system that the file changed)

Resources