"
& _
"
"
& data(0
, I) & "
["
& data(3
,I) & "
| "
& data(2
, I) & "
| "
& data(1
, I) & "
] | "
if
LoggedIn <> "
"
then
response
.write "
"
response
.write "
| "
end
if
Next
"
I
%>
table
>
<%
end
if
If
LoggedIn <> "
"
Then
response
.write logoutlink
else
response
.write loginlink
end
if
"
close db just in case
on
error
resume
next
dConn.Close
Set
dConn = Nothing
on
error
goto 0
%>
That is basically it, this is a very simple little guestbook, that should be
easy to add to an site that supports ASP and MS Access database connections (No
ODBC is necesary).
Recently I was working on my Website, and decided I wanted to implement a guestbook. I started to search the Web to find the best guestbook for my Website, but when none turned up, I thought ‘Hey I’m a developer, why not create my own?’
It was very easy to create a guestbook — you can do it too. In this tutorial, I’ll show you how. I’ll assume that you have already knowledge about the basics of ASP.NET programming, that you know the techniques involved in codebehind, and that you have some XML/XSL skills.
Overview
What do we need in order to create a guestbook? We need two Web forms: one in which the user can enter their name, email address, and comment, and another that’s used to display these comments as they’re signed into the guestbook. Of course we can build this functionality into one Web form, but to have a clean code, I’ll use two Web forms with several codebehind files (I’ll discuss these in more detail in a moment).
We’ll also need a database to hold the information entered via the form. I used a simple XML file (a database) to store the information entered by the user. For the visualisation of the XML we’ll use XSL.
So, in summary, we need the following:
- Two Web forms
- Codebehind
- Database
In a guestbook, it’s usually sufficient to store a user’s name, location, email address, Website address, and comment. Of course, you can store more fields, but for our purposes, these are enough. We’ll store this data in the XML file, which will look something like this:
Sonu Kapoor
Germany
sonu@codefinger.de
www.codefinger.de
This guestbook is written by Sonu Kapoor.
I hope you like it. To learn how to create such a guestbook,
read the whole story on my website.
Signing the Guestbook
We’ll allow the user to ‘sign’ our guestbook by entering some information into a simple Web form — in our example this is the guestbook.aspx file. I use the following fields in the Web form:
- Location
- Email
- Website
- Comment
Here’s the code:
<% @Page Language="C#" Debug="true" Src="Guestbook.cs"
Inherits="Guestbook" %>
To avoid confusing you with unnecessary code, I have removed the visualisation tags — including table, table header etc. — from this example (though, of course, these are all included in the downloadable code that’s provided at the end of this tutorial). As we only display a simple form with a few fields and buttons, you can’t see any real programming code in this file. This is because all the functionality is hidden in the codebehind.
In the first line of the code above, I set the SRC attribute to let the ASP.NET file know that we are using the codebehind file Guestbook.cs I’ve also set the attribute Inherits with the corresponding classname. This attribute lets the file know which class to inherit.
Next, I’ve implemented the required text fields. Remember that if you want to use the same variables in the codebehind, they need to have the same ID in both files, and they must be declared as public.
In the next section of the code, I used the ASP.NET validator controls. These controls check whether the user has entered a value into the text field, without doing a round-trip to the server. The code is executed on the client side.
Finally, I implemented a submit button with an OnClick event called Save_Comment . This event is used to store the information entered into the XML file by the user. The function of this event is available in Guestbook.cs. I also implemented a reset button — and that’s it! Nothing more has to be done to the Web form. Now, if you run the guestbook.aspx, you should see a Web form that looks like this:
Now we know how to display the Web form, but we haven’t seen the code that handles the event in guestbooks.cs. Let’s take a look at that now.
Using System;
using System.Web;
using System.Web.UI;
using System.Xml;
Public class Guestbook: Page
{
// Create the required webcontrols with the same name as
in the guestbook.aspx file
public TextBox name;
public TextBox location;
public TextBox email;
public TextBox website;
public TextBox comment;
Public void Save_Comment(object sender, EventArgs e)
{
// Everything is all right, so let us save the data
into the XML file
SaveXMLData();
// Remove the values of the textboxes
name.Text="";
location.Text="";
website.Text="";
email.Text="";
comment.Text="";
}
}
Private void SaveXMLData()
{
// Load the xml file
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("guestbook.xml"));
//Create a new guest element and add it to the root node
XmlElement parentNode = xmldoc.CreateElement("guest");
xmldoc.DocumentElement.PrependChild(parentNode);
// Create the required nodes
XmlElement nameNode = xmldoc.CreateElement("name");
XmlElement locationNode = xmldoc.CreateElement("location");
XmlElement emailNode = xmldoc.CreateElement("email");
XmlElement websiteNode = xmldoc.CreateElement("website");
XmlElement commentNode = xmldoc.CreateElement("comment");
// retrieve the text
XmlText nameText = xmldoc.CreateTextNode(name.Text);
XmlText locationText = xmldoc.CreateTextNode(location.Text);
XmlText emailText = xmldoc.CreateTextNode(email.Text);
XmlText websiteText = xmldoc.CreateTextNode(website.Text);
XmlText commentText = xmldoc.CreateTextNode(comment.Text);
// append the nodes to the parentNode without the value
parentNode.AppendChild(nameNode);
parentNode.AppendChild(locationNode);
parentNode.AppendChild(emailNode);
parentNode.AppendChild(websiteNode);
parentNode.AppendChild(commentNode);
// save the value of the fields into the nodes
nameNode.AppendChild(nameText);
locationNode.AppendChild(locationText);
emailNode.AppendChild(emailText);
websiteNode.AppendChild(websiteText);
commentNode.AppendChild(commentText);
// Save to the XML file
xmldoc.Save(Server.MapPath("guestbook.xml"));
// Display the user the signed guestbook
Response.Redirect("viewguestbook.aspx");
}
}
Wow! That’s our codebehind file… but what really happens here? You won’t believe it, but the answer is: "not much"!
First, we implement the minimal required namespaces which we need in order to access several important functions. Then I create a new class called Guestbook:
public class Guestbook: Page
Note that it’s this class that’s inherited by the guestbook.aspx file. Then we declare 5 public variables of type textbox. Remember that here, the names have to be identical to those we used when we created the text boxes in guestbook.aspx. Then, as you can see, we use the Save_Comment event, which is fired by the submit button we included in the guestbookpx file. This event is used to save the data.
The Saving Process
The function SaveXMLData() saves the information for us. As we’re using an XML database to store the information, we use the XmlDocument , XmlElement and XmlText classes, which provide all the functions we need.
Next, we create a new XMLDocument class object and load the guestbook.xml file. The required nodes are created with the function CreateElement , and the information entered by the user is retrieved and stored to an object of XmlText . Next, we store the created nodes without any values, using the function AppendChild in conjunction with the main XmlDocument object.
And finally, the values are stored in the nodes we just created, we save all changes to the guestbook.xml file, and we redirect the page to viewguestbook.aspx, where the stored comment is displayed.
Viewing the Guestbook
To view the guestbook, we must created an another Web form:
<% @Page Language="C#" Debug="true" Src="ViewGuestbook.cs"
Inherits="ViewGuestbook" %>
As you see, this Web form doesn’t really do all that much. It simply calls the codebehind file, ViewGuestbook.cs. Let’s take a look at this file.
Using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
Public class ViewGuestbook: Page
{
private void Page_Load(object sender, System.EventArgs e)
{
//Load the XML file
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("guestbook.xml"));
//Load the XSL file
XslTransform xslt = new XslTransform();
xslt.Load(Server.MapPath("guestbook.xsl"));
String xmlQuery="//guestbook";
XmlNodeList nodeList=doc.Document
Element.SelectNodes(xmlQuery);
MemoryStream ms=new MemoryStream();
xslt.Transform(doc, null, ms);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
//Print out the result
Response.Write(sr.ReadToEnd());
}
}
I’ve created this class to display all comments submitted through the guestbook to our users. Again, the first thing we do is implement the required namespaces, and, as we’re using XSL for the visualisation, we have to be sure to include the namespace System.Xml.Xsl .
Then we create a new class called ViewGuestbook , with a private inbuilt function called Page_Load . This function is always called when the page loads, or when the user performs a refresh. Here, the function loads the guestbook.xml file, and then the XslTranform class is used to transform the XML elements into HTML before we load the guestbook.xsl with the help of a XslTransform object.
Next, we create a new object of class XmlNodeList , which will allow us to select the required nodes. We then use the class MemoryStream , available via the namespace System.IO , to create a stream that has memory as a backing store, and use the Transform function to assign the xml data to this memory stream. The Seek function sets the current position to zero.
We then create an object of the class StreamReader , which reads the stream, and print the result with the help of the function ReadToEnd() . This function reads the stream from the current position to the end. If you run viewguestbook.aspx, you should see a Web form like this:
The XSL
As I’ve already mentioned, we use XSL for the transformation of the data from XML to HTML. I’ve assumed that you’re already experienced with XSLT, so I’ll only touch on the important aspects here. I have used an XSL for-each loop to iterate through all the guests in the book, which looks something like this:
And in the loop we call the XSL template name, which looks something like this:
Conclusion
As you see, it’s not very difficult to create a guestbook. Good luck! And don’t forget to .
Как правильно искать с помощью гугла
Все наверное умеют пользоваться такой поисковой системой, как гугл. Но не все знают, что если грамотно составить поисковой запрос с помощью специальных конструкций, то можно достичь результатов того, что Вы ищете намного эффективнее и быстрее. В этой статье я постараюсь показать что и как Вам нужно делать, чтобы искать правильно
Гугл поддерживает несколько расширенных операторов поиска, имеющими специальное значение при поиске на google.com. Типично, эти операторы изменяют поиск, или даже говорят гуглу делать полностью различные типы поиска. Например, конструкция link: является специальным оператором, и запрос link:www.google.com не даст вам нормального поиска, но вместо этого найдет все web-страницы, которые имеют связи к google.com.
альтернативные типы запросов
cache: Если Вы будете включать другие слова в запрос, то Гугл подсветит эти включенные слова в пределах кэшируемого документа.
Например, cache:www.nnm.ru web покажет кэшируемое содержимое с подсвеченным словом "web".
link: рассматриваемый выше поисковой запрос покажет веб-страницы, на которых содержатся ссылки к указанному запросу.
Например: link:www.nnm.ru отобразит все страницы на которых есть ссылка на
related: Отобразит web-страницы, которые являются "подобными" (related) указанной web-странице.
Например,related: www.google.com перечислит web-страницы, которые являются подобными домашней странице Гугл.
info: Информация запроса: предjставит немного информации, которую Гугл имеет о запрашиваемой web-странице.
Например,info:nnm.ru покажет информации о NNM.ru (http://nnm.ru/ - NoNaMe - скачать программы).
Другие информационные запросы
define: Запрос define: обеспечит определение слов, которые Вы вводите после того, как это, собранный из различных сетевых источников. Определение будет для всей введенной фразы (то есть, это будет включать все слова в точный запрос). | правда с этим я сам немного не разобрался как его использоватьsmile.gif Так что кто знает - велкам в коменты
stocks: Если Вы начинаете запрос с stocks: Гугл обработает остальную часть сроков запроса как символы биржевых сводок, и свяжется со страницей, показывающую готовую информацию для этих символов.
Например, stocks: intc yhoo покажет информации о Intel и Yahoo. (Отметьте, что Вы должны напечатать символы последних новостей, не название компании)
Модификаторы Запросов
site: Если Вы включаете site: в ваш запрос, Гугл ограничит результаты теми вебсайтами? которые найдет в данном домене.
Например, без названия site:nnm.ru найдет этот док =) Также можно искать и по отдельным зонам, как таковое ru, org, com, etc (site:com site:ru)
allintitle: Если Вы запускаете запрос с allintitle:, Гугл ограничит результаты со всеми словами запроса в заголовке.
Например, allintitle: google search вернет все страницы гугла по поискуsmile.gif как то images, Blog, etc
intitle: Если Вы включаете intitle: в вашем запросе, Гугл ограничит результаты документами, содержащими то слово в заголовке.
Например, intitle:Бизнес
allinurl: Если Вы запускаете запрос с allinurl:, Гугл ограничит результаты, со всеми словами запроса в URL.
Например, [ u]allinurl: google search вернет документы с google и search в заголовке. Также как вариант можно разделять слова слэшем (/) тогда слова по обе стороны слэша будут искаться в пределах одной страницы: Пример allinurl: foo/bar
inurl: Если Вы включаете inurl: в вашем запросе, Гугл ограничит результаты документами, содержащими то слово в URL.
Например, Animation inurl:doci.nnm.ru
intext: ищет только в тексте страницы указанное слово, игнорируя заглавие и тексты ссылок, и прочее не относящееся к. Есть также и производная этого модификатора -allintext: , т.е. далее все слова в запросе будут искаться только в тексте, что тоже бывает важно, игнорируя часто используемые слова в ссылках
Например, intext:программы
daterange: ищет во временных рамках (daterange:2452389-2452389), даты для времени указываются в Юлианском формате (посмотрите здесь)
Ну и еще всякие интересные примеры запросовsmile.gif
Примеры составления запросов для Google. Для спамеров
inurl:control.guest?a=sign
site:books.dreambook.com “Homepage URL” “Sign my” inurl:sign
site:www.freegb.net Homepage
inurl:sign.asp “Character Count”
“Message:” inurl:sign.cfm “Sender:”
inurl:register.php “User Registration” “Website”
inurl:edu/guestbook “Sign the Guestbook”
inurl:post “Post Comment” “URL”
inurl:/archives/ “Comments:” “Remember info?”
“Script and Guestbook Created by:” “URL:” “Comments:”
inurl:?action=add “phpBook” “URL”
intitle:”Submit New Story”
inurl:www.livejournal.com/users/ mode=reply
inurl greatestjournal.com/ mode=reply
inurl:fastbb.ru/re.pl?
inurl:fastbb.ru /re.pl? “Гостевая книга”
inurl:blogger.com/comment.g?”postID”"anonymous”
inurl:typepad.com/ “Post a comment” “Remember personal info?”
inurl:greatestjournal.com/community/ “Post comment” “addresses of anonymous posters”
“Post comment” “addresses of anonymous posters” -
intitle:”Post comment”
inurl:pirillo.com “Post comment”
inurl:gate.html?”name=Forums” “mode=reply”
inurl:”forum/posting.php?mode=reply”
inurl:”mes.php?”
inurl:”members.html”
inurl:forum/memberlist.php?”
inurl:”members.html”
Использованы материалы сайтов