Jump to content

Yahweh

Members
  • Posts

    186
  • Joined

  • Last visited

Posts posted by Yahweh

  1. Years and years ago I started programming in VB, then I moved to classic ASP, and I'm perfectly fluent in both languages. Only recently I've decided to move on to ASP.Net, because I figure that classic ASP will die and be forgotten in the next few years.So now I feel like a n00b again. I've never touched web controls before, and I don't know what any of the namespaces are, so I'm going to reserve this thread for all of my "please help me, I'm a total n00b" questions about ASP.Net :) If someone wants to answer my questions, presume I have zero experience with ASP.Net; too many of the tutorials I've seen online are not written with beginners in mind, so they can't really help me out at all.First, I want to know how ASP.Net does page cacheing. When I use ASP, I have to jump through hoops to make pages cache correctly (first by creating a FileScriptingObject to see if a page is expired, then creating a BuildPage function to write a page to disk, then Server.Transfer-ing over to the page I've just created). Page cacheing in ASP is no fun at all.When I searched on Google, I came across this tutorial at 4Guys, and it looks like cacheing can be done in just one line of code. However, I have a question about this: are the page caches stored in server memory, or stored on disk?I just noticed most of the tutorials mentioned that the duration of time for page caching is in seconds; but I like to cache my pages for long term storage, sometimes for months at a time, and I can't imagine that its very good to cache pages (especially huge ones) in memory for that amount of time. I prefer to have my caches stored on disk, so that I don't use up all of my system resources.Second, how can I execute regular expressions with ASP.Net.Just recently, I wroted a 400+ character length regular expression in ASP that simulates a recursive function, and it is incredibly slow and runs out of memory very quickly; the same expression can be executed in a few characters using balanced groups in ASP.Net. The .NET regular expressions are much more powerful than anything available in ASP, so I prefer to use them.

  2. Here is my problem. I want to make a forum page, where the people can say whatever they want and however they want to say it. I guess you can say a "blog" page for people that come to my site. I am not sure what code to use. I don't even know where to start for this. I would really appreiciate it if you could help me. Thanks.

    Sounds almost like you're writing a guestbook, which is a pretty good first project if you're new to ASP.It is a prerequisite to know HTML before getting started. Its also a prerequisite that you make sure you have a place to host your website. You can't put your site on Geocities, Tripod, or just any website, you have to find a host that has ASP installed. Generally, the best host for that solution is Brinkster, because they're the most reliable and have the fastest servers.Next, you want to do is create a database. If you're planning to use Brinkster, then you can't use a database more powerful than MS Access. Its fine to use Access if you plan to have less than 10 people viewing your site at any given time. If you wanted to create a website like My Miserable Life, a website that is based on the same concept as yours above, then you need a more robust database like MySQL or SQL Server. You don't get those kinds of databases for free, usually you have to buy webspace, which will cost about US$5 a month.(I'll presume you're using Access from hear on out.)Now, before you can get anything started with your site, you have to design a table. For the kind of website you're proposing, you don't need to make anything complicated. Open MS Access, start with a blank database, save it as "mydb.mdb". When get to the main screen, select the option which says "Create a new table in DESIGN view", and enter the following fields:
    Field          Type              OptionsID             Autonumber        Primary KeyAuthor         Text              Maxlength=20Content        MemoPosted         Date/Time

    Save that table as Guestbook. Its important to be sure that none of your table fields, or you table names have spaces in them.After you've created your table, type a few names, dates, and a few words into each field (make sure when you type the dates, you use a valid date format such as YYYY-MM-DD). That data will be used as test data when we build the page; you can always delete it when your done.At this point, you can start building a website. Here's a sample page, name it default.asp and upload it to your webhost (its important that whatever you name your website has the .asp extension):

    <% Option Explicit %><html><head><title>My site</title></head><body><h1>This is my site</h1><p>Write something!</p><!-- We are going to display the contents of our database here. --></body></html>

    So far, there is nothing that appears on the page, except for the a mysterious "<% Option Explicit %>". The "<%" and "%>" are the ASP delimeters, anything that appears between those two tags will be interpreted by the server and executed. All of your programming code goes between the ASP delimters. For now, the only code that exists is the "Option Explicit" statement, which just tells the server to force variable declaration. If you are trying to use a variable that hasn't been declared, ASP will display an error reading "Undeclared variable at line ###".I'm not sure how much programming experience you have, so I'm going to divert away from the Guestbook program for just a moment and explain the importance of declaring your variables:Usually, people think its a pain to be forced to declare variables, but its actually very important, and it saves time in development. For instance, if you misspell the name of a variable without using Option Explicit, then ASP will treat it as just a new variable; so when you use that unknowingly misspelled variable, you get incorrect results, such as an empty string when you were expecting a name or a word. When this happens, you have to hunt down the misspelled variable, change it, and run your program again; if you have an exceptionally long program, such as something that is 400 or 500 lines long, and perhaps spans over several pages, you could very easily misspell your variable a number of times and be forced to hunt down each instance of a misspelling. And that's no fun at all. Using Option Explicit will do all of that work for you, so get faster development.Now back to your guestbook:We're ready to display some of the data from your database now. This always requires us to create four variables, two them are going to be special variables called Objects.

    <% Option Explicit %><html><head><title>My site</title></head><body><h1>This is my site</h1><p>Write something!</p><%' Use the Dim statement to declare variables'' You can declare several variables with successive Dim statements like this:'   Dim var1'   Dim var2'   Dim var3'   ...'' Or you can declare several variables in one line, seperating each variable with a comma:'   Dim var1, var2, var3''<--- Oh, and these apostrophes create comments in your code. They are a way of'helping you remember what logic you used to create a program, but they the ASP'interpreter will just overlook them.'' Also, when you create a page, the ASP code you've used to write it will be invisible. It' will be converted into HTML.'Dim DSNName    'This is variable that will hold the information to connect to the databaseDim Conn    'This is the "connection" variable, it will use the DSNName variable to            'connect to the database.Dim RS      'This is the recordset variable, it will be used to access the records of the            'database which was created earlier.Dim sql     'This is a variable that will hold SQL statements.'These next three lines set the path to your database. Of course, you'll want to set'the fields to location of you own database. If you are using Brinkster, then you are'required to put the database in the db/ folder (its the only one with read/write'permissions).DSNName = "DRIVER=Microsoft Access Driver (*.mdb);DBQ="DSNName = DSNName & Server.MapPath("db/mydb.mdb")      'The "&" symbol is a way ofDSNName = DSNName & ";PWD=mypass"                      'joining, or contatenating                                               'two strings together.'Now we are going to create our objects:Set Conn = Server.CreateObject("ADODB.Connection")Set RS = Server.CreateObject("ADODB.Recordset")Conn.Open DSNName        'Hopefully, even if you don't know SQL, the following statement will be obvious    'to you. All of the fields after the SELECT keyword correspond to the fields you    'Created in your database, the FROM keyword specifies which table that fields    'correspond to. The ID DESC statement means you are going to put your records    'in descending order; because all of your IDs will numbers (such as 1,2,3,4,5),    'putting them descending order will rearrange the records by ID so that    'the record with the highest ID is at the top and the record with lowest ID is    'at the bottom (such as 5,4,3,2,1). This will correspond to ordering your     'records from Newest to Oldest.    sql = "SELECT ID, Author, Content, Posted FROM Guestbook ORDER BY ID DESC"        RS.Open sql, Conn, 1, 1       'The RS.Open statement puts all of the records from your database into an       'array. It executes the SQL statement above. The "1, 1," at the end of the       'statement tell the database that we'll be opening it in read-only mode,        'without making any further changes to the database.       'Now we just have to loop through all the records we've created. We're going       'to put these records into a two-column table. I'm putting the HTML tags       'outside of the ASP delimeters for the sake of simplicity.       %>       <table width="100%">       <%       Do until rs.eof        'This tells the database to loop through all the                              'records in recordset.           %>           <tr>                <td align="left" valign="top">                    <p>                        <%=RS("Author")%><br>                        <%=RS("Posted")%>                    </p>                </td>                <td align="left" valign="top">                    <%=Replace(RS("Content"), vbNewline, "<br>", 1, -1, vbBinaryCompare)%>                </td>           </tr>           <%           'Those mini-%= statements above are actually equivalent to the ASP           'Response.write statement, which outputs text to the window. In this           'case, they are just writing the fields from the database. The Replace           'statement above transforms all the linebreaks the Content field into           '<br>s, so that they can be interpreted by the browser.           RS.Movenext        'This tells the database to go to the next record.                              'If you omit the RS.Movenext statement, you get an                              'infinite loop. Trust me, you don't like infinite                              'loops.       Loop       %>       </table>       <%    RS.CloseConn.Close'ALWAYS ALWAYS ALWAYS clear the objects you've created from memory by setting them'equal to nothing when you've finished with them.set conn = nothingset rs = nothing%></body></html>

    That's how to display records in a database. Its important realize that *all* of the records from your database will be displayed one page; recordpaging takes a little more work, which would be overwhelming for a newbie.The code above looks intimidating, but in actuality its only 20 lines actual code with my comments taking up the bulk of it; the ASP is actually spaced out quite a bit for simplicity, the same program can be written in about 15 lines.I should also mention a disclaimer: no web developers use the RS(fieldname) method, called recordset iteration, to get contents out of a database, because while it is very simple, its also extremely inefficient (see AspFaq #2467 for an explanation); when I call information from a database, I almost never use Recordset iteration, I use the GetRows() feature to cram all of my information into a 2-dimensional array, then display it. I would have shown you the GetRows() method, but multidimensional arrays are just too much work for your first ASP project.Now, I'm going to show you how to insert records into your database. You need to have an HTML form somewhere on your page, preferably above all of your records. Just use the following HTML:

    <%Option Explicit %><html><head><title>My site</title></head><body><h1>This is my site</h1><p>Write something!</p><form action="post.asp" method="post"><p>Name:<br><input type="Text" name="author"></p><p>Comment:<br><textarea rows="10" cols="50" name="Content"></textarea></p></form><hr>...

    Everything else on the page will stay the same.Now, you are going to create a page called Post.asp, which will insert the contents of form on the previous page into your Guestbook table. The code for this page is actually very simple:

    <% Option ExplicitDim DSNName, Conn, RS, sqlDim strAuthor, strContentstrAuthor = request("Author")     'The request keyword is used to access the                             'querystringstrContent = request("Content")   'data that you send from page to page.DSNName = "DRIVER=Microsoft Access Driver (*.mdb);DBQ="DSNName = DSNName & Server.MapPath("db/mydb.mdb")DSNName = DSNName & ";PWD=mypass"Set Conn = Server.CreateObject("ADODB.Connection")Set RS = Server.CreateObject("ADODB.Recordset")Conn.Open DSNName    sql = "SELECT ID, Author, Content, Posted FROM Guestbook Where 0=1"    'The SQL statement above just opens the table without returning any records.    'We don't need it to return any records, because all we're doing is adding a    'new record.     RS.Open sql, Conn, 3, 3          'The "3, 3" tells the database that we'll be adding a new record to           'database.                    RS.AddNew          RS("Author") = strAuthor          RS("Content") = strContent          RS("Posted") = Now    'The now keyword inserts the date and time          RS.Update     RS.CloseConn.Closeset conn = nothingset rs = nothing'That's all there is to adding new records to the database. Now you have to 'return back to your previous page. You use the Response.redirect statement'to do that:Response.Redirect "default.asp"%>

    Now you're done. You have a guestbook for your site.

  3. Dang, I knew I'd started this thread too soon. I asked the same question in the opening post on a Regex forum, and they were quite helpful:http://regexadvice.com/forums/17123/ShowPost.aspx#17123Its not possible to do recursive regexes, but they can be simulated like this:\[(color)=\s*([^]]+)]((?:\[\1=[^]]+](?:\[\1=[^]]+][\S\s]*?\[/\1]|[\S\s])*?\[/\1]|[\S\s])*?)\[/\1]That will only get 0 to 2 levels of nesting, so I'd have to know in advance how deep nesting can go (I wouldn't imagine I'd need more than 5 or 6 levels). It works nicely :)

  4. I think you've got the speeding correctly, but what about the cache itself? I can't figure out how is the server going to know when to use the server side code and when not, and isn't this kind of check slow by itself?If there is an explainable and proven answer to this (in other words: if my question is stupid), please tell me at least in PM :) .

    Oops, sorry I didn't get to this sooner :)The check for cacheing isn't that slow, as long as you do it right. I write everything in ASP, which has a FileScriptingObject that lets you check when a file was created. I generally use this code:
    Option ExplicitDim CacheTimeCacheTime = 3         'hoursPrivate Sub showPage(ByRef strCache)	dim objFSO, objFile, DoCache	Dim writeNewCache	writeNewCache = True		set objFSO = Server.CreateObject("Scripting.FileSystemObject")	if objFSO.FileExists(Server.MapPath(strCache)) then  if DateDiff("h", objFSO.GetFile(Server.MapPath(strCache)).DateLastModified, Now()) < CacheTime then 	 writeNewCache = False  end if	end if		DoCache = cbool(lcase(request("mode")) = lcase("recalc"))		if writeNewCache = True or DoCache = True then  server.transfer("buildfile.asp") 'I build the file, then write it to disk	end if		'set objFSO = nothing		Server.Transfer(strCache)End SubCall ShowPage("somepage.html")

    Building the file and writing it to disk takes about as long as executing it on every page load, but with the extra 2 or 3 milliseconds of time it takes to build and write the file is acceptable (it has the same affect as setting Response.Buffer = True), because you only have to build it just once per whatever time interval you set, as opposed to building it on each page load.

  5. False alarm folks, I've found a solution to my problem :)I've been working on this problem for a while, and I haven't figured the solution. I've written a script that lets users define their own bbCodes and HTML template, then it transforms the bbCode into HTML.The code works like this:1) A user defines a YCode, specifying the opening tag, and whether it uses arguments or an end tag.2) The data is sent to the BuildPattern function, where it uses the data to construct a regular expression pattern. A sample pattern looks like this:

    \{url=\s*([^\};]+)\s*;?\}([\S\s]*?)\{\/url\}The above expression is obviously the regex for a YCode that looks like this:{url=http://www.google.com}Google Homepage{/url}The part in red captures any arguments used, without capturing any character that is a ";" or "}". Semicolons are used to seperate arguments for tags using multiple arguments. The "\s*" is just a way of capturing only the argument, and not the whitespace surrounding it.The part in blue captures the text between the opening and closing tag.
    3) I perform a quick regex search and replace.I repeat that process a few times to get any tags that have been nested.However, I'm having a problem: the code I've written doesn't work for nested tags. For instance, if I define a tag that makes text a certain color, and for some reason prints the name of the color after the text, I would define a code like this:
    YCode: "color"Arguments: 1EndTag: TrueHTMLTemplate: <font color="$arg">$text</font> ($arg1)

    But when I run that through the regex, it won't work quite right with nested colors.

    {color=red}This is red.    {color=blue}This is blue nested in red.{/color}Now its red again.{/color}It *should* work like this:        First pass through regex:        <font color="red">This is red.            {color=blue}This is blue nested in red.{/color}        Now its red again.</font> (red)                Second pass through regex:        <font color="red">This is red.            <font color="blue">This is blue nested in red.</color> (blue)        Now its red again.</font> (red)Instead, it does this:        One the first pass through regex, that becomes:        <font color="red">This is red.            {color=blue}This is blue nested in red.</font> (red)        Now its red again.{/color}                On the second pass through regex, it becomes:        <font color="red">This is red.            <font color="blue">This is blue nested in red.</font> (red)        Now its red again. </font> (blue)

    Obviously, you can see that the code isn't parsing correctly, because it matches the start tag to its nearest end tag, regardless of wear the end tag is nested, which causes parsing problems. It does that as a consequence of regex pattern, because I use a lazy matching for determing the text between two tags; however, I'm forced to use lazy matching, otherwise I can't put non-nested tags side by side.

    Here's why I can't use greedy matching:{color=red}This is red.    {color=blue}This is blue nested in red.{/color}Now its red again.{/color}{color=orange}This is orange beside red{/color}        First pass through regex:        <font color="red">This is red.            {color=blue}This is blue nested in red.{/color}        Now its red again.{/color}                {color=orange}This is orange beside red</font> (red)                Second pass through regex:        <font color="red">This is red.            <font color="blue">This is blue nested in red.{/color}        Now its red again.</font> (blue)                {color=orange}This is orange beside red</font> (red)        That obviously isn't what I wanted.

    This is the script I've written for YCode parsing (I'm posting it as seperate link because its too long for the board software to handle):http://www.fstdt.com/scripts/ycode/ycode_source.aspA working version of the script above is available at:http://www.fstdt.com/scripts/ycode/ycode_beta.aspI've been working on the nesting problem for the longest time, and I haven't come close to solving it. Would anyone like to give this problem a shot?

  6. I have a website that stores cached copies of webpages on my server, so that I can serve the cached copies of the pages without having to process server-side code again. Normally, I just keep the copies in a folder called /cache like this

    /cache    0000001.html    0000002.html    0000003.html...

    However, I was wondering if it makes a difference if I stored the files in subfolders, where each subfolder contains 100 caches:

    /cache    /000-100        0000001.html        0000002.html        0000003.html        ...    /101-200        0000101.html        0000102.html        0000103.html        ...    /301-400        0000301.html        0000302.html        0000303.html        ...    ...

    I figure, if I had a 1000 (or a million) caches, I could serve them up faster by putting them in folders of about 100 each.The logic behind this idea works like this: if I had 1000 caches in a single folder, then the server has to search through 1000 filenames (at least 1000 operations). If I had them in groups of 100, the server has to pick 1 of the 10 folders (at least 10 operations) then search through 100 filenames (100 more operations). I cut the server load by almost 90%, which is noticeable for extremely popular websites.Is my reasoning correct, or do I completely misunderstand the way servers operate?

  7. I've created menus with subcategories before, but not very efficently. Basically, I want to take a table that looks like this:

    ID      ParentID        Name1       0               Menu12       1               Menu23       1               Menu34       0               Menu45       1               Menu56       4               Menu67       6               Menu78       6               Menu89       0               Menu910      6               Menu10

    And make it output something like this:

    Menu1     Menu2     Menu3     Menu5Menu4     Menu6          Menu7          Menu7          Menu10Menu9

    Is there a painless way to do that without requerying the database a dozen times?

  8. guys.. i have a problem.. i am working on a important/urgent project tat.. requires MI to check if a field in MS access is Numeric... i tried isNumeric() but it didn't work.. any ideas????
    It really helps to see sourcecode, that makes diagnosing the problem much easier. Its not exactly clear if you want to use Access to check for numeric, or if you want to use an SQL statement to check for numeric, or if you want to use ASP to check, so here are all three ways:Using Access: generally, you should stay away from Access database, they can't serve two users simultaneously, and they give a "too many users connected" error when you have more than 10 users on your site at the same time. However, if you really want to use Access, then when setting up a table in design mode, you can tell Access what kind of datatype a field is going to be used for (i.e. whether its going to be a text field, a date/time field, a number field). If you try to insert the wrong data into the field, you'll get an error.Using SQL: I think you can write a statement like "SELECT * FROM some_table WHERE IsNumeric(some_field) = True;", and Access will execute it properly.Using ASP: there a few ways to check whether data is numeric, the easiest way is using IsNumeric(someString), which will return true or false if the string contains any non-numeric characters.You can also use regular expressions, but I wouldn't see why you'd have to if you're not doing anything more complicated than checking for numeric values.
    BTW is this SQL called MySQL?? Thankz~
    MySQL is the name of a type of database, just like MS Access is the name of a database.
  9. The code checks to see that the an ASP script is hosted on a server located at safeURL. If it isn't, the script forces the browser to a display a 301 Relocation page.However, I really doubt that code is really going to be useful to you. If you're problem is just search engines penalizing your site, then you don't even need ASP at all, you can add a robots metatag to the top of your HTML page:

    <meta name="robots" content="noindex,nofollow">

    Otherwise, use a Robots.txt in your /root folder. See this page for a few examples.

  10. anyone knoes how to create a new database in ASP using SQL statements???i sort of like have 44tables to create in the new database...

    The kind of code you want to use depends on the type of database, such as using MySQL, Access, SQL Server, PostGres, etc.See this tutorial for how to create a database from ASP (the steps for creating the SQL server database are basically the same for MySQL, PostGres, and other database types):http://www.aspfaq.com/show.asp?id=2029For the SQL syntax you need to use, see this tutorial:http://www.simple-sw.com/sql-crdb.htm
  11. Interesting,gonna look this one up, but off the top of my head i thought of a labor-some workaround lol.redirect the link to a processing page youve made and stored on a different server than your own.when a user clicks on the link to get the site it came from, they are first redirected to the outside-server page you made, (sending data via form/post) on outside page the data is collected and then they are redirected to the source of the quote.K, off to find a real way to just hide the HTTP ref now, :)Of course with the above method sooner or later theyll just block that http-ref too:)
    I actually figured out how to hide the HTTP referer on my own with this code:
    <% Dim objXmlHttp Dim strHTML Set objXmlHttp = Server.CreateObject("MSXML2.ServerXMLHTTP.4.0") Dim myPage     myPage = Request.ServerVariables("QUERY_STRING")     if myPage = "" then         myPage = "http://www.targetsite.com"     end if With objXMLHTTP     .open "POST", myPage, False     .setRequestHeader "Content-Type", "text/html; charset=ISO-8859-4"     .setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"     .setRequestHeader "Referer", "http://targetsite.com/"     .setRequestHeader "ACCEPT-LANGUAGE", "en-us"     .setRequestHeader "Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*"          .send     While .readyState <> 4         .waitForResponse 1000     Wend     strHTML = .responseText end with Set objXmlHttp = Nothing response.write strHTML%>

    I use that script to pull up pages from their site, then I use a few Replace functions to change selected words in the strHTML string to something funny (it works in the same way as one of those "text to Elmer Fudd" translators).However, my site is still being blocked, I get a 403 error which is accomplished in basically the same way as preventing hotlinking, where the admins of the site have added some kind "don't accept http requests from foreign IPs" command in their .htaccess file. I have not figured out a way to get around that.

    Any idea what the code is they use to pinpoint it came from you?Im not familiar with how they isolate your http ref.

    I access the site in two different ways:- using the translation script above.- providing links to the site.For the second method, the admins have put a javascript on all of their pages to detect HTTP referers, where basically if the referer is fstdt.com or www.fstdt.com then the javascript forwards the client to a 404 page. The site I'm trying to access is Free Conservatives, and the code they use is this:
    <script language="javascript">//Let's create the variable for the arrayvar refarray = new Array();//Now we will add the strings into our arrayrefarray['http://www.fstdt.com'] = "?";refarray['http://fstdt.com'] = "?";//Here we scan our array for the above stringsfor (var i in refarray) {if (document.referrer.indexOf(i) != -1) window.location.replace(refarray[i]);}</script>

    That basically breaks all of the external link from my site to the target site, although targetsite pages can still be accessed by pasting the URLs in a new browser.

  12. What Seph wants is to select the last register, but when you order the last register may be different from the actual one. correct me if i am wrong.

    It could only do that if he orders his list by something other than the unique ID of his users (such as ordering them by name).But if Seph is anything like me, he most likely has a uniqueID assigned to each record that increases by 1 for each record. Then the newest user is the one with the largest ID, and ordering by "ID DESC Limit 1" automatically selects the single record with the largest ID.
  13. I'm certain there is a way to do this, but I haven't found it yet, but I'm looking for a way to hide a user's HTTP referrer if they click on an external link on my site.I want a script like this for these reasons: I own a satire website that quotes silly things that people say on internet messageboards, where quotes are put in the following format:

    "quote"User, [url=source]Message Board[/url]

    I always link to the original message so people can check to see that the quotes are in context. However, one board in particular gets quoted a lot, and they don't really like that my site quotes the silly things some of its members say; so, the admins of the board put a javascript on their site that redirects users to a 404 page if their http referrer has my site.This causes a problem because it breaks all of my links from my site to the particular quoted board, and it forces all my users to jump through all kinds of hoops to view the board (i.e. they have to copy/paste the URL into a new browser window to check quotes at their original source).The only true solution to this problem is to hide my user's HTTP referrer information, but I haven't figured out a way to do this. Any help would be appreciated :)

  14. Full name: Yahweh NodAlternative name(s): Yahweh, YahBirth date(dd/mm/yyyy): ----Gender: MaleZodiacal sign: ScorpioCountry of residance: USCity of residance: Beverly HillsHeight: ----Weight: ----Eyes: GreenHair: I don't know. I really don't.Smoking/Drinking/Drugs: No/No/NoInterest: Books, reading.Additional comments: I build database driven websites for a living, my preferred language is classic ASP for small to medium projects and ASP.Net for larger projects. I've been programming for more than 5 years.Right now, one of my little pet projects is developing a new messageboard system to add to the glut of all the existing ones out there. Anyone who has ever installed a phpBB knows how truly awful those boards are, so I wanted to create one with a little more functionality. I'm writing the software in classic ASP, and I'm basing it off the SPIP blog software, which has a very sophisticated template engine.

  15. I couldn't find a more appropriate place to put this thread, but no worries :)I'm writing a small BBCode engine for my website, and I haven't had any trouble with it until now. I've been trying to figure out how to make regex ignore matches if they contain a certain word. Example:

    Source text:----------[color=red]This color is red[/color][color=white]This bunny is white[/color][color=blue]This is blue[/color][color=green]Bunnies are adorable[/color]Regex:----------\[color=(?:\s{0,})([^\];]+)\]([\S\s]*?)\[\/color\]Results:----------Match                                    $1      $2 [color=red]This color is red[/color]     red     This color is red [color=white]This bunny is white[/color] white   This bunny is white [color=blue]This is blue[/color]         blue    This is blue[color=green]Bunnies are adorable[/color] green  Bunnies are adorable

    However, I want to exclude matches where $2 contains "bunny" or "bunnies" anywhere in the text. Here is the desired input and output:

    Source text:----------[color=red]This color is red[/color][color=white]This bunny is white[/color][color=blue]This is blue[/color][color=green]Bunnies are adorable[/color]Regex:----------***Haven't figured out this step yet***Results:----------Match                                   $1      $2 [color=red]This color is red[/color]     red     This color is red[color=blue]This is blue[/color]         blue     This is blue

    I've been working on this for a while, and it should be incredibly simple but I haven't figured it out yet. What regex code would I need to use to get my desired matches?Note: you can test your regex patterns here:http://regexlib.com/RETester.aspx

  16. I can't see my source code. How come? How to solve it?

    Its a good thing that you can't see your sourcecode (you wouldn't want users to be able to right-click on your .asp page and steal all your source code), because that means you've got your IIS set up correctly. So, most likely the problem doesn't have anything to do with your IIS or your code, but its just that you aren't writing any text to the screen.However, its easier to diagnose problems with code when we can actually read it, so can you post the ASP script that you're trying to test?
  17. I have dozens and dozens of little snippets of ASP code I like to reuse, most of these I came up with by necessity. For instance, how many of us have written a menu and struggled with putting together submenus; and how many of us have written blogs and messageboard systems and struggled with writing custom BBCodes.So, use this thread for the useful little ASP snippets you like.Some of my snippets:Use Request("your_var") for form data sent by method=post and method=get. Example:

    Dim someVarsomeVar = Request("username")

    The code above works no matter how the username variable was sent. I generally don't like to use Request.Form and Request.Querystring because I usually like to send form data by method=post (such as a search page), but then I also like to add hyperlinks to the same pages with querystring (such as "search.asp?username=Yahweh"), so I find I need to get the same data by both get and post methods. So that's why I prefer Request("username"), and it also makes my code a little shorter.Custom BBCode for blogs, guestbooks, or messageboardsA while ago, I wanted to put a messageboard on my website, but rather than re-invent the wheel by writing my own messageboard software, I decided to go with the standard phpBB software. And let me just say, that is some of the ugliest most awful sourcecode I've ever seen in my life. In particular, I wanted to add new BBCodes to my site and change existing ones, but I quickly learned it is impossible; the BBCode engine for that site is more than 800 lines long, and theres no standard way of adding new codes. I was extremely disappointed with the software.So, in a couple of hours, I wrote a BBCode engine in ASP thats only 44 lines long. Not only does it allow you to add new codes on the fly, it also lets you add codes that take 1 or more arguments. And it executes extremely quickly, much faster the phpBB code.A working version of the code is post here:http://www.fstdt.com/scripts/ycode.aspThis forum software on this site formats the source code for my script as BBCode, so I've posted the source code on my site, and its available here:http://www.fstdt.com/scripts/ycode_source.aspThe sourcecode looks longer than it really is, because I have a tendency to write rather verbose comments, and I also included ways to extend the code to accomodate more features. While the source code itself is only 44 lines, all the comments make the code appear to be 215 lines.

  18. I am using what I assume to be pretty straightforward asp, xhtml and scripts (vbscript, javascript) to manage my website. Everything is working OK, including maintaining an MS Access db on the server from form data, and reading and updating folders & files on the server.But I have one more need:The only way I have found, of passing any info back from the client to the server is by using a form - the form displays on the client, the user enters data and submits the form, and the data can then be picked up in ASP, ie, on the server. I can then, for example, write the form data to my MS Access db on the server, and pass it back to the client in whatever form I need it in the html.But I want to be able to pass back (small amounts of) data without using a form. For example, if the user clicks on a certain field (like a cell in a table), I want to resubmit the .asp file (as I would for form data) so that in my asp code I can pick up the fact that the user has clicked field "x" and act accordingly (eg. update a db record and redisplay).I can't find any way of doing this. Some things, like the Session object, appears to be accessible only on the server. Other things, like window.location.search, appear to be accessible only on the client. Such a mechanism must logically exist, because it exists for form data.XMLHttpRequest appears to pass data back to the server, but it is far too complicated for my liking.Any ideas?TIA

    I think using XMLHttpRequest overcomplicates everything, you don't need AJAX for something this simple.The easiest way to do this is putting querystring data in the link you want you're users to click. An example might look like this:Clickrows.asp
    <table><%Dim IFor I = 1 to 10%>    <tr>        <td><a href="update.asp?row=<%=I%>">Row <%=I%></a>    </tr><%Next%></table>

    When a user clicks a link above, they will be forwarded to the URL a page called update.asp, and they'll be sending the querystring "row=1". This works exactly the same as using a form (with method="get") to send the data. Now you can write your update.asp page to change the necessary values in your database:Update.asp

    <%Dim myRowmyRow = request("row")' Open a connection' Update your table' Close connectionresponse.redirect "clickrows.asp"%>

    If you're users don't like the page refreshing everytime they click a link, you can try using AJAX. I recommend this page as an example for updating databases.Edit to add:Oh, looks like I was too slow to type this, glad you got your problem fixed.But I also want to add, you don't really need to use Request.Form or Request.QueryString. If you use Request("your_var"), then you can get the value passed by Your_Var regardless of whether it was passed by method=post or method=get.

  19. I wrote a asp page and I wanted to test it. However, the browser displayed a blank page only.

    Do this:Go to your ASP page, right click and view source. If you can see the sourcecode that you typed, that means the server where your ASP page is sitting doesn't support ASP. The server is just processing the page as regular HTML, not as ASP. The reason why you get a blank page when it processes as HTML is because greaterthan / lessthan signs have a special meaning in HTML, and when you type "<% ... %>" the browser thinks you're trying to write an HTML tag that it can't understand, so it just doesn't format the tag at all (hence you get a blank page).If you're writing the page at home, then you need to have IIS or PWS installed on your computer (note: WinXP Home edition doesn't have IIS or PWS). Otherwise, you can just use a free webhost that supports ASP and test your scripts there, I recommend using Brinkster to get started.Even if you have IIS installed already, I recommend uploading your page to Brinkster and seeing if it works there. You might be able to tell if you have a problem on your home IIS depending on whether or not you get a blank page on Brinkster.If you get a blank page on Brinkster, then the problem with your ASP page is really simple: you're not writing text to the browser. For instance, there is a difference between this code:
    <%Dim I, JFor I = 1 to 10     J = J * INext%>

    And this code:

    <%Dim I, JFor I = 1 to 10    J = J * I    response.write J & "<br>"Next%>

    The first block will just process the ASP but it won't output text, so you get a blank page. The second block outputs text.Make sure that your ASP script you're testing actually outputs something to the browser.

  20. Here's my advice: ween yourself from the habit of using session variables. In fact, add this line of code to the top of your ASP pages:

    <%@ Language="VBScript" enablesessionstate=false %>

    That disables session variables on your ASP page altogether and makes your pages run much much faster.The problem with Session variables is that they only last for as long as a user's session lasts (hence the name), so they typically have a lifetime of about 20 minutes before they expire. Thats what they are designed for. Although Sessions are technically cookies, you can't manipulate them to the same extent as cookies (such as controlling when they expire), sessions are basically a very impotent form of cookies that that really irritate your users immensely by having them log in all the time. There are two general solutions to this problem:1) Start using cookies (and make sure to set their expiration dates, otherwise they're automatically session cookies). Heres a good tutorial on ASP cookies:http://www.aspit.net/tutorials/beginner/co...r_advantage.asp2) Use hidden fields to store a username and password in a form, then everytime the user sends form data you can log them back in automatically if their cookie has expired. I don't recommend doing this with links, because its a security risk.

  21. SQL = "SELECT * FROM TBL_NAMESet RS = Server.CreateObject("ADODB.Recordset")RS.Open SQL, MyConn RS.MOVELAST         'This will take you to the last record of the recordset I guess this is what you are looking for.. HTH

    That's a bad way to select the last registered user, because it causes MySQL to cache all of the records in the database, when it only makes use of a single record.A better SQL statement is:
    Select * From Your_TABLE ORDER BY ID Desc Limit 1

    Basically, this just reverses the order the table and selects one record, its much faster, doesn't require MySQL to cache all the data in the table, and doesn't require an "RS.Movelast" line.

  22. hi i use for each statment to get the values of recored in access db so for example if there are a recored contain 6 fields how can i get 4 fields with for each statment

    Off the top of my head, I imagine this code would work if you already know the 4 fields you want to use:
    'connect to your databaseDim SQL, X, someVarSQL = "Select field1, field2, field3, field4 from Your_Table"Set RS = Server.CreateObject("ADODB.Recordset")RS.open Conn, sql1, 1, 1For each X in RS.Fields     someVar = RS(X)Next

  23. Whats wrong with the Exception Handling,getting the following errorError Type:Microsoft VBScript compilation (0x800A0400)Expected statement/test.asp, line 26End TryThis is the code
    <html><body><% Dim objMessage,objConfig,Flds              Set objMessage = createobject("cdo.message")            Set objConfig = createobject("cdo.configuration")                Set Flds = objConfig.Fields            Flds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2'Flds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "....."            Flds.update            Set objMessage.Configuration = objConfig        Try            objMessage.TextBody = "this is a test mail"            objMessage.To = "......"            objMessage.From = "......"            objMessage.Subject = "Test mail"            objMessage.TextBody = "test mail"            objMessage.fields.update            objMessage.Send  	        Catch            respones.write("error")                           End Try                               'Set objMessage = Nothing            'Set objConfig = Nothing           'Response.Write("success")                     ' response.Write("failure")           %></body></html>

    I have commented the fld.item so that it throws an exception. Thank you.

    There is no Try/Catch in VBScript, but there is one in JScript. Also, you'll generate a syntax error by using respones.write("error") instead of response.write("error"). Generally, when catching errors in ASP, you can use On Error Resume Next and use if err.number then ... end if to troubleshoot after any line which you suspect could cause a proble, or use On Error Goto 0 to stop the error right away.However, if you want to send emails, use this code:
    <% Option Explicit %><html><body><%Dim objCDOSet objCDO = Server.CreateObject("CDONTS.NewMail")objCDO.To = "sender@someone.com"objCDO.From = "reciever@someone.com"Dim txtSubjecttxtSubject = "Your message should go right here." objCDO.Subject = "Your subject should go here."objCDO.Body = txtSubjectobjCDO.SendSet objCDO = nothing%></body></html>

    If you have CDONTS installed, that code will execute without any errors.

  24. ummm, in designing of my home web page I've came to one obstacle. I am hoby programmer, and I started my home web page project. I knew VB6 from past, so with help of w3schools I managed to learn alot of classic ASP.So I was able to build pretty sophisticated framework, which let me add pages to site without applying style to every page, just a single line in each page and I could even change styles (without help of any css  :) ). The problem is I have to use address bar information (Request.QueryString) to properly display page. Example would be http://mypage.com/default.asp?ID=page:somepage. I could call from somepage.asp to default.asp and it would call that file back but I consider that 'clumsy'.Notice that I have designed site in a way that every page consists of 3 parts: title, main body, and menu. The concept of my page is the following: 1. default.asp finds trough cookie selected user’s style and transfers execution to appropriate style asp file along with arguments. 2. The style asp has design which looks like empty page and where the content would be are asp function calls. The style asp also includes 'core' asp where the bodies of functions mentioned before are. So trough these function the somepage.asp, somepageTitle.asp, and somepageMenu.asp are executed. And in the same manner every page builds up.The problem is I would like to use .../somepage.url without that additional 'default.asp?ID=page:nonsense'. I tought CSS would give me that power, so I learned how it works and I nearly started redesigning, but I found one problem. With CSS I can change position, change fonts, backgrounds, but I can't add any text or code to the style. One example would be that I got in mind one secret style which would be parody to that xxx pages (codename red light district). And for that reason I would like to have each time other hostess, other neon displays…, other example would be to have some text completely  out of 'title', 'menu', 'body' …So does anybody know how to redesign my page so I could use 'normal' url and keep having features that gives me my current design?thx for help  :)

    This problem is exactly what ASP Includes are for. Basically, every ASP website ever is constructed in pieces, usually with a header.asp, footer.asp, and maybe a menu.asp in between.Example Header.asp:
    <html><head><title>My Site</title><style>/* some style sheet goes here */</style></head><body>

    Example Footer.asp:

    <p>Some copyright notice here</p></body></html>

    Then, for any single page on your site, you can display it like this, example Cat.asp:

    <%@ Language="VBScript" enablesessionstate=false %><!--#include file="header.asp"-->I like cats, they rock![i]Miscellaneous cat appreciation goes here[/i].<!--#include file="footer.asp"-->

    The page above will execute, putting the code from the other files in the place where the includes are located. (Yes, there can be includes inside other includes.)Now, as for your page, I recommend doing this:1) Seperate your main functions from the rest of your code, put it in a file called global.asp. You can use <!--#include file="global.asp"--> to include those functions in any page.2) Next, if you have several different styles for your site, you can create several different files called style1.asp, style2.asp, style3.asp and so on. Then you this code to call any style:

    <%Dim myStylemyStyle = request.Cookies("MyCookies")("someStyle")         'The cookie should contain the value "style1.asp" or "style2.asp" or whatever the names of your style files are called.Server.execute myStyle%>

    You could probably call the code above inc_style.asp and include it in your header.asp.3) If you are looking to change more than just the CSS, such as chaging where elements on your page are laid out, then this technique works really well:3.1) You'll have to store your page elements in a database, where each element is its own field. So you'll have to create a database and a few tables.In the first table, add the following fields: ID, Author, DateCreated, DateEdited, Article, Title, any other desired fields.In the second table, add the following fields: ID, Template.I recommend using ID in your tables because its easier to reference rows by ID rather than by article or template title.3.2) Your template will be written in a kind of pseudomarkup language, put it will position elements on your page like this:

    <table><tr><td>$AUTHOR</td><td>$DATE</td></tr><tr><td colspan="2"><b>$TITLE</b><p>$Article</td></tr></table>

    (I usually like to use the [element] format, because its a little more human readable.)3.3) For each page, you'll have to use an SQL query to extract the ID, Author, Title, and other information into variables like this:

    <%Author = rs("Author")Title = rs("Title")Article = rs("Article")' You might have to execute another SQL query to retrieve the template from the other tableTemplate = rs("Template")'...etc. ...%>

    3.4) Now that you have all your data, you can start making replacements:

    <%Template = replace(Template, "$AUTHOR", Author, 1, -1, vbTextCompare)Template = replace(Template, "$TITLE", Title, 1, -1, vbTextCompare)Template = replace(Template, "$Article", Article, 1, -1, vbTextCompare)Template = replace(Template, "$DATE", Date, 1, -1, vbTextCompare)'...etc. ...'After all of the replacements are done, just print your Template variableReponse.write Template%>

    The first 2 options are consistent with having normal looking URLs. The third option requires you to use a URL like article.asp?id=10 or something similar, although it technically is possible to have normal looking URLs if you're willing to recycle the same code over and over for each page.

×
×
  • Create New...