Using VB.net for file download and AD check - asp.net

Thanks for your help on this.
I've got an ftp site and web tools (vb.net) that manage the files in the site.
The ftp site and the tools use AD groups (intranet) to check permissions.
Some directories are restricted, some not so much.
On the download tool I'm using:
My.Computer.Network.DownloadFile(urlPath, userProfileLocal & fileNameLab.Value, domainNameHid.Value, "", True, 60000, True, FileIO.UICancelOption.DoNothing)
urlPath might equal ftp://ftp.net/foo/bar/myfile.zip
For the userProfileLocal I'm trying to use Dim userProfileLocal As String = Environment.GetEnvironmentVariable("USERPROFILE") & "\documents"
fileNameLab.Value is pre-populated in a hidden input and is the file name
domainNameHid.Value is pre-populated and would look something like DOMAIN\jimmmy
I'm keeping the password value blank since I'm hoping to use AD.
I found this which says I should be using ICredentials in place of the username and password, but I'm having toubles implementing the ICredentials part, and not even sure if this is correct.
The rest I think is accounted for.
I keep getting the error Access to the path 'C:\Windows\system32\config\systemprofile' is denied.
First, that's not the path I was going for. I was hoping that GetEnvironmentVariable("USERPROFILE") & "\documents" would create the path to the documents folder... Is there a better way to do this? Why can't one just be prompted to browse to a location or a default location be used?
Second,... well, second would have to do with how I don't have perms to download to my own disk. But if the firstly can be solved, then I think this will too.
I think my AD requirements are mucking up the works for what should be a simple task. Can someone point me in the right direction for an example of ICredentials (if that's what I need) or else let me know what I'm doing wrong here?

I just wanted to respond and let those who are looking know that I found an answer.
Instead of the code used above, I ended up using the following:
Dim mydocsdir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Response.AppendHeader("Content-Disposition", "attachment; filename=" & fileNameLab.Value)
Response.Clear()
Response.WriteFile(Path.Combine(mydocsdir, fileNameLab.Value))
This worked like a charm.
I need to write a special thanks to Darin Dimitrov who provided an answer in another post. His answer was actually the simple answer I thought it could be... but my VB.Net experience, while little now, is still growing.

Related

ASP.NET setting a path for file with VB

So this is a pretty dumb question, and one I am clearly misunderstanding for whatever the reason. I have an ASP.net project and the default aspx page loads a file. I made a class to deal with file handling, in it I hard coded the local directory to where that file is. I want to make that path relative to the default.aspx page. I can't figure out how to do that. I have read a lot of stuff on MSDN, and it makes simple sense, but when I put it to code I can't seem to get it right.
I feel my answer is here, I understand what it is saying but I can't translate that to my program.http://msdn.microsoft.com/en-us/library/ms178116.aspx. Code such as
Dim rootPath As String = Server.MapPath("~")
makes sense to me but I can't use 'Server' for some reason.
I have used this spot of code to supplement my problem for now.
string=System.AppDomain.CurrentDomain.BaseDirectory()
Any help leading me on the right....path, would be appreciated.
Try
Dim rootPath As String = HttpContext.Current.Server.MapPath("~")
from your class.

Writing file to users giving sporadic error in IE

I have a very interesting issue with only specific IE implementations. I have an ASPX page that is used to write files down to the user, as part of the process the page uses the following code to write the file to the user.
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=download" + System.IO.Path.GetExtension(oInfo.SupportingFilePath));
Response.ContentType = "application/octet-stream";
Response.WriteFile(Server.MapPath(oInfo.SupportingFilePath));
Response.End();
In 99.5% of the cases this works just fine, however, in certain rare circumstances within IE only on specific machines, the user is prompted to download the .aspx page, and/or is given an error message.
Anyone have an idea of what is going on here?
Per RFC2231, MIME headers' parameter values have to be included in double quotes: http://www.ietf.org/rfc/rfc2231.txt (page 3, if you are interested).
It should be something like "attachment;filename=""download" + System.IO.Path.GetExtension(oInfo.SupportingFilePath) + """");
Although this should not be happening because you've set the ContentType and content-disposition, I believe that IE's built-in MIME sniffing/handling is what is causing the problem here. Here are a couple of work-around/hacks you can try:
Add the file extension to the query string on the .aspx page that is transferring the file, i.e., http://blahblahblah/page.aspx?.ext
If you are using IE 8, you can specify another response header for "nosniff," as specified here.
I'm still having issues with this, as documented here, but I hope one of these helps.

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)

ASP.NET: Get *real* raw URL

In ASP.NET, is there any way to get the real raw URL?
For example, if a user browse to "http://example.com/mypage.aspx/%2F", I would like to be able to get "http://example.com/mypage.aspx/%2F" rather than "http://example.com/mypage.aspx//".
I would of course like a clean way to do it, but I can live with a hacky approach using reflection or accessing obscure properties.
At the moment, I try to use the uri in the Authorization-header (which works), but I cannot rely on that always being there.
EDIT:
What I really want to do is to be able to distinguish between "http://example.com/mypage.aspx/%2F" and "http://example.com/mypage.aspx/%2F%2F".
It looks like ASP.NET first converts "%2F%2F" into "//" and then converts the slashes into a single slash.
So just re-encoding it is not going to work.
I wasn't able to test this because it only works in IIS and not the ASP.NET Development Server that is part of Visual Studio, but try:
Request.ServerVariables[ "HTTP_URL" ]
The following code works for me:
IServiceProvider serviceProvider = (IServiceProvider)HttpContext.Current;
HttpWorkerRequest workerRequest = (HttpWorkerRequest)serviceProvider.GetService(typeof(HttpWorkerRequest));
string realUrl = workerRequest.GetServerVariable("HTTP_URL");
Note that this only works when running on the IIS and not under f.x. ASP.NET Development Server!
Thanks to Lucero for the answer in another thread and Zhaph for pointing me to the thread.
See also:
Get the exact url the user typed into the browser
Server.HtmlEncode(Request.RawUrl);
The raw URL is defined as the part of the URL following the domain information. In the URL string http://www.contoso.com/articles/recent.aspx, the raw URL is /articles/recent.aspx. The raw URL includes the query string, if present.
see also:link text
I can't test here, but this might be what you need:
Request.Url.AbsoluteUri
Request.RawUrl will return the application relative path(including querystring info) while Request.Url will return the complete path(including querystring info).
For more information, see "Making sense of ASP.NET paths".
Well, you could just encode it back to the url-encoded version.
Get the url from the request and urlencode only the query string part and then concatenate them

How to read an external page's title?

I think it's possible with jQuery, but any ASP.NET serverside code is good for my situation too.
With jQuery I can load a page to for example a div, and filter the div for <title> tag, but I think for heavy pages, it is not good to first read all of the content and then read the title tag..
or maybe it has a very simple solution? anyways I couldnt find anything about that from internet.
thanks
okay thanks to cjjer and Boo, I've just read more about regex and finally the code below is working for me.
Dim qq As New System.Net.WebClient
Dim theuri As New Uri(TextBox1.Text)
Dim res As String = qq.DownloadString(theuri)
Dim re As Regex = New Regex("<title\b[^>]*>(.*?)</title>", RegexOptions.Singleline)
Dim ma As Match = re.Match(res)
If Not ma Is Nothing And ma.Success Then
Response.Write(ma.Groups(1).Value.ToString())
Else
Response.Write("error")
End If
but anyways, the problem remains, this code is downloading the whole page and seeking through it, which one heavy websites it took more than 2 or 3 secconds to complete, but seems it is the only way as far as I know :|
Is there any suggestions to refine this code?
cjjer almost got it right.
First, change the regex to: <title>(?<Content>.*?)?</title>
Second, you need to create a match object first (just in case your URI does not have a title).
Match tMatch = new RegEx(#"<title>(?<Content>.*?)?</title>").Match(new System.Net.WebClient().DownloadString(url));
if ((null != tMatch) && (tMatch.IsSuccess)) {
// yay.
title = tMatch.Groups("Content").value;
}
Titles usually appear within the first few hundred bytes, so you could try a range request for the first 1KiB or so, try parsing that (with an error-correcting parser, since some closing tags will be missing) and if that fails fall back to loading the whole page.
It would be security risk for you to load any other web page into yours, just for title read... You should do this with server side scripting (asp.net, php, ...) and just output the title to your web page. Thing of some kind of caching because it is seamless to fetch titles on every request.
There is no simple clean way to retrieve an external page's title. You could do it server side using a WebClient and parsing the response.
However it may be worth reviewing the requirement, is it really necessary, how much extra traffic and latency is it going to generate. Consider also that you could be generating load on the external site which is unaware all you want is a title, the page creation may be quite expensive.
string title=Regex.Match(new System.Net.WebClient().DownloadString(url),(#"<title>(.*?)</title>"))[0].Groups[1].ToString();
try.i am not sure.
I am not sure whether all servers support this.
See, if this helps
char[] data = new char[299];
System.Net.HttpWebRequest wr =(HttpWebRequest)WebRequest.Create("http://www.yahoo.com");
wr.AddRange("bytes", 0, 299);
HttpWebResponse wre = (HttpWebResponse)wr.GetResponse();
StreamReader sr = new StreamReader(wre.GetResponseStream());
sr.Read(data, 0, 299);
Console.WriteLine((data));
sr.Close();
EDIT: Try checking with some network monitoring tool to find out what is the text that servers send out. I used fiddler to see the output & wrote it to console.
EDIT2: I am assuming the title to be in the beginning of the page.

Resources