How to encode URL chunks - asp.net

I'm developing a ASP.NET MVC application, and I'm managing file names in my URL paths. I need to encode url file names, to avoid errors on some paths (for example, when the character '+' is used, it fails under Mono/XSP).
But I need to encode only the file names, for example:
For example, given this input:
/dir1/this has spaces/file+name.txt
I need the following output:
/dir1/this%20has%20spaces/file%2bname.txt
Note that I don't want to encode the path separator. Any suggestion?
Thanks in advance.
EDIT: I'm building my URL using the following:
<%= Html.ActionLink(
Html.Encode(revision.Name),
"Details",
"Items",
Model.GetRouteParameters(revision.FullPath),
null) %>
Where GetRouteParameters is the following:
public object GetRouteParameters(string path)
{
return new
{
repository = ItemProvider.GetBrowsingObject().Repository,
path = path,
browsing = ItemProvider.GetBrowsingObject().Name
};
}
I would like to encode any "dangerous" character in the repository, the path or the browsing names.

You can use HttpUtility.UrlEncode to encode the strings in a url safe way. You need to url encode the separate path components and then create the path.

Related

How to map several segments of URL to one PathVariable in spring-mvc?

I'm working on a webapp, one function of which was to list all the files under given path. I tried to map several segments of URL to one PathVariable like this :
#RequestMapping("/list/{path}")
public String listFilesUnderPath(#PathVariable String path, Model model) {
//.... add the file list to the model
return "list"; //the model name
}
It didn't work. When the request url was like /list/folder_a/folder_aa, RequestMappingHandlerMapping complained : "Did not find handler method for ..."
Since the given path could contains any number of segments, it's not practical to write a method for every possible situation.
In REST each URL is a separate resource, so I don't think you can have a generic solution. I can think of two options
One option is to change the mapping to #RequestMapping("/list/**") (path parameter no longer needed) and extract the whole path from request
Second option is to create several methods, with mappings like #RequestMapping("/list/{level1}"), #RequestMapping("/list/{level1}/{level2}"), #RequestMapping("/list/{level1}/{level2}/{level3}")... concatenate the path in method bodies and call one method that does the job. This, of course, has a downside that you can only support a limited folder depth (you can make a dozen methods with these mappings if it's not too ugly for you)
You can capture zero or more path segments by appending an asterisk to the path pattern.
From the Spring documentation on PathPattern:
{*spring} matches zero or more path segments until the end of the path and captures it as a variable named "spring"
Note that the leading slash is part of the captured path as mentioned in the example on the same page:
/resources/{*path} — matches all files underneath the /resources/, as well as /resources, and captures their relative path in a variable named "path"; /resources/image.png will match with "path" → "/image.png", and /resources/css/spring.css will match with "path" → "/css/spring.css"
For your particular problem the solution would be:
#RequestMapping("/list/{*path}") // Use *path instead of path
public String listFilesUnderPath(#PathVariable String path, Model model) {
//.... add the file list to the model
return "list"; //the model name
}

How to write a link to an Alfresco Share folder? (within a site)

I want to create an HTTP link to a particular folder in Alfresco Share.
Alfresco Share encodes paths in a rather convoluted way:
thesite
http://server/share/page/site/thesite/documentlibrary
thesite/documentLibrary/somefolder/anotherfolder
http://server/share/page/site/thesite/documentlibrary#filter=path|%2Fsomefolder%2Fanotherfolder
thesite/documentLibrary/éß和ệ
http://server/share/page/site/s1/documentlibrary#filter=path|%2F%25E9%25DF%25u548C%25u1EC7
thesite/documentLibrary/a#bc/éß和ệ
http://server/share/page/site/thesite/documentlibrary#filter=path%7C%2Fa%2523bc%2F%25E9%25DF%25u548C%25u1EC7%7C
I suspect it is a double URLencode, with the exception of slashes which are only URLencoded once.
But I am not 100% sure.
Is there a C# library that does this encoding?
You might find it easier to use the legacy ?path= parameter for document library folder URL creation.
Using the example path /Sample Content/∞⊕⊗¤☺☹★☆★☆★ instead of building a URL of the form
http://alfresco.example/share/page/site/mike/documentlibrary#filter=path%7C%2FSample%2520Content%2F%25u221E%25u2295%25u2297%25A4%25u263A%25u2639%25u2605%25u2606%25u2605%25u2606%25u2605%7C&page=1
you can generate one that looks like
https://alfresco.example/share/page/site/mike/documentlibrary?path=/Sample%20Content/%E2%88%9E%E2%8A%95%E2%8A%97%C2%A4%E2%98%BA%E2%98%B9%E2%98%85%E2%98%86%E2%98%85%E2%98%86%E2%98%85
So using C# you'd use Uri.EscapeUriString() on the path and append it to the base document library URL with ?path=
You can see how the path parameter is interpreted in documentlibrary.inc.ftl
Check org.alfresco.repo.web.scripts.site.SiteShareViewUrlGetfor an implementation. Its not very elegant, but seems pretty complete, probably a good starting point for your own class.
There really should be a helper class for this, but maybe I'm missing something.
I could not find a library, so I wrote the following code:
if (path.Contains("documentLibrary"))
{
int firstSlashPosition = path.IndexOf("/");
string siteName = path.Substring(0, firstSlashPosition);
string pathWithinSite = path.Substring(firstSlashPosition + "/documentLibrary".Length);
string escapedPathWithinSite = HttpUtility.UrlEncode(pathWithinSite);
string reescapedPathWithinSite = HttpUtility.UrlEncode(escapedPathWithinSite);
string sharePath = reescapedPathWithinSite.Replace("%252f", "%2F");
return "http://server/share/page/site/" + siteName + "/documentlibrary#filter=path|" + sharePath;
}
else
{
// Site name only.
return "http://server/share/page/site/" + path + "/documentlibrary";
}
Any correction or better answer would be much appreciated!

how to get the list of the images from the Application Directory

I am Developing a Web site and i need to read all the images from the images folder in the
application directory and i have to display all the images on the page can any body tell me how to read all the images from the images folder which is in my application directory.
Thanks in Advance.
This could help
https://web.archive.org/web/20210304125318/https://www.4guysfromrolla.com/articles/052803-1.aspx
To add to the answer of Mr. Disappointment, you can get a list of all the files using the command specified,
To get the path of the application using Server.MapPath.
Then getting the list of files, you can simply iterate and filter on the extensions you need.
This will get you an array of the file names in a given path:
string[] fileNames = System.IO.Directory.GetFiles(yourPath);
You can then generate URLs for them and use <img> tags written out to the response, for example something like ought to get the valid URLs:
string relativePath = Request.AppRelativeCurrentExecutionFilePath;
relativePath = relativePath.Substring(0, relativePath.LastIndexOf('/') + 1);
string requestPath = Path.GetDirectoryName(Server.MapPath(relativePath));
string[] fileNames = Directory.GetFiles(requestPath);
List<string> imageUrls = new List<string>(fileNames.Length);
foreach(var fileName in fileNames)
{
imageUrls.Add(Path.Combine(relativePath, Path.GetFileName(fileName)));
}
You could just write out the <img> items in the loop. Also, note that a call to GetFiles supplying only a path will return all available files so you might want to supply a searchPattern argument such as *.jpg.

What is the most efficient way to perform the reverse of Server.MapPath in an ASP.Net Application

I am building an MVC application in which I am reading a list of files from the file system and I want to pass the relative URL to that file to the view, preferably prefixed with "~/" so that whatever view is selected cab render the URL appropriately.
To do this, I need to enumerate the files in the file system and convert their physical paths back to relative URLs. There are a few algorithms I've experimented with, but I am concerned about efficiency and minimal string operations. Also, I believe there's nothing in the .Net Framework that can perform this operation, but is there something in the latest MVC release that can?
At the moment I don't know any built-in method to do it, but it's not difficult, I do it like this:
We need to get the Application root, and replace it in our new path with ~
We need to convert the backslashes to slashes
public string ReverseMapPath(string path)
{
string appPath = HttpContext.Current.Server.MapPath("~");
string res = string.Format("~{0}", path.Replace(appPath, "").Replace("\\", "/"));
return res;
}
Isn't this what UrlHelper.Content method does? http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.content.aspx
I did some digging, trying to get the UrlHelper class to work outside of a controller, then I remembered a old trick to do the same thing within an aspx page:
string ResolveUrl(string pathWithTilde)
Hope this helps!
See:
https://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveurl(v=vs.110).aspx

how can an .ASPX page get its file system path?

I have a page something.aspx, with associated codebehind something.aspx.cs. In that codebehind, I want to know the filesystem location of something.aspx. Is there any convenient way to get it?
Update: I got several excellent answers, which unfortunately didn't work because of something else crazy I'm doing. I'm encoding some additional information on the URL I pass in, so it looks like this:
http://server/path/something.aspx/info1/info2/info3.xml
The server deals with this OK (and I'm not using querystring parameters to work around some other code that I didn't write). But when I call Server.MapPath(Request.Url.ToString()) I get an error that the full URL with the 'info' segments isn't a valid virtual path.
// File path
string absoluteSystemPath = Server.MapPath("~/relative/path.aspx");
// Directory path
string dir = System.IO.Path.GetDirectoryName(absoluteSystemPath);
// Or simply
string dir2 = Server.MapPath("~/relative");
Request.PhysicalPath
Server.MapPath is among the most used way to do it.
string physicalPath = Server.MapPath(Request.Url);
Server.MapPath( Request.AppRelativeCurrentExecutionFilePath )

Resources