ASP.NET setting a path for file with VB - asp.net

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.

Related

How to change the language of ErrorText based on culture in aspx.cs

I'm new to the world of asp and was given the task to make sure a site can be translated with the click of a button.
So far i was able to make most of the page translate using recourse files but small things like the error messages you get when trying to login is what i'm stuck on.
The error messages for ASPX(Password is required and Username is required) is inside so i cant "call" my resource file.
The "Username or password is incorrect" message is inside my ASPX.CS is inside a else statement and i cant figure out how to "call" the resource file.
Any help will truly be appreciated.
Thanks in advance
The answer is quite simple. All you need to do is remember to convert to string
https://forums.asp.net/t/1930499.aspx?Displaying+messages+in+the+message+box+from+the+resource+files+in+c+

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)

How to select between include files

I am working on adding a mulit-language feature to an asp classic site. I was trying to do this by using if else statements to select the include I want to load. After a bit of research I found out that includes files are loaded up before any code is handled.
How can I get around this issue and load up the proper include files? Is there a better way of doing this?
Thanks!
You can't, as you've discovered, dynamically choose includes. Includes are handled statically before any script is executed.
The next best thing is Server.Execute. You can use logic to choose what additional files to execute, however whether this fits with your solution is another matter. What do your includes currently contain?
Another approach would be place your "multi-language" choices in some data format such a set of CSV files or XML files. Your code would then load the appropriate "language file".
After countless hours I think I finally came up with a solution. I create xml files for each language (en.xml, fr.xml) with a super simple structure (just a label element with an id and value).
By using an attribute that has a similar name to the label I want to replace I can figure out where everything needs to go, and just pull the value.
I'm not sure if this idea helps, but you could dim the language string variables in one ASP file and then set the variables in separate ASP functions. Then your if statements can call the proper function to set the ASP language string variables. You would not be breaking out the language string into separate files, but it might accomplish what you are trying to achieve.
For example:
dim str1, str2
sub SetLangX
str1 = "String val 1 for lang X"
str2 = "String val 2 for lang X"
end sub
sub SetLangY
str1 = "String val 1 for lang Y"
str2 = "String val 2 for lang Y"
end sub
It can be done - just use include virtual instead of file
edit
I stand corrected - obviously i tried too hard to forget those dark ages.
Years ago i worked on a project where we would create a "container page" for every language version an then include the respective portion of constants.
A working spinoff is still running and if you check the page source of this site you can get an idea how we plugged the pages together.
Some of the included scripts identified by their SVN id tags even included more scripts and maintaining this slowly turned into a nightmare.
I'm sorry i was wrong about the conditional include and there should be a better solution than the one mentioned above.

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.

is it possible to issue dynamic include in asp-classic?

I mean, like php'h include...
something like
my_file_to_be_included = "include_me.asp"
-- >
for what I've seen so far, there are a couple of alternatives, but every one of them has some sort of shortcoming...
what I'm trying to figure out is how to make a flexible template system... without having to statically include the whole thing in a single file with a loooooong case statement...
here there are a couple of links
a solution using FileSysmemObject, just lets you include static pages
idem
yet another one
same thing from adobe
this approach uses Server.Execute
but it has some shortcomings I'd like to avoid... seems like (haven't tried yet) Server.Execute code runs in another context, so you can't use it to load a functions your are planning to use in the caller code... nasty...
same thing
I think this one is the same
this looks promising!!!
I'm not sure about it (couldn't test it yet) but it seems like this one dinamycally handles the page to a SSDI component...
any idea???
No you can't do a dyanmic include, period.
Your best shot at this is a server.execute and passing whatever state it needs via a Session variable:-
Session("callParams") = BuildMyParams() 'Creates some sort of string
Server.Execute(my_file_to_be_included)
Session.Contents.Remove("callParams")
Improved version (v2.0):
<%
' **** Dynamic ASP include v.2.0
function fixInclude(content)
out=""
if instr(content,"#include ")>0 then
response.write "Error: include directive not permitted!"
response.end
end if
content=replace(content,"<"&"%=","<"&"%response.write ")
pos1=instr(content,"<%")
pos2=instr(content,"%"& ">")
if pos1>0 then
before= mid(content,1,pos1-1)
before=replace(before,"""","""""")
before=replace(before,vbcrlf,""""&vbcrlf&"response.write vbcrlf&""")
before=vbcrlf & "response.write """ & before & """" &vbcrlf
middle= mid(content,pos1+2,(pos2-pos1-2))
after=mid(content,pos2+2,len(content))
out=before & middle & fixInclude(after)
else
content=replace(content,"""","""""")
content=replace(content,vbcrlf,""""&vbcrlf&"response.write vbcrlf&""")
out=vbcrlf & "response.write """ & content &""""
end if
fixInclude=out
end function
Function getMappedFileAsString(byVal strFilename)
Dim fso,td
Set fso = Server.CreateObject("Scripting.FilesystemObject")
Set ts = fso.OpenTextFile(Server.MapPath(strFilename), 1)
getMappedFileAsString = ts.ReadAll
ts.close
Set ts = nothing
Set fso = Nothing
End Function
execute (fixInclude(getMappedFileAsString("included.asp")))
%>
Sure you can do REAL classic asp dynamic includes. I wrote this a while back and it has opened up Classic ASP for me in a whole new way. It will do exactly what you are after, even though people seem to think it isn't possible!
Any problems just let me know.
I'm a bit rusty on classic ASP, but I'm pretty sure you can use the Server.Execute method to read in another asp page, and then carry on executing the calling page. 15Seconds had some basic stuff about it - it takes me back ...
I am building a web site where it would have been convenient to be able to use dynamic includes. The site is all ajax (no page reloads at all) and while the pure-data JSON-returning calls didn't need it, all the different html content for each different application sub-part (window/pane/area/form etc) seems best to me to be in different files.
My initial idea was to have the ajax call be back to the "central hub" main file (that kicks the application off in the first place), which would then know which sub-file to include. Simply including all the files was not workable after I realized that each call for some possibly tiny piece would have to parse all the ASP code for the entire site! And using the Execute method was not good, both in terms of speed and maintenance.
I solved the problem by making the supposed "child" pages the main pages, and including the "central hub" file in each one. Basically, it's a javascript round-trip include.
This is less costly than it seems since the whole idea of a web page is that the server responds to client requests for "the next page" all the time. The content that is being requested is defined in scope by the page being called.
The only drawback to this is that the "web pieces" of the application have to live partly split apart: most of their content in a real named .asp file, but enough of their structure and relationship defined in the main .asp file (so that, for example, a menu item in one web piece knows the name to use to call or load another web piece and how that loading should be done). In a way, though, this is still an advantage over a traditional site where each page has to know how to load every other page. Now, I can do stuff like "load this part (whether it's a whole page or otherwise) the way it wants to be loaded".
I also set it up so each part can have its own javascript and css (if only that part needs those things). Then, those files are included dynamically through javascript only the first time that part is loaded. Then if the part is loaded repeatedly it won't incur an extra overhead.
Just as an additional note. I was getting weird ASCII characters at the top of the pages that were using dynamic includes so I found that using an ADODB.Stream object to read the include file eliminated this issue.
So my updated code for the getMappedFileAsString function is as follows
Function getMappedFileAsString(byVal strFilename)
Dim fso
Set fso = CreateObject("ADODB.Stream")
fso.CharSet = "utf-8"
fso.Open
fso.LoadFromFile(Server.MapPath(strFilename))
getMappedFileAsString = fso.ReadText()
'Response.write(getMappedFileAsString)
'Response.End
Set fso = Nothing
End Function

Resources