text to speach recognition
About: Text to speach (where the computer can read out text) has long been availalbe, mainly through the L&H TruVoice Text-To-Speech. More recently, Microsofts agent programs have allowed text to speach in web pages and speach recognition.
Quick info. on programming with Ms Agent in Visual basic:
Right-click on the Toolbox.
Select "Components".
Scroll down the list until you see "Microsoft Agent Control 2.0". Select it and press OK to return to the main window.
Double-click on the "Agent" control in the Toolbox.
In the General | Declarations section of you form, add this code:
Dim Merlin As IAgentCtlCharacter 'This _
"creates" Merlin
Const MERLINPATH = "Merlin.acs" '"Merlin.acs" _
is Merlin's character file.
Next, add the following code to the form's Load event:
Agent1.Characters.Load "Merlin", MERLINPATH '"Loads" _
Merlin.
Set Merlin = Agent1.Characters("Merlin") 'Without _
this code, every time you wanted you make Merlin _
do something, you would have to type _
"Agent1.Characters("Merlin")". With this _
code, you just have to type "Merlin".
To get Merlin to appear, say "Hello", point left and then hide, add this code to the form's Load event:
Merlin.Show 'Makes Merlin apear.
Merlin.Speak "Hello" 'Makes Merlin say "Hello".
Merlin.Play "GestureLeft" 'Makes Merlin point left.
Merlin.Hide 'Makes Merlin hide.
Top 10 Ajax Security Holes and Driving Factors
One of the central ingredients of Web 2.0 applications is Ajax encompassed by JavaScripts. This phase of evolution has transformed the Web into a superplatform. Not surprisingly, this transformation has also given rise to a new breed of worms and viruses such as Yamanner, Samy and Spaceflash. Portals like Google, NetFlix, Yahoo and MySpace have witnessed new vulnerabilities in the last few months. These vulnerabilities can be leveraged by attackers to perform Phishing, Cross-site Scripting (XSS) and Cross-Site Request Forgery (XSRF) exploitation.
There is no inherent security weakness in Ajax but adaptation of this technology vector has changed the Web application development approach and methodology significantly. Data and object serialization was very difficult in the old days when DCOM and CORBA formed the core middleware tier. Ajax can consume XML, HTML, JS Array, JSON, JS Objects and other customized objects using simple GET, POST or SOAP calls; all this without invoking any middleware tier. This integration has brought about a relatively seamless data exchange between an application server and a browser. Information coming from the server is injected into the current DOM context dynamically and the state of the browser’s DOM gets recharged. Before we take a look at security holes let’s examine the key factors that seem to be driving Web 2.0 vulnerabilities.
Multiple scattered end points and hidden calls – One of the major differences between Web 2.0 applications and Web 1.0 is the information access mechanism. A Web 2.0 application has several endpoints for Ajax as compared to its predecessor Web 1.0. Potential Ajax calls are scattered all over the browser page and can be invoked by respective events. Not only does this scattering of Ajax calls make it difficult for developers to handle, but also tends to induce sloppy coding practices given the fact that these calls are hidden and not easily obvious.
Qualys: This free security guide describes the scanning requirements for PCI-DSS and provides a quick-reference requirements matrix for both Merchants and Service Providers of all levels.
Validation confusion – One of the important factors in an application is input and outgoing content validation. Web 2.0 applications use bridges, mashups, feeds, etc. In many cases it is assumed that the “other party” (read server-side or client-side code) has implemented validation and this confusion leads to neither party implementing proper validation control.
Untrusted information sources – Web 2.0 applications fetch information from various untrusted sources such as feeds, blogs, search results. This content is never validated prior to being served to the end browser, leading to cross-site exploitation. It is also possible to load JavaScript in the browser that forces the browser to make cross-domain calls and opens up security holes. This can be lethal and leveraged by virus and worms.
Data serialization – Browsers can invoke an Ajax call and perform data serialization. It can fetch JS array, Objects, Feeds, XML files, HTML blocks and JSON. If any of these serialization blocks can be intercepted and manipulated, the browser can be forced to execute malicious scripts. Data serialization with untrusted information can be a lethal combination for end-user security.
Dynamic script construction & execution – Ajax opens up a backend channel and fetches information from the server and passes it to the DOM. In order to achieve this one of the requirements is the dynamic execution of JavaScripts to update the state of the DOM or the browser’s page memory. This is achieved by calling customized functions or the eval() function. The consequence of not validating content or of making an insecure call can range from a session compromise to the execution of malicious content.
Web 2.0 applications can become vulnerable with one or more lapses mentioned above. If developers have not taken enough precautions in putting in place security controls, then security issues can be opened up on both the server as well as browser ends. Here is a list and brief overview of ten possible security holes.
Qualys: This free security guide describes the scanning requirements for PCI-DSS and provides a quick-reference requirements matrix for both Merchants and Service Providers of all levels.
(1) Malformed JS Object serialization
JavaScript supports Object-Oriented Programming (OOP) techniques. It has many different built-in objects and allows the creation of user objects as well. A new object can be created using new object() or simple inline code as shown next:
message = {
from : "john@example.com",
to : "jerry@victim.com",
subject : "I am fine",
body : "Long message here",
showsubject : function(){document.write(this.subject)}
};
Here is a simple message object that has different fields required for email. This object can be serialized using Ajax and consumed by JavaScript code. The programmer can either assign it to the variable and process it or make eval(). If an attacker sends a malicious “subject” line embedded with script then it makes the reader a victim of cross-site scripting attacks. A JS object can have both data and methods. Improper usage of JS object serialization can open up a security hole that can be exploited by crafty packet injection code.
(2) JSON pair injection
JavaScript Object Notation (JSON) is a simple and effective lightweight data exchange format and one that can contain object, array, hash table, vector and list data structures. JSON is supported by JavaScript, Python, C, C++, C# and Perl languages. Serialization of JSON is a very effective exchange mechanism in Web 2.0 applications. Developers choose JSON over Ajax very frequently and fetch and pass required information to the DOM. Here is a simple JSON object “bookmarks” object with different name-value pair.
{"bookmarks":[{"Link":"www.example.com","Desc":"Interesting link"}]}
It is possible to inject a malicious script in either Link or Desc. If it gets injected into the DOM and executes, it falls into the XSS category. This is another way of serializing malicious content to the end-user.
(3) JS Array poisoning
JS array is another very popular object for serialization. It is easy to port across platforms and is effective in a cross-language framework. Poisoning a JS array spoils the DOM context. A JS array can be exploited with simple cross-site scripting in the browser. Here is a sample JS array:
new Array(“Laptop”, “Thinkpad”, “T60”, “Used”, “900$”, “It is great and I have used it for 2 years”)
This array is passed by an auction site for a used laptop. If this array object is not properly sanitized on the server-side, a user can inject a script in the last field. This injection can compromise the browser and can be exploited by an attack agent.
(4) Manipulated XML stream
An Ajax call consumes XML from various locations. These XML blocks originate from Web services running on SOAP, REST or XML-RPC. These Web services are consumed over proxy bridges from third-parties. If this third-party XML stream is manipulated by an attacker then the attacker can inject malformed content.
The browser consumes this stream from its own little XML parser. This XML parser can be vulnerable to different XML bombs. It is also possible to inject a script in this stream which can again, lead to cross-site scripting (XSS). XML consumption in the browser without proper validation can compromise the end-client.
Qualys: This free security guide describes the scanning requirements for PCI-DSS and provides a quick-reference requirements matrix for both Merchants and Service Providers of all levels.
(5) Script injection in DOM
The first four holes were the result of issues with serialization. Once this serialized stream of object is received in the browser, developers make certain calls to access the DOM. The objective is to “repaint” or “recharge” the DOM with new content. This can be done by calling eval(), a customized function or document.write(). If these calls are made on untrusted information streams, the browser would be vulnerable to a DOM manipulation vulnerability. There are several document.*() calls that can be utilized by attack agents to inject XSS into the DOM context.
For example, consider this line of JavaScript code, Document.write(product-review)
Here, “Product-review” is a variable originating from a third-party blog. What if it contains JavaScript? The answer is obvious. It will get executed in the browser.
(6) Cross-domain access and Callback
Ajax cannot access cross-domains from the browser. One of the browser security features that exists in all flavors of browsers is the blocking of cross-domain access. There are several Web services that provide a callback mechanism for object serialization. Developers can use this callback mechanism to integrate Web services in the browser itself. The callback function name can be passed back so that as soon as the callback object stream is retrieved by the browser it gets executed by the specific function name originally passed from the browser.
This callback puts an extra burden on developers to have in-browser validation. If the incoming object stream is not validated by the browser then developers are putting the end client’s fate at the mercy of cross-domain targets. Intentionally or unintentionally, this cross domain service can inject malicious content into the browser. This cross domain call runs in the current DOM context and so makes the current session vulnerable as well. This entire cross-domain mechanism needs to be looked at very closely before implementation into an application.
(7) RSS & Atom injection
Syndicated feeds, RSS and Atom, are one of the most popular ways of passing site-updated information over the Internet. Several news, blogs, portals, etc. share more than one feed over the Internet. A feed is a standard XML document and can be consumed by any application. Web 2.0 applications integrate syndicated feeds using widgets or in-browser components. These components make Ajax calls to access feeds.
These feeds can be selected by end-users easily. Once selected, these feeds are parsed and injected into the DOM. But if the feed is not properly validated prior to injecting it into the DOM, several security issues can crop up. It is possible to inject a malicious link or JavaScript code into the browser. Once this malicious code injected into the DOM, the game is over. The end result is XSS and session hijacking.
Qualys: This free security guide describes the scanning requirements for PCI-DSS and provides a quick-reference requirements matrix for both Merchants and Service Providers of all levels.
(8) One-click bomb
Web 2.0 applications may not be compromised at the first instance itself, but it is possible to make an event-based injection. A malicious link with “onclick” can be injected with JavaScript. In this case, the browser is sitting on an exploit bomb waiting for the right event from the end-user to trigger the bomb. The exploit succeeds if that particular event is fired by clicking the link or button. This can lead to session hijacking through malicious code.
Once again this security hole is opened up as a result of information processing from untrusted sources without the right kind of validation. To exploit this security hole an event is required to be fired from an end-client. This event may be an innocuous event such as clicking a button or a link but the consequences can be disastrous. A malicious event that is fired may send current session information to the target or execute fancy inline exploit scripts in current browser context.
(9) Flash-based cross domain access
It is possible to make GET and POST requests from JavaScripts within a browser by using a Flash plugin’s Ajax interface. This also enables cross-domain calls to be made from any particular domain. To avoid security concerns, the Flash plugin has implemented policy-based access to other domains. This policy can be configured by placing the file crossdomain.xml at the root of the domain. If this file is left poorly configured – as is quite often the case – it opens up the possibility of cross-domain access. Here is a sample of a poorly configured XML file:
Now, it is possible to make cross-domain calls from within the browser itself. There are a few other security issues concerning this framework as well. Flash-based Rich Internet Applications (RIA) can be vulnerable to a cross-domain access bug over Ajax if deployment is incorrect.
(10) XSRF
Cross-Site Request Forgery is an old attack vector in which a browser can be forced to make HTTP GET or POST requests to cross-domains; requests that may trigger an event in the application logic running on the cross-domain. These can be requests for a change of password or email address. When the browser makes this call it replays the cookie and adopts an identity. This is the key aspect of the request. If an application makes a judgment on the basis of cookies alone, this attack will succeed.
In Web 2.0 applications Ajax talks with backend Web services over XML-RPC, SOAP or REST. It is possible to invoke them over GET and POST. In other words, it is also possible to make cross-site calls to these Web services. Doing so would end up compromising a victim’s profile interfaced with Web services. XSRF is an interesting attack vector and is getting a new dimension in this newly defined endpoints scenario. These endpoints may be for Ajax or Web services but can be invoked by cross-domain requests.
Exploitation of security holes and Countermeasures
Web 2.0 applications have several endpoints; each an entry point for threat modeling. To provide proper security it is imperative to guard each of these entry points. Third-party information must be processed thoroughly prior to sending it to the end-client.
Qualys: This free security guide describes the scanning requirements for PCI-DSS and provides a quick-reference requirements matrix for both Merchants and Service Providers of all levels.
To deal with Ajax serialization issues validation must be placed on incoming streams before they hit the DOM. XML parsing and cross-domain security issues need extra attention and better security controls. Follow the simple thumb rule of not implementing cross-domain information processing into the browser without proper validation. Interestingly, up until now, the use of client-side scripts for input validation was thoroughly discouraged by security professionals because they can be circumvented easily.
Web 2.0 opens up several new holes around browser security. Exploitation of these security holes is difficult but not impossible. Combinations of security issues and driving factors can open up exploitable holes that impact the sizeable Web community, such as those that can be leveraged by attackers, worms and viruses. Identity compromise may be the final outcome.
Conclusion
This article has briefly touched upon a few likely security holes around Ajax. There are a few more lurking around, such as the ones leveraging cross-domain proxies to establish a one-way communication channel or memory variable access in the browser.
Screens: A Screen-Saver Manager
When you come back from lunch or finish a long phone call, you may find your computer's monitor filled with moving lines, bouncing pictures, a scrolling message--even a view from a Web camera thousands of miles away! It's your screen saver, of course, and tapping a key or bumping the mouse will dismiss it. The selected screen saver is activated automatically when a specified number of minutes pass with no keyboard or mouse activity. Screen savers are controlled by the desktop's Display Properties dialog, which is invoked either by right-clicking the desktop and choosing Properties or by launching the Display applet in Control Panel. The Display Properties dialog lets you select your favorite screen saver and preview or invoke its configuration dialog. You can also set the wait period--the number of minutes of inactivity before the screen saver becomes active--and control password protection.
Wouldn't it be nice if you could schedule screen savers by the day of the week or special dates such as holidays, birthdays, or anniversaries? For example, you might want to have the marquee screen saver that comes with Windows display "I hate work" on Monday, "Hump Day" on Wednesday, and "Thank Goodness It's Friday!" on, what else, Friday. Or how about "Happy Birthday" on your birthday or--this could be a lifesaver--Call your wife" on your anniversary? For some, an important reminder at the beginning of January, April, June, and September would be "Pay quarterly taxes to avoid penalty." Maybe you have a special Christmas screen saver you've been waiting to use? It would be nice if the screen saver came up automatically on Christmas Day.
You can change the screen saver with the Control Panel Display dialog, but you have to do it manually, and that takes all the fun out of it. With this issue's utility--Screens--you can preschedule a screen saver for a special event, or for a specific day of the week, and have it become the screen-saver-of-the-day automatically when you turn on the computer. If the current day has no special-event or daily screen saver, Screens can activate a default screen saver or choose one at random. Screens also lets you turn the screen saver on or off with a single click of a button without having to select or deselect the current screen saver.
Screens is a 32-bit utility that runs under Windows 95 or Windows NT 3.51 or higher. The source code for Screens, which was written with Borland's visual programming tool Delphi, is also provided for those interested in seeing how it works.
Using Screens
To install Screens, simply run the INSTALL program. It will install the necessary files in a subdirectory on your hard disk, create an icon for Screens in your shell, and also put a shortcut into your StartUp folder so that Screens can activate the screen-saver-of-the-day each time you start the system.
When you first launch Screens, you'll see a dialog with a list of screen savers down the left-hand side (see Figure 1 ). These are all the screen savers found in your Windows and System directories (the same ones found in the Display Properties list). You can choose a screen saver from this list and preview it or change its configuration settings. The Wait box above the list shows the current screen-saver delay in minutes. Pressing the Apply Now button will select the highlighted screen saver as the system screen saver, and it will also apply any changes you've made to the wait time.
You'll note that there is not a (None) selection in the screen-saver list as there is in the desktop Display Properties dialog. Instead, at the top-left corner of the dialog are ON and OFF buttons for enabling and disabling the screen saver. These buttons provide a quick and easy way to turn the screen saver on or off before running, for example, a backup application. You don't have to choose (None) and then later relocate your favorite screen saver in the list.
The rest of the dialog is occupied by three tabbed pages that let you define screen savers for special events, days of the week, and days for which no screen savers are defined (the default screen saver). To determine the screen saver for the current day, Screens first checks to see if the day matches any of the special-event dates; if a match is found, it uses that date's screen saver. If not, it checks whether a screen saver is defined for the current day of the week. If so, it uses that one. If there's no daily screen saver, it uses the default screen saver. Let's look at those three tabs in more detail.
Special-Events Screen Saver
The grid on this page is initially blank, so your first task is to define the dates for which you want special screen savers. Clicking the Insert Date button brings up the Choose Date dialog (see Figure 2 ). This dialog lets you choose a date in three different ways, each with its own tab: Calendar, Holidays, or Calculated Date.
First, and simplest, you can choose a date from the calendar. If the Annual box is checked, the utility knows that the event will recur every year on the specified date. If the Annual box is blank, the utility knows that the event will occur just once, on the exact date (month, day, and year) you've selected.
The second tab lets you quickly select a number of standard holidays. Some, such as Valentine's Day, always occur on a particular date--in this case February 14. Others, such as Thanksgiving, are defined by month and day of week. Thanksgiving is the fourth Thursday in November, which Screens expresses as Nov-Thu #4. Easter is a special case, as it can occur on a wide range of dates in March or April. When you choose a holiday, the appropriate date code will be inserted in the grid. You can also create user-defined events based on month, day of week, and day-index, where day-index is the month's first, second, third, fourth, or last occurrence of the day of week. (The last instance is represented internally as -1.)
For each special event in the grid, you must define a screen saver. Either drag the screen saver from the list at the left, or highlight it and press the Add SS to Date button. Windows 95 comes with a screen saver called Scrolling Marquee, which scrolls text horizontally across the screen; if you are using the marquee screen saver (identified by the word marquee in its name), you can also enter marquee text for an event. For example, you might define your anniversary as a special event, add the Scrolling Marquee, and define the marquee text as "Don't forget flowers!"
The Remove Date button removes the currently highlighted date from your special-events list. You can also select the date and click Delete. The Erase All Dates button should be used with caution, as it completely empties the list of special events.
Daily Screen Saver
At the top of the Daily Screen Saver tab, you'll find a three-column list. The first column contains the days of the week, the second column holds the screen saver associated with each day, and the third column is labeled Marquee Text. To attach a screen saver to a day of the week, simply drag it from the list at the left to the appropriate row. If you prefer, you can highlight the desired screen saver and then press the Add SS to Day button.
If the selected screen saver's name contains marquee, you can enter in the cell next to the screen saver the text that scrolls across the screen when the screen saver is active. For example, if you want to see "I hate work" on Monday, first place the marquee screen saver in the column next to "Mon" and then edit the text in the Marquee Text column to "I hate work." The Marquee Text column only has meaning when you select a marquee screen saver; it is grayed and inaccessible otherwise.
To change the screen saver for a day of the week, simply drag a new screen saver into place, or highlight the screen-saver cell and click the Add SS to Day button. Other buttons clear the screen saver for the highlighted day and clear all daily screen savers.
Default Screen Saver
If Screens doesn't find a special-event screen saver or daily screen saver, it uses the default screen saver, defined on the Default tab. To select a default screen saver, place its name in the one-row grid at the top of the page, then check the radio button titled Use the default Screen Saver shown here.
If you prefer, you can use the previously selected screen saver as the default by checking the radio button titled Do not change the screen saver. For example, you might want to define a special-event screen saver for the first of each month and use that as the default screen saver on subsequent days in the month. In that case, you'd leave the screen saver unchanged.
Finally, if you like surprises, you can check the box titled Choose a screen saver at random. The list from which this choice is made is updated each time you configure Screens. If you add or remove screen savers from your system, simply run Screens, make any changes you wish, and click the Close button.
Commad Line Parameters
Screens accepts three command line arguments: /C for Choose, /D for Disable, and /E for Enable. So far, we've been looking at Screens' main window, which is what you get if you don't specify any command line arguments. Most days, you won't need to see this configuration dialog--you'll just want Screens to activate the day's screen saver. The command line switch /C invokes this behavior. Since you'll normally want Screens to choose the day's screen saver each time Windows starts, the INSTALL program places a shortcut for the command SCREENS /C in the StartUp folder. If you want to prevent Screens from running at start-up, just move this shortcut to another folder.
Run Screens with the /D parameter to disable the screen saver, just as if you were to click the OFF button in the main window. The /E parameter enables the screen-saver activation, as if you were to click the ON button. You could take advantage of these parameters in a batch file to run a program with no screen-saver interruption:
SCREENS /D
START /W PROGRAM.EXE
SCREENS /E
START /W, in the second line, launches the program and waits for it to terminate before letting the batch file continue execution.
Programming Screens
Manipulating screen savers programmatically is straightforward for the most part, but finding a descriptive name to display in the selection list can be tricky. For 32-bit screen savers, the long filename is the descriptive name, but for 16-bit screen savers the description must be extracted from the executable header. Screens digs deep to give you an understandable list. Defining holidays is another challenge, since many don't occur on specific dates; the contortions required to calculate the date of Easter in particular are amazing. We'll also look at a grab bag of functions for getting and changing information about screen savers.
Screen-Saver Name
Screen savers normally reside in the Windows directory or the System directory; that's where the Display Properties dialog looks for them. So to make its list of screen savers, Screens examines each file in those directories with the extension .SCR. A screen saver's descriptive name is stored differently, depending on whether it's a 16-bit screen saver for Windows 3.x, a 32-bit screen saver for Windows 95, or a 32-bit screen saver for Windows NT. So the first step is to figure out what type of screen saver it is.
Every Windows program (including screen savers) starts with an old-style DOS executable header that Screens defines as the data structure OldExeHdr. Windows requires much more information to load and run a program than OldExeHdr provides, so Microsoft has added the "new executable header" (NewExeHdr, in Screens) and placed a pointer to it in OldExeHdr. (Note that 32-bit Windows defines yet another format--called the portable executable header--but that as we'll see below, Screens doesn't need to read this one. Screens only needs to know if it's there.) The first 2 bytes of NewExeHdr constitute a "signature" that defines whether the header is a new executable ("NE") or a portable executable ("PE").
Screens starts by opening each .SCR file and reading a block of data sized to match the old-style DOS-based executable header (defined as the data structure OldExeHdr). After reading the header, Screens does a sanity check to confirm it's actually an OldExeHdr, by looking at the EXE signature--the very first 2 bytes of the file. This signature is "4D, 5A" in hex; in ASCII it's "MZ," the initials of Mark Zbikowski (one of the three developers of DOS 2.0). The location of NewExeHdr is found at offset 3Ch of OldExeHdr. Screens reads the NewExeHdr signature to see whether it's an NE or PE header.
The Win32 SDK documentation says that the descriptive name for a 32-bit screen saver (the PE signature) is stored as a string resource with a numeric ID of IDS_DESCRIPTION. (The value of IDS_DESCRIPTION is 1.) Windows NT honors this convention, but Windows 95 does not, using instead the screen saver's filename. If Screens detects that it is running under Windows NT, it loads the screen saver into memory using LoadLibraryEx--with the LOAD_LIBRARY_AS_DATAFILE flag--and extracts the IDS_DESCRIPTION resource string. If the string is blank, or if Windows 95 is the operating system, Screens uses the filename for the descriptive name.
For a 16-bit screen saver (with an NE signature), Screens reads NewExeHdr. The descriptive name is stored as the first entry in the nonresident names table, and this table's location is found in NewExeHdr. Screens reads a block of data from the screen-saver file, starting at the nonresident names table's offset. The first byte is the descriptive name's length. The descriptive name for a screen saver is supposed to be prefaced with SCRNSAVE. In practice, this usage is inconsistent--sometimes the prefix is absent, and sometimes it's followed by a colon, or a colon and a space. Screens strips off the prefix (if found) before storing the descriptive name.
Is Today Special?
When you start Screens with the /C parameter, its first task is to determine whether the current date matches any of the special events you've defined. It reads the list of special-event dates from SCREENS.INI and compares each date string with the current date until it either finds a match or reaches the end of the list. The function MatchesToday handles this comparison.
There are four kinds of special events: specific dates, annual dates, calculated dates, and Easter. Here are some examples, showing a string representation of each event type. Note that all four of the example strings match the date April 12, 1998.
"EASTER" (Easter--a special case)
"Apr-Sun #2" (calculated date-- second Sunday in April)
"Apr 12" (annual date--April 12
of any year)
"Apr 12, 1998" (specific date)
First, MatchesToday looks to see if the date string is "EASTER." If so, it calls the function Easter, described below, to get the date of Easter for the current year. If that date matches the current date, the Easter screen saver is selected.
If it's not Easter, MatchesToday checks for a calculated date by looking for the character "#" in the date string's ninth position. If the date string represents a calculated date, MatchesToday converts the current date into a calculated date for comparison.
A calculated date is built from the month name, the day of the week, and the day-index. The first occurrence of a particular day of week in the month has a day-index of 1, the second a day-index of 2, and so on. The last occurrence (which may be either the fourth or fifth occurrence) is represented by a day-index of -1. Note that the fifth occurrence of a particular day in the month is always the last, while the fourth occurrence may be the last.
To calculate the day-index, we subtract 1 from the day of the month, divide the result by 7, discard any remainder, and add 1. For example, December 25, 1997, is a Thursday; subtracting 1 from 25 yields 24; dividing 24 by 7 without remainder gives 3; and adding 1 to 3 yields 4, meaning this is the fourth Thursday in December. Screens never uses a day-index of 5, so if this calculation yields 5, the MatchesToday function automatically changes the index to -1.
As noted above, the fourth occurrence of a given day of the week may also be the last. To determine whether this is the case, MatchesToday adds seven days to the current date and checks whether the result is within the same month. If it is not, MatchesToday creates a new representation of the current date as a calculated date, using a day-index of -1, and checks the representation once more against the date string.
If the date string is neither "EASTER" nor a calculated date, MatchesToday tries to convert the current date into a string with the same format used by Screens for storing specific dates. This format is represented by the string "mmm d, yyyy," where mmm is replaced by the three-letter month abbreviation, d is the day of the month with no leading 0, and yyyy is the four-digit year. If this format precisely matches the passed string, a specific-date match has been found. Otherwise, if the month and day (the portion of this format before the comma) precisely match the passed string, an annual-date match has been found.
The date of Easter varies from year to year, sometimes occurring in March, sometimes in April. To figure out whether a given date is Easter requires some complicated calculations. I searched the Internet for algorithms and found one that does the job. Easter is defined as the first Sunday after the paschal full moon. The paschal full moon is not an actual astronomical event; rather, it is a day identified by an artificial value, which is determined from tables and calculations. It may differ from the date of the true full moon by as much as two days. This calculation-based definition is necessary, because the actual full moon can occur on different calendar days in different parts of the world. The Easter function (which is available for downloading from PC Magazine Online) performs the necessary calculations to determine the paschal full moon, and it returns the date corresponding to the following Sunday.
Screen-Saver Miscellany
Controlling screen savers programmatically requires the use of quite a few specialized API functions, and there are some surprises along the way. We'll hit a few of the high points so you don't have to learn the hard way.
A screen saver has two executable sections in it: a configuration dialog and the actual screen saver. When the screen saver is invoked with /C or -C on the command line or with nothing on the command line, the configuration dialog is invoked. When the command line switch /S or -S is used, the screen saver itself is launched. In Screens, pressing Preview launches the highlighted screen saver with the /S switch, and pressing Settings launches it with the /C switch.
The ShellExecute function can't be used to launch the screen saver, because this function always invokes preview mode, regardless of the command line switch. ShellExecute seems to include some special-case code for screen savers. The solution that I found is simple--Screens calls the screen saver using the antique WinExec function, carried over from Windows 3.x. Another solution would have been to launch the screen saver using the Win32 function CreateProcess, but this seemed unduly complicated.
There are other oddities as well. For example, you'd think Windows 95 would refer to the current screen saver using long filenames. You'd be wrong! The current screen saver is defined by the SCRNSAVE.EXE= entry in the [Boot] section of SYSTEM.INI, and it must be stored using a short filename. Screens uses the handy API function GetShortPathName to convert the selected screen-saver name before storing the file in SYSTEM.INI.
Any time your programs need to get or set system information, chances are good you'll wind up using the Windows API function SystemParametersInfo. Screens uses this function to enable and disable the screen saver, check whether the screen saver is enabled, and get or set the screen-saver time-out delay. SystemParamatersInfo takes four parameters:
uiAction defines the desired action
uiParam varies depending on the action
pvParam varies depending on the action
fWinIni defines how a SET action will be communicated to the system
That last parameter deserves further explanation. When SystemParametersInfo changes one of the system parameters, the change takes place immediately. However, programs that are already running may still be using the old value. Also, if the parameter in question is initialized through WIN.INI, it will be restored to its old value the next time Windows restarts. Two flag values for the fWinIni parameter prevent these two problems. The SPIF_UPDATEINIFILE flag causes SystemParametersInfo to record the parameter change in WIN.INI, if indeed the parameter value is stored there. And the SPIF_SENDWININICHANGE flag causes SystemParametersInfo to broadcast a WM_WININICHANGE message to all top-level windows, giving them the opportunity to obtain and use the new parameter value. Any time Screens calls this function to set new values for system parameters, the utility includes both of these flags.
In most cases, a SystemParametersInfo call that sets a new value will pass the value in
SystemParametersInfo(SPI_SETSCREEN-SAVEACTIVE, 0, nil, SPIF_UPDATEINI-FILE OR SPIF_SENDWININICHANGE);
To reenable screen-saver activity, it uses this call:
SystemParametersInfo(SPI_SETSCREEN-SAVEACTIVE, 1, nil, SPIF_UPDATE-INIFILE OR SPIF_SENDWININICHANGE);
If you're not already familiar with SystemParametersInfo, look it up in the Windows help. You'll be amazed by the number of different parameters it can query and change!
In Closing
Screen savers can be fun. They can be even more fun if a relevant screen saver runs automatically according to a prearranged schedule. Try scheduling a screen-saver message for a far-off event. Screens will pleasantly remind you when the event arrives, long after you've forgotten about the date. Or simply have Screens randomly choose a screen saver for you each day. I hope Screens brings you some fun.
Coding Windows Screen Savers with Delphi
Screen Shuffling with Delphi
1.Screen Shuffling with Delphi
Delphi code that divides the current desktop into blocks and then swaps the blocks. It includes an option that lets you adjust the shuffling speed, and the size of the blocks. Great intro to sliding puzzle game or to screen saver development.
More of this Feature
• Project's CODE
Printer friendly versionPrinter friendly version
Join the Discussion
"Post your views, comments, questions and doubts to this article."
Discuss!
Related Resources
• Graphics programming
• Custom shaped forms
• Zoom - Desktop loupe
• TScreen object
• Changing Screen size
• Screen savers with Delphi
About Poll
This [082801] article is:
Awesome (5)
Great (4)
Ok (3)
Not bad (2)
Poor (1)
Current Results
The Idea
Screen shuffling in actionI'm sure you've seen it. When the program starts it takes a picture of the current desktop, the picture is then "cut" into a number of rectangular pieces (all of the same size). The piece at some random position is "removed". The main code randomly swaps that piece with the one next to it. Only pieces adjacent to the removed one can be moved into it.
Implementation
Start a new Delphi project with a blank form. Set the Name property to be 'Shuffler'. Add an Image (Image1) and a Timer (Timer1) component to a form. Image will hold the (scrambled) picture of the Desktop and Timer will fire the drawing procedure. The Interval property of the Timer component determines how often the swapping takes place (the value of 1000 is equal to one second, 2000 is two seconds).
Several global variables are required by the project. Place the next code above the implementation part of the form unit:
var
//this was added by Delphi
Shuffler: TShuffler;
DesktopBitmap : TBitmap;
gx, gy : Integer;
redRect : TBitmap;
rW, rH : Integer;
const
DELTA = 8; //should be 2^n
• The constant (integer) DELTA value determines in how many pieces (preciselly, rows and columns) the screen shot will be split into. The DELTA number should be 2^n where n is a signed integer number. Bigger DELTA results in smaller pieces. For example if DELTA is 16 and the screen resolution is 1024 x 768 then the screen is divided in 64x48 matrix forming 256 pieces.
• DesktopBitmap bitmap holds the captured image of the current Desktop screen - we get this picture by taking the screen shoot.
• redRect is a bitmap picture that replaces the "removed" piece of the picture. The redRect is created in the form's OnCreate event.
• gx, gy hold the current x and y position (Left, Top) of the redRect inside the scrambled picture.
• rW, rH are width and Height of a rectangular part of the picture. For the 1024x768 and DELTA=16 the rW is 64 and rH is 48.
The project starts in the form's OnCreate event handler:
procedure TShuffler.FormCreate(Sender: TObject);
begin
rW := Screen.Width div DELTA;
rH := Screen.Height div DELTA;
redRect:=TBitmap.Create;
with redRect do begin
Width := rW;
Height := rH;
Canvas.Brush.Color := clRed;
Canvas.Brush.Style := bssolid;
Canvas.Rectangle(0,0,rW,rH);
Canvas.Font.Color := clNavy;
Canvas.Font.Style := Canvas.Font.Style + [fsBold];
Canvas.TextOut(2,2,'About');
Canvas.Font.Style := Canvas.Font.Style - [fsBold];
Canvas.TextOut(2,17,'Delphi');
Canvas.TextOut(2,32,'Programming');
end;
Timer1.Enabled := False;
Image1.Align := alClient;
Visible := False;
BorderStyle := bsNone;
Top := 0;
Left := 0;
Width := Screen.Width;
Height := Screen.Height;
InitScreen;
// SetWindowPos(Handle,HWND_TOPMOST,0,0,0,0,
SWP_NOSIZE + SWP_NOMOVE);
Visible := True;
Timer1.Interval := 10; // smaller := faster
Timer1.Enabled := True; // start calling DrawScreen
end;
First, the rW and rH values are determined by the DELTA value. As explained, if the screen dimension is 800x600 and DELTA is 8 than the screen picture is "divided" into 8x8 matrix thus forming small 100x75 peaces (rW = 100, rH = 75). In Delphi the TScreen object represents the state (resolution, color depth, etc.) of the screen in which an application runs.
Second, the redRect bitmap is created that will be placed inside the picture so that it replaces the "removed" slide. The redRect is simply a red rectangle with a sample (blue) text inside it. You could use some ready made graphics, some logo or something.
Finally, the code sets the form to be wide and tall as the Screen. The (commented) call to the API SetWindowPos could be used to set the form to be always OnTop, non movable and non resizable. The InitScreen procedure is called. Timer Interval is set and the OnTimer event starts executing the DrawScreen procedure.
InitScreen - Screen shot
The InitScreen procedure, called from the form's OnCreate event handler, is used to take a screen shot of the current Desktop screen, set the starting position of the redRect and to draw the grid. The code that draws the grid is optional.
To take a screen shoot of the Desktop the GetDC along GetDesktopWindow are used. The BitBt API function is used to transfer the picture of the Desktop to the DesktopBitmap. GetDC(GetDesktopWindow) retrieves a handle of a display device context for the specified window - the window returned by the GetDesktopWindow call. Finally DesktopBitmap is then assigned to Image1 component. Take a look at Delphi help files for more info.
Initial position of the redRect piece is randomly selected. Trunc(Random * DELTA) returns an integer number between 0 and DELTA. Next, the redRect is drawn on the gx, gy position using the CopyRect function of the Canvas object. Again, if you are unfamiliar with drawing algorithms in Delphi - please consider the help system for more info.
Finally, the grid is drawn by using the MoveTo and LineTo. Grid is optional and is used to better differentiate each peace of the picture.
procedure InitScreen;
var i,j:integer;
begin
//get Desktop bitmap
DesktopBitmap := TBitmap.Create;
with DesktopBitmap do begin
Width := Screen.Width;
Height := Screen.Height;
end;
BitBlt(DesktopBitmap.Canvas.Handle,
0,0,Screen.Width,Screen.Height,
GetDC(GetDesktopWindow),0,0,SrcCopy);
Shuffler.Image1.Picture.Bitmap := DesktopBitmap;
//initial position of the redRect
Randomize;
gx := Trunc(Random * DELTA);
gy := Trunc(Random * DELTA);
Shuffler.Image1.Canvas.CopyRect(
Rect(rW * gx, rH * gy, rW * gx + rW, rH * gy + rH),
redRect.Canvas,
Rect(0,0,rW,rH));
//draw grid
for i:=0 to DELTA-1 do begin
Shuffler.Image1.Canvas.MoveTo(rW * i,0);
Shuffler.Image1.Canvas.LineTo(rW * i,Screen.Height);
Shuffler.Image1.Canvas.MoveTo(0, rH * i);
Shuffler.Image1.Canvas.LineTo(Screen.Width, rH * i);
end;
end;
Draw Screen
The main code is in the DrawScreen procedure. This procedure is called inside the Ontimer event of a Timer component.
procedure DrawScreen;
var
r1,r2:TRect;
Direction:integer;
begin
r1:=Rect(rW * gx , rH * gy,
rW * gx + rW, rH * gy + rH);
Direction := Trunc(Random*4);
case Direction of
0: gx := Abs((gx + 1) MOD DELTA); //right
1: gx := Abs((gx - 1) MOD DELTA); //left
2: gy := Abs((gy + 1) MOD DELTA); //down
3: gy := Abs((gy - 1) MOD DELTA); //up
end; //case
r2 := Rect(rW * gx , rH * gy,
rW * gx + rW, rH * gy + rH);
with Shuffler.Image1.Canvas do begin
CopyRect(r1, Shuffler.Image1.Canvas, r2);
CopyRect(r2, redRect.Canvas, redRect.Canvas.ClipRect);
end;
end;
The code may seam strange but is really simple. Since only pieces adjacent to the redRect one can be swapped with it, there are just 4 possible directions. The r1 rectangle holds the current position of the redRect, r2 points to the rectangle with the peace that will be replaced. The CopyRect is used to transfer the "selected" part on the redRect position and again to draw the redRect on it's new position - thus swapping those two peaces.
It would be much eye-frienldy if the swapping is animated - I'll leave this for yopu to implement.
This is how my 640x480 Desktop looks, after several OnTimer events, with DELTA=4. My Screen is usually 1024x768, but I've changed my display properties to take a better screen shoot. Note that you have to hit ALT+F4 in order to stop the program execution. Here is the Project's CODE.
Screen shuffling in action
Note: If you run this application under Delphi 6 the screen will flicker. In Delphi 6 the csOpaque (in TControlStyle) is only set when the Proportional property is False, Stretch is True and Transparent is False. In Delphi 5 (and <) csOpaque is set if Transparent is False and Stretch is True (or the bitmap you want to display is greater or equal size of the Timage) which make sense.
Conclusion. To shuffle the screen without the flicker effect (in D6) you have to set the Stretch property to TRUE - even when you don't want the bitmap to get stretched (if a graphics is of the equal size to the TImage in which it is displayed - as in our case.)
Final words
You've probably saw something like this as a screen saver. If you would like to make one with this code - go ahead. More info on Screen Saver development can also be found on this site.
For a bit of entertainment - the code is the starting point for the popular slide type puzzle. Those little hand puzzles with tiles numbered 1 to 15 that you must slide into numeric order. All you have to do is to stop the DrawScreen routine after some time to get the puzzled image. The idea of the game is to move the pieces back to reform the picture. In general, add the code that receives user clicks on the shuffled picture. Clicking on a piece next to the redRect should swap that piece with the redRect.
Once you have the game done, you could post it to our Free Source Area.
Of course, if you have any questions or comments on this article please post to the Delphi Programming Forum.
Shell Scripting With PHP
Who says you have to use Perl to shell script? Jayesh definetly doesn't, and in this article he will show you how to shell script with PHP instead!I know that you all want to get rid of Perl Scripts because of their complexity and the fact that Perl is not an easy language to learn. With the introduction of PHP version 4.2, PHP has started supporting a new SAPI (Server Application Programming Interface) called CLI (Command Line Interface). This facility was introduced to help developers create small shell application (scripts) with PHP, meaning that you can kiss Perl goodbye forever!
The CLI SAPI was released for the first time with PHP 4.2.0, but was still experimental back then and had to be explicitly enabled with --enable-cli when running ./configure. With PHP 4.3.0, the CLI SAPI will no longer be experimental and therefore will always be built and installed as the PHP (called php.exe on Windows) binary.
In this tutorial I will show you how to use PHP's CLI feature to interpret shell scripts. I will assume that you have a fair understanding of PHP and that PHP is installed and working properly on your computer. You can have PHP installed on Linux or Windows (the examples in this tutorial are demonstrated with PHP installed under Windows but they should work the same on a Linux machine).
Normally shells are interactive, but not always. This means that the shell accepts commands from you through your keyboard and executes them. But instead of issuing command one by one, we can store this sequence of commands in a text file and tell PHP to execute this text file instead of entering the commands manually. This is known as PHP shell scripting.
PHP shell scripts are just like batch files in MS-DOS, but they have more power than the MS-DOS batch file, thanks to PHP.
Why Write Shell Scripts?
Here are some reasons why you may want to consider writing PHP shell scripts:
Shell script can take input from a user or file and output them on screen
Useful to create your own commands/applications
Don't have to reinvent the wheel
Can be used to automate some day to day tasks, such as backups
Getting Started
Lets start with a small script to display the typical "Hello World" text. Create a text file called world.php. Enter the following code into world.php and save it in your PHP directory:
echo "Hello World";
?>
Open your command prompt change into the folder where PHP is installed and run the following command:
php world.php

If you're surprised to see the output at the command prompt instead of in a web browser, then welcome to the other dimension of PHP! You may have noticed that the following header is also included in the output (PHP does this be default, which also tells you the PHP version):
X-Powered-By: PHP/4.2.3
Content-type: text/html
To suppress this HTTP header, we could run PHP with the following command line parameter:
php -q world.php
Lets look at few of the command line options available with the PHP interpreter:
-q (Quiet mode. Suppress HTTP Header output)
-w (Display source with stripped comments and white space)
-v (Version number)
-c
(With this option one can either specify a directory where to look for php.ini or you can specify a custom INI file directly (which does not need to be named php.ini)
-d (This option allows you to set a custom value for any of the configuration directives allowed in php.ini. The syntax is: -d configuration_directive[=value])
-l (This option checks the syntax in the source file)
-i (This command line option calls phpinfo() and prints out the results)
Using Streams in Scripts
You can redirect the output from any script to a file, just like this:
php world.php > outputfile
For all you Linux fans, you can also redirect the script output to another command by using the | (pipe operator) e.g. : php world.php | sort.
There are three streams available in the PHP CLI, which are:
stdin ('php://stdin')
stdout ('php://stdout')
stderr ('php://stderr')
This following example will display "Hello World" in the output window using the output stream:
$stdout = fopen('php://stdout', 'w');
fwrite($stdout,"Hello World");
fclose($stdout);
?>
This example will demonstrate how to use an input stream. It will accept input from the user and wait until the user presses the enter key and then it will display the text entered:
$stdin = fopen('php://stdin', 'r');
echo "Please Enter your Name :";
$mystr = fgets($stdin,100);
echo "Your Name Is :\n";
echo $mystr;
fclose($stdin);
?>
This following example shows you how to output text to an error stream:
$stderr = fopen('php://stderr', 'w');
fwrite($stderr,"There was an Error");
fclose($stderr);
?>
OK, before we move ahead, there are a few things that you should know. The output to the error stream is always sent to the error device (normally screen) and is not sent to file or another command when redirecting the output. Always make sure you close this stream once you are done with it. Please refer to the PHP manual if you need more information on the fopen, fwrite, fgets and fclose functions.
As you all know, we can use arguments with PHP (remember, world.php was an argument to the PHP interpreter). Similarly, we can use arguments in our scripts too. Curious? Let's take a look...
All of the arguments passed to your script are stored in a zero based global array variable called $argv. There is also another global variable, $argc, which holds number of arguments passed to the script (For all of those coming from a C/C++ background, this should be familiar to you).
One thing you need to remember is that $argc will always be one or more – never zero. This is because the name of the script being interpreted is always the first argument to the PHP interpreter. Here's the code, which will display the total number of arguments passed. It will also will display what those arguments are arguments:
echo "Total argument passed are : $argc \n";
for( $i = 0 ; $i <= $argc -1 ;$i++)
{
echo "Argument $i : $argv[$i] \n";
}
?>
Assuming this code is entered into a file called argument.php, you could test this script by running something like this:
php argument.php arg1 arg2
Here's the output:

Using PHP Script Instead of Perl Scripts
As you must have guessed so far, the PHP executable can run independently from the web server. If you want to run your PHP scripts instead of Perl scripts -- which should be transparent to the system – you need to add a shebang to the top of the PHP script that you want to execute. A shebang looks like this:
#!/usr/bin/php
This will tell the UNIX system that it needs to run the PHP interpreter for the following script, and the good thing is that this line will be ignored when you run the script under a Windows environment, thus you can write PHP scripts that are not operating system specific:
#!/usr/bin/php
// your PHP code
// goes here
?>
Don't forget to add the PHP tags in the script file, otherwise PHP will not interpret it properly. If you want to suppress the PHP headers, use #!/usr/bin/php –q. Similarly you can also use any other PHP arguments that we discussed earlier by specifying them after the shebang.
Configuring Windows to Executing PHP Scripts
If you plan to run PHP scripts from a command line on a Windows machine, then you need to associate the PHP files with the PHP interpreter. To do this, open Windows explorer, click on the tools menu and select folder options. Next, click on the file types tab and select the new button. Type .php into the file extension box and click OK:

You now need to select the PHP entry in the registered file types list box and click on the advanced button. Click new and type "Run" in the action box. In the "Application Used to Perform Actions" box, type C:\PHP\PHP.exe "%1" %* (change the PHP path if its different on your machine, %* is used to send any command line arguments). Click OK, and then OK again and then the close button:
With this step completed, Windows is now configured to run PHP Scripts. To try it out, just double click on any PHP file using Windows Explorer to see it running.
You can also register files with different PHP extensions, such as .php3 and .php4 using the same method mentioned above.
some questions on vbscript codings
How to load vbs functions in qtp
U can directly use the function
ExecuteFile "vbsfunctionname.vbs"
What are the differences between Visual Basic, VBA and VBScript? When would it be appropriate to use one as opposed to another?
Visual Basic is a standalone tool for creating separate
software components such as executable programs, COM
components and ActiveX? Controls. It is useful when
building a specialised solution from scratch. VBA offers
the same powerful tools as Visual Basic in the context of
an existing application and is the best option for
customising software that already meets most needs.
VBScript is a lightweight version of the Visual Basic
language designed specifically for use on web pages. While
VBScript can sometimes be used for simple automation, VBA
is the premier technology designed specifically for
application automation.
What is the equivalent of VBScript?s On Error In Jscript ?
JScript uses the try/catch construct to trap, handle, and
throw exceptions. This is one area where JScript is superior
to VBScript.
When inserting strings into a SQL table in ASP what is the risk and how can you prevent it?
The risk associated if not properly taken care of is
something called as "SQL Injection" attack.
This means you could
say in Username textfield on the html frontend or any
frontend, is possible to type something like the following
to by pass the security mechanism and get access to the
protected area of the site or application.
Type the following in Username or Password or both and
click on login/submit or equivalent button.
' or 'x' = 'x'
What is parametrization ?
It is used to test the application with different data sets.
Different Data sets are stored in DataTable and we
parametrize the test..........
Bug Report
reported by the following persons!
Below you find the latest bug reports and a few resurrected ones.
Multi-Column Ordered List Renumbering
Permalink | Mozilla | 1 comments
Reported on 7 September 2007
If you style an ordered list that contains links with the experimental -moz-column-count the list items of the last columns will be renumbered when a link in that column is clicked.
Test page Workaround is included
Reported by: Brian Sweeney.
Backgrounds show through in invisible tables
Permalink | (Orphaned), Safari | 2 comments
Reported on 6 September 2007
Background colors given to
,
, and
on a table that is supposed to be invisible (visibility: hidden) still show up. Backgrounds given to individual cells or to elements inside cells are not shown (like expected).
Test page Workaround is not included
Reported by: Jeffrey Bush.
Buttons with an image don't align with text ones
Permalink | Mozilla, Opera, Safari | 4 comments
Reported on 5 September 2007
Sometimes you might want to mix text buttons with image buttons and insist on using the button tag. However, Firefox aligns the text buttons lower then the image buttons.
Test page Workaround is not included
Reported by: Laurens van der Klis.
Absolute/Fixed elements align with Adjacent elements
Permalink | Explorer 7 | 1 comments
Reported on 4 September 2007
I have a fixed div that is supposed to reside on the left side of the page and remain static using fixed positioning. There is another div adjacent to it that has a margin property that ensures it remains shifted to the right of my fixed element.
This looks fine in Firefox and Opera, but in IE7 the fixed element seems to 'inherit' somehow the margin of the adjacent element and positions itself relative to it, so that they share the same left margin. Any repositioning of the fixed element is relative to its adjacent node. This also happens if the node is adjacent.
Test page Workaround is not included
Reported by: Randeep.
IE7 Uncle Double Class Selector Bug
Permalink | Explorer 7 | 0 comments
Reported on 3 September 2007
Creating a [.class|*|element] + element selector rule will cause IE7 to apply .class1.class2 element or .class1.class2 > element as though it was also a .class1.class2 + element:first-of-type; assuming the final element getting selected in all the above rules are the same element type.
Test page Workaround is included
Reported by: Mit The Destroyer.
Older entries
See the September 2007 archive and beyond.
Below you find a few resurrected bug reports.
border on tbody incorrectly rendered
Permalink | Safari | 0 comments
Reported on 23 March 2007
Safari incorrectly places a border below the tfoot element. This is fixed in the current nightlies of web kit.
Test page Workaround is not included
Reported by: Marc Pacheco.
Restoring default border for text input elements leaves left border color intact
Permalink | Explorer 5-6 Windows, Explorer 7 | 0 comments
Reported on 7 November 2006
Setting border: 2px inset on a text input element (INPUT.text, INPUT.password, TEXTAREA) to return to its default border after having changed its border style and color leaves the left border's previous color intact.
Test page Workaround is included
Reported by: Jason Brunette.
Hangs up on form element with display:table-cell
Permalink | Safari | 1 comments
Reported on 19 July 2006
Put the code: in a page. Safari will hang and you must force it to quit.
Applying styles dynamically makes no difference.
Test page Workaround is not included
Reported by: Toby Woodwark.
Incorrect clientX/Y for text of disabled INPUT elements in tables
Permalink | Explorer 5-6 Windows, Explorer 7 | 1 comments
Reported on 15 March 2006
The event.clientX/Y values for the text portion of disabled INPUT elements is reported relative to the left/top of the INPUT element and not the viewport if the INPUT element is in a table.
Test page Workaround is not included
Reported by: Jason Brunette.
nested form/table causes extra whitespace
Permalink | Explorer 5-6 Windows, Explorer 7, Safari | 3 comments
Reported on 21 November 2005
When nesting a form wholy inside a cell certain browsers includes extra white space at the end of the form. This would appear to be a bug.
Test page Workaround is not included
Reported by: Jay Soffian.
Types of SQL statements
There are four basic types of SQL statements:
* Data definition language (DDL) statements
* Data manipulation language (DML) statements
* Dynamic SQL statements
* Miscellaneous statements
SQL statements can operate on objects that are created by SQL as well as externally described physical files and single-format logical files, whether they reside in an SQL schema. They do not refer to the IDDU dictionary definition for program-described files. Program-described files appear as a table with only a single column.
Start of change
SQL DDL Statements SQL DML Statements
ALTER SEQUENCE
ALTER TABLE
COMMENT ON
CREATE ALIAS
CREATE DISTINCT TYPE
CREATE FUNCTION
CREATE INDEX
CREATE PROCEDURE
CREATE SCHEMA
CREATE SEQUENCE
CREATE TABLE
CREATE TRIGGER
CREATE VIEW
DECLARE GLOBAL TEMPORARY TABLE
DROP ALIAS
DROP DISTINCT TYPE
DROP FUNCTION
DROP INDEX
DROP PACKAGE
DROP PROCEDURE
DROP SEQUENCE
DROP SCHEMA
DROP TABLE
DROP TRIGGER
DROP VIEW
GRANT DISTINCT TYPE
GRANT FUNCTION
GRANT PACKAGE
GRANT PROCEDURE
GRANT SEQUENCE
GRANT TABLE
LABEL ON
RENAME
REVOKE DISTINCT TYPE
REVOKE FUNCTION
REVOKE PACKAGE
REVOKE PROCEDURE
REVOKE SEQUENCE
REVOKE TABLE
CLOSE
COMMIT
DECLARE CURSOR
DELETE
FETCH
INSERT
LOCK TABLE
OPEN
REFRESH TABLE
RELEASE SAVEPOINT
ROLLBACK
SAVEPOINT
SELECT INTO
SET variable
UPDATE
VALUES INTO
End of change
Dynamic SQL Statements Miscellaneous Statements
DESCRIBE
EXECUTE
EXECUTE IMMEDIATE
PREPARE
BEGIN DECLARE SECTION
CALL
CONNECT
DECLARE PROCEDURE
DECLARE STATEMENT
DECLARE VARIABLE
DESCRIBE TABLE
DISCONNECT
END DECLARE SECTION
FREE LOCATOR
GET DIAGNOSTICS
HOLD LOCATOR
INCLUDE
RELEASE
SET CONNECTION
SET ENCRYPTION PASSWORD
SET OPTION
SET PATH
SET RESULT SETS
SET SCHEMA
SET TRANSACTION
SIGNAL
WHENEVER
SQL DDL statements are described in Data Definition Language (DDL). SQL DML statements are described in Retrieving data using the SELECT statement and Data Manipulation Language. You can find complete descriptions of these statements in the SQL Reference book.
AJAX Fast and Easy
The purpose of this post is to try to explain AJAX the way I understand it. To me, AJAX is not some complicated technology that you need to go out and buy books to learn. Rather, it is simply two or more web pages, and a couple of simple Javascript functions.I have come to hate the term AJAX. It seems every time I mention AJAX, either developers get nervous, or account managers get excited. Neither situation benefits me. Actually, I’ve pretty much stopped using the term at all. Depending on my audience, I’ll make up different terms. Like when I’m talking to Java developers, I’ll say “we need to do a back end call” and that doesn’t freak them out, but telling them we need to do an AJAX call makes them sweat.
Hopefully, if enough people read posts like this, the mystery and glamor will be removed from the term AJAX. So, lets get to the de-mystification.
First, lets dissect the name itself. A.J.A.X.
A = Asynchronous
J = Javascript
A = And
X = XML
Most developers reading this will feel pretty comfortable with the Javascript part. It’s the asynchronous and the XML parts that make most people nervous. They really shouldn’t. I’ll briefly describe each, then we’ll put it all together.
Asynchronous simply means “lets open another URL without changing or reloading the page.” Picture it like this… You are reading a blog post, and you come across a link to another page. You don’t want to stop reading, so you right click the link and open it in a new window or another tab right? Now you continue reading the page you were on. Asynchronous simply means we are doing something else without disturbing the page we are viewing.
Javascript, we all know what that is I hope. If you don’t, then you should probably be reading some other sites first (intro to Javascript). Now, the purpose of this post is to make AJAX easy to write, and easy to understand, so we are going to use Javascript tools that make our job a lot easier. Whenever I write AJAX code, I always use the Prototype Javascript framework. Go ahead and download it, we’ll talk more about it later, just know that it has most of the Javascript we will need built in.
Before I get into XML, and what it is, I would like to note that AJAX doesn’t even need XML to work. For those who can’t or won’t use XML, don’t worry, you can still write useful AJAX code without it, but please continue reading and maybe you will decide that you can use XML after all. It does make AJAX a lot easier, but like I said, it’s not necessary.
XML shouldn’t be scary, but many people just don’t know what it is. If you’ve got this far and you aren’t totally confused, then you probably know how to write HTML. HTML and XML should not necessarily be compared, but they are similar in how they are written. XML is written using ‘tags’ similar to HTML. And XML tags need to be “balanced” just like HTML should be. Following is some simple HTML:
< h tml >
< he ad >
< tit le >sample< / title >
< / head >
< body >
< div >something< /div >
< / body >
< / ht ml >
Most people will recognize this as the most basic of HTML code, but what you may not know is that this could also be valid XML code as well. I mentioned the word “balanced” earlier. In the sample above, you will notice that each tag has a corresponding ending tag like < h tml>. That is what balanced means. That is probably the most important concept in XML. Unlike HTML, we don’t necessarily use XML for presentation, XML is normally used more like a database. For example, if the code above were an XML file, and we wanted to think of it as data, we could say that the < htm l> section could be the database itself, the < h e ad > section could represent a table in that database, the
section could represent a column in that table and the word “sample” would be the value of that column. If it were a database, we could query it something like this…
select title
from html.head
We could spend a great deal of time explaining XML, but lets just says that its basic function is to store data and to define what that data means. So, in the example above, the word “sample” means, and we know this because of the XML tags we use to surround it, it is the ‘title’ of the ‘head’ of the ‘html’ file.
I’ll write one more sample XML just for clarification because I think I’ve spent too much time on this subject already, but I think one more sample will be helpful in describing just how easy XML is. Lets say we want to get a list of books. We could represent that list of books with XML.
The Shining
Stephen King
0743437497
Fahrenheit 451
Ray Bradbury
9506440298
From that example, XML should be pretty self explanatory. And that is the real point of XML.
That concludes “AJAX Fast and Easy – part one”. In part two, we will build a basic HTML file and make an AJAX call to another basic HTML file, leaving the XML part out of the equation.
XML-binary Optimized Packaging
This specification defines the XML-binary Optimized Packaging (XOP) convention, a means of more efficiently serializing XML Infosets (see [XMLInfoSet]) that have certain types of content.
A XOP package is created by placing a serialization of the XML Infoset inside of an extensible packaging format (such a MIME Multipart/Related, see [RFC 2387]). Then, selected portions of its content that are base64-encoded binary data are extracted and re-encoded (i.e., the data is decoded from base64) and placed into the package. The locations of those selected portions are marked in the XML with a special element that links to the packaged data using URIs.

In a number of important XOP applications, binary data need never be encoded in base64 form. If the data to be included is already available as a binary octet stream, then either an application or other software acting on its behalf can directly copy that data into a XOP package, at the same time preparing suitable linking elements for use in the root part; when parsing a XOP package, the binary data can be made available directly to applications, or, if appropriate, the base64 binary character representation can be computed from the binary data.
However, at the conceptual level, this binary data can be thought of as being base64-encoded in the XML Document. As this conceptual form might be needed during some processing of the XML Document (e.g., for signing the XML document), it is necessary to have a one to one correspondence between XML Infosets and XOP Packages. Therefore, the conceptual representation of such binary data is as if it were base64-encoded, using the canonical lexical form of XML Schema base64Binary datatype (see [XML Schema Part 2: Datatypes Second Edition] 3.2.16 base64Binary). In the reverse direction, XOP is capable of optimizing only base64-encoded Infoset data that is in the canonical lexical form.
Only element content can be optimized; attributes, non-base64-compatible character data, and data not in the canonical representation of the base64Binary datatype cannot be successfully optimized by XOP.
The remainder of this specification is organized in the following fashion:
*
Section 2 describes the XOP Infoset, which preserves the non-optimized content and structure of the original XML Infoset.
*
Section 3 specifies the XOP processing model.
*
Section 4 of this specification describes the form of the XOP Package.
*
Section 5 describes how XOP Documents are identified.
*
Section 6 explores the security considerations of using the XOP convention.
1.1 Terminology
This specification uses terminology from the XML Infoset (see [XMLInfoSet]) when discussing XML content and structure. This is only a convention for clear specification of XOP behavior.
The following terms are used in this specification:
* Original XML Infoset - An XML Infoset to be optimized.
* Optimized Content - Content which has been removed from the XML Infoset.
* XOP Infoset - The Original Infoset with any Optimized Content removed and replaced by xop:Include element information items.
* XOP Document - A serialization of the XOP Infoset using any W3C recommendation-level version of XML.
* XOP Package - A package containing the XOP Document and any Optimized Content. As a whole, the XOP Package is an alternate serialization of the Original Infoset.
* Reconstituted XML Infoset - An XML Infoset that has been constructed from the parts of a XOP Package.
Architecture of the XOP framework
1.2 Example
Example 1 shows an XML Infoset prior to XOP processing. Example 2 shows the same Infoset, serialized using the XOP format in a MIME Multipart/Related package. The base64-encoded content of the m:photo and m:sig elements have been replaced by a xop:Include element, while the binary octets have been serialized in separate MIME parts. Note that those examples use [Assigning Media Types to Binary Data in XML] to identify the media type of the content of the m:photo and m:sig elements. Note also that the sample base64 data is smaller than would be typical and the binary octets are not shown; in practice, the optimized form is likely to be much smaller than the original.
Example: XML Infoset prior to XOP processing (Example 1, SOAP)
xmlns:soap='http://www.w3.org/2003/05/soap-envelope'
xmlns:xmlmime='http://www.w3.org/2004/11/xmlmime'>
xmlmime:contentType='image/png'>/aWKKapGGyQ=
xmlmime:contentType='application/pkcs7-signature'>Faa7vROi2VQ=
Example: XML Infoset serialized as a XOP package (Example 2, SOAP)
MIME-Version: 1.0
Content-Type: Multipart/Related;boundary=MIME_boundary;
type="application/xop+xml";
start="
";
startinfo="application/soap+xml; action=\"ProcessData\""
Content-Description: A SOAP message with my pic and sig in it
--MIME_boundary
Content-Type: application/xop+xml;
charset=UTF-8;
type="application/soap+xml; action=\"ProcessData\""
Content-Transfer-Encoding: 8bit
Content-ID:
xmlns:soap='http://www.w3.org/2003/05/soap-envelope'
xmlns:xmlmime='http://www.w3.org/2004/11/xmlmime'>
xmlmime:contentType='image/png'> xmlns:xop='http://www.w3.org/2004/08/xop/include'
href='cid:http://example.org/me.png'/>
xmlmime:contentType='application/pkcs7-signature'> xmlns:xop='http://www.w3.org/2004/08/xop/include'
href='cid:http://example.org/my.hsh'/>
--MIME_boundary
Content-Type: image/png
Content-Transfer-Encoding: binary
Content-ID:
// binary octets for png
--MIME_boundary
Content-Type: application/pkcs7-signature
Content-Transfer-Encoding: binary
Content-ID:
// binary octets for signature
--MIME_boundary--
Example 3 shows an XML Infoset prior to XOP processing. Example 4 shows the same Infoset, serialized using the XOP format in a MIME Multipart/Related package. The base64-encoded content of the m:photo and m:sig elements have been replaced by a xop:Include element, while the binary octets have been serialized in separate MIME parts. Note also that the sample base64 data is smaller than would be typical and the binary octets are not shown; in practice, the optimized form is likely to be much smaller than the original.
Example: XML Infoset prior to XOP processing (Example 3, non-SOAP)
/aWKKapGGyQ=
Faa7vROi2VQ=
Example: XML Infoset serialized as a XOP package (Example 4, non-SOAP)
MIME-Version: 1.0
Content-Type: Multipart/Related;boundary=MIME_boundary;
type="application/xop+xml";
start="";
start-info="text/xml"
Content-Description: An XML document with my pic and sig in it
--MIME_boundary
Content-Type: application/xop+xml;
charset=UTF-8;
type="text/xml"
Content-Transfer-Encoding: 8bit
Content-ID:
xmlns:xop='http://www.w3.org/2004/08/xop/include'
href='cid:http://example.org/me.png'/>
xmlns:xop='http://www.w3.org/2004/08/xop/include'
href='cid:http://example.org/my.hsh'/>
--MIME_boundary
Content-Type: image/png
Content-Transfer-Encoding: binary
Content-ID:
// binary octets for png
--MIME_boundary
Content-Type: application/pkcs7-signature
Content-Transfer-Encoding: binary
Content-ID:
// binary octets for signature
--MIME_boundary--
1.3 Notational Conventions
The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 [RFC 2119].
This specification uses a number of namespace prefixes throughout; they are listed below. Note that the choice of any namespace prefix is arbitrary and not semantically significant.
Prefixes and Namespaces used in this specification.Prefix Namespace
Notes
xop "http://www.w3.org/2004/08/xop/include"
A non-normative XML Schema [XML Schema Part 1: Structures Second Edition], [XML Schema Part 2: Datatypes Second Edition] document for the "http://www.w3.org/2004/08/xop/include" namespace can be found at http://www.w3.org/2004/08/xop/include. Note that XML Schema > currently provides only for validation of XML 1.0 Infosets; accordingly, > the schema may not be usable > with XOP Infosets corresponding to later versions of XML.
xmlmime "http://www.w3.org/2004/11/xmlmime"
The namespace for the content type attribute.
soap "http://www.w3.org/2003/05/soap-envelope"
The SOAP 1.2 namespace[SOAP12].
xs "http://www.w3.org/2001/XMLSchema"
The namespace of XML Schema data types [XML Schema Part 2: Datatypes Second Edition].
Editorial note: HR
Note that the "http://www.w3.org/2004/11/xmlmime" URI is not final and will be changed to track the evolution of the "Assigning Media Types to Binary Data in XML" document.
Gate Methodology
Everyone has heard the horror stories of cost overruns on SAP programmes. While there are a few factors which are outside the control of the programme managers (e.g. business change, funding withdrawn) the majority of the responsibility lies at their door.
From the programme managers viewpoint it is essential to get early warning that things are starting to slip. One of the quickest way to lose your job is to surprise your board 4 weeks from go-live with the message that the programme is 6 months late.
One of the best ways to get this early warning is through implementing a gate methodology which forces a structured review of the programme at pre-defined checkpoints along the way. In essence you build gates at the exit points of the major phases of the programme. Naturally these are also the entrance points to the next major phase.
Let's assume that you have five major phases as follows: Scope & Plan, Design, Build, Test, Go-Live. You would then have five major gates as well - each positioned at the exit point of the five phases: Gate 1 - Exit Scope & Plan, Gate 2 - Exit Design, Gate 3 - Exit Build, Gate 4 - Exit Test and Gate 5 - Go-Live. Potential criteria for each of these gates could be as follows:
Gate 1 - Exit Scope & Plan
Is there a scope document, and does it cover all aspects of scope including functionality requirements, modules to be implemented, geography, gaps, interfaces, organisational aspects, technical aspects, data conversion etc
Is there a plan, and does it include detailed tasks (nothing longer than two weeks), with resource names mapped to tasks, and is it resource balanced (no simple task)
Is the design team mobilised
Is there a design authority in place, and is the change control process agreed
Is the sandbox SAP system ready, and is there a client strategy document agreed
Gate 2 - Exit Design
Has the design been documented, including SAP transactions identified, and signed off by the business. A design walkthrough is strongly recommended.
Have critical areas of the design (depending on your business) been prototyped in the sandbox
Have all gaps and interfaces been identified, specified and estimated
Has the data required been identified and mapped to legacy (ignore this at your peril), and have the data conversion programmes been identified and specified at a high level
Have the roles required been identified
Have control requirements been identified
Has the plan been updated, and (if necessary) the scope document updated
Gate 3 - Exit Build
Has the system been fully built and unit tested in the development system (not the sandbox), and signed off by the business. A config walkthrough is strongly recommended.
Have the gaps and interfaces been fully built and unit tested (this is a grey area)
Have the data conversion programmes been built and unit tested (this is not a grey area)
Has the system gone through any scenario-based validation (a step up from unit testing). It is probably best to include this in the Design phase since you cannot be fully satisfied your requirements have been met until you run business scenarios through the system.
Has the configuration been fully documented, and the design documentation updated (if necessary)
Have the roles been built
Have the control requirements been built
Has the plan been updated, and (if necessary) the scope document updated
Gate 4 - Exit Test
Has the system been fully tested in the test system (not the development system), and signed off by the business. A test walkthrough is strongly recommended.
Have the gaps, interfaces and data conversion programmes been fully tested and signed off
Have the user procedures been documented and tested
Has the training material been completed and tested
Has the system been tested by running converted data through it (warning: expect to do this four or five times before it works properly)
Have all critical test problems been resolved.
Gate 5 - Go-Live (done a few days prior to go-live)
Have the users been trained
Are the user procedures in place
Is the user documentation in place
Did the data conversion work
Is the support team in place
Is your 'cutover control room' ready, manned 24 hrs, and have detailed cutover plans in place (this might have started already for the data conversion)
Have you done a trial cutover
Do you have a contingency plan
Everyone feeling well rested? Then push the button!
For the programme to actually exit the gate, you hold a gate meeting at which each team is required to demonstrate (not only verbally claim) why the feel that they have satisfied all the criteria. Pre-gate meetings will probably be required about 4 weeks out to help the teams finalise their positions. usually, but not always, post-gate meetings are required where teams resolve any issues which arose during the gate meeting itself.
Properly implemented and executed, a gate methodology provides and excellent early warning system and should be looked at by every project.
Basic Knowledge and System Navigation Question
What SPRO stands for?
SPRO stands for SAP Project Reference Object
.
It is used to configure the setting as per your client requirement by using the standard setting present in the system. This where you can do all the SAP configuration work. It is also known as the Configuration Menu.
What is full form IMG and SPRO? How are they different from each other?
IMG :- Implementation Guide.
SPRO :- SAP Project Reference Object.
SPRO------>IMG.
Type in the T-Code SPRO under That got to Main Menu which is IMG.
SPRO is basically used to organize the consultant customizing during the SAP Project Phrase.
How to close a window?
If we want to stop a transaction in the middle, Right click on the end button (X) on the top right corner of the window. Then select "stop transaction".
As we dont have STOP icon as we have in WINDOWS, this will help in the same way.
Its a very small tip, but will help a lot.
Tips by : Bhaskar
Name two ways to start a transaction.
- Dynamic Menu
- Command Field
Why do you create user-specific parameters?
They supply defaults to R/3 fields. If a field is indicated, the system automatically fills in default value. Depending on the field definition, the entry can also be replaced with a value entered by the user. (Concept of PARAMETER ID)
Name the three different kinds of messages in the R/3 system. What is the difference between them?
A message can have five different types. These message types have the following effects during list processing:
A (=Abend):
The system displays a message of this message type in a dialog window. After the user confirms the message using ENTER, the system terminates the entire transaction (for example SE38).
E (=Error) or W (=Warning):
The system displays a message of this message type in the status line. After the user chooses ENTER, the system acts as follows:
While creating the basic list, the system terminates the report.
While creating a secondary list, the system terminates the corresponding processing block and keeps displaying the previous list level.
I (=Information):
The system displays a message of this message type in a dialog window. After the user chooses ENTER , the system resumes processing at the current program position.
S (=Success):
The system displays a message of this message type on the output screen in the status line of the currently created list.
What is a data dictionary or repository?
Central catalog that contains the descriptions of an organization's data and provides information about the relationships between the data and its use in programs and screens.
The data descriptions in a Data Dictionary is also called metadata, i.e., data that describes other data.
The ABAP/4 Dictionary stores system-wide data definitions. When you create a new data definition, the Dictionary tool does all the processing necessary to create the definition. You can use the Dictionary tool to look up the "definition" of objects in your R/3 System.
What is a matchcode?
Comparsion key. A matchcode allows you to locate the key of a particular database record (e.g. account number) by entering any field value contained in the record. The system then displays a list of records matching the specifications.
If you want an end user to see a specific menu after logging on the R/3 system, how could you do that?
User maintenance transactions allow the system administrator to create and maintain user master records. This includes the generation and assignment of authorizations and authorization profiles.
D Programming Language
The first D Programming Language Conference took place in Seattle at Amazon, Aug 23..24, 2007.
D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python. Special attention is given to the needs of quality assurance, documentation, management, portability and reliability.
The D language is statically typed and compiles directly to machine code. It's multiparadigm, supporting many programming styles: imperative, object oriented, and metaprogramming. It's a member of the C syntax family, and its appearance is very similar to that of C++. For a quick comparison of the features, see this comparison of D with C, C++, C# and Java.
It is not governed by a corporate agenda or any overarching theory of programming. The needs and contributions of the D programming community form the direction it goes.
There are currently two implementations, the Digital Mars DMD package for Win32 and x86 Linux, and the GCC D Compiler package for several platforms, including Windows and Mac OS X.
A large and growing collection of D source code and projects are at dsource. More links to innumerable D wikis, libraries, tools, media articles, etc. are at dlinks.
This document is available as a pdf, as well as in Japanese and Portugese translations. A Japanese book D Language Perfect Guide is available.
This is an example D program illustrating some of the capabilities:
#!/usr/bin/dmd -run
/* sh style script syntax is supported */
/* Hello World in D
To compile:
dmd hello.d
or to optimize:
dmd -O -inline -release hello.d
*/
import std.stdio;
void main(string[] args)
{
writefln("Hello World, Reloaded");
// auto type inference and built-in foreach
foreach (argc, argv; args)
{
// Object Oriented Programming
auto cl = new CmdLin(argc, argv);
// Improved typesafe printf
writefln(cl.argnum, cl.suffix, " arg: %s", cl.argv);
// Automatic or explicit memory management
delete cl;
}
// Nested structs and classes
struct specs
{
// all members automatically initialized
int count, allocated;
}
// Nested functions can refer to outer
// variables like args
specs argspecs()
{
specs* s = new specs;
// no need for '->'
s.count = args.length; // get length of array with .length
s.allocated = typeof(args).sizeof; // built-in native type properties
foreach (argv; args)
s.allocated += argv.length * typeof(argv[0]).sizeof;
return *s;
}
// built-in string and common string operations
writefln("argc = %d, " ~ "allocated = %d",
argspecs().count, argspecs().allocated);
}
class CmdLin
{
private int _argc;
private string _argv;
public:
this(int argc, string argv) // constructor
{
_argc = argc;
_argv = argv;
}
int argnum()
{
return _argc + 1;
}
string argv()
{
return _argv;
}
string suffix()
{
string suffix = "th";
switch (_argc)
{
case 0:
suffix = "st";
break;
case 1:
suffix = "nd";
break;
case 2:
suffix = "rd";
break;
default:
break;
}
return suffix;
}
}
Note: all D users agree that by downloading and using D, or reading the D specs, they will explicitly identify any claims to intellectual property rights with a copyright or patent notice in any posted or emailed feedback sent to Digital Mars.
Common .NET Naming Conventions
These are the industry-accepted standard naming conventions for J#, C# and VB.NET programs. For additional information, please see the MSDN help documentation and FX Cop. While individual naming conventions at organizations may vary (Microsoft only suggests conventions for public and protected items), the list below is quickly becoming the de-facto standard in the industry. Please note the absence of Hungarian Notation except in visual controls. These naming standards should find their way into all of your .NET development, including ASP.NET Web applications and .NET Windows Forms applications.
Note that while this document predates the online and printed standards documentation from Microsoft, everything below which indicates it is based on .NET library standards is consistent with that documentation. In areas where Microsoft has not provided guidance (Microsoft generally doesn't care what you do in private/non-exposed code. In fact, they aren't even consistant in their internal code in the .NET framework), de facto standards have emerged, and I have captured them here.
The "ux" naming convention for controls is something I have added and found to be helpful. It is not based on any official standards, but instead based upon a multitude of projects by my teams and others, as well as on-line discussions on the topic. While I strongly recommend that you follow Microsoft guidelines when present, I encourage you to try out the items marked as extensions below and see how they work for you before committing to them.
Type Standard / Convention Example
Namespaces Standard Based Upon Microsoft .NET Library Standards
Pascal Case, no underscores. Use CompanyName.TechnologyName as root. If you don't have a company, use your domain name or your own initials. Note that any acronyms of three or more letters should be pascal case (Xml instead of XML) instead of all caps.
Why: This convention is consistent with the .NET Framework and is easy to read.
AppliedIS.TimeCard.BusinessRules
IrritatedVowel.Controllers
PeteBrown.DotNetTraining.InheritanceDemo PeteBrown.DotNetTraining.Xml
Assemblies Standard Based Upon Microsoft .NET Library Standards
If the assembly contains a single name space, or has an entire self-contained root namespace, name the assembly the same name as the namespace.
Why: This convention is consistent with the .NET Framework and is easy to read. More importantly, however, it keeps your assembly names and namespaces lined up, making it really easy to figure out what is any particular assembly, and what assembly you need to reference for any given class.
AppliedIS.TimeCard.BusinessRules.dll
IrritatedVowel.Controllers.dll
Classes and Structs Standard Based Upon Microsoft .NET Library Standards
Pascal Case, no underscores or leading "C" or "cls". Classes may begin with an "I" only if the letter following the I is not capitalized, otherwise it looks like an Interface. Classes should not have the same name as the namespace in which they reside. Any acronyms of three or more letters should be pascal case, not all caps. Try to avoid abbreviations, and try to always use nouns.
Why: This convention is consistent with the .NET Framework and is easy to read.
Widget
InstanceManager
XmlDocument
MainForm
DocumentForm
HeaderControl
CustomerListDataSet (typed dataset)
Collection Classes Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but add Collection to the end of the name
Why: This convention is consistent with the .NET Framework and is easy to read.
WidgetCollection
Delegate Classes Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but add Delegate to the end of the name
Why: This convention is consistent with the .NET Framework and is easy to read.
WidgetCallbackDelegate
Exception Classes Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but add Exception to the end of the name
Why: This convention is consistent with the .NET Framework and is easy to read.
InvalidTransactionException
Attribute Classes Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but add Attribute to the end of the name
Why: This convention is consistent with the .NET Framework and is easy to read.
WebServiceAttribute
Interfaces Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions, but start the name with "I" and capitalize the letter following the "I"
Why: This convention is consistent with the .NET Framework and is easy to read. It also distinguishes classes from interfaces, where (unlike in VB6) are truly different beings. This avoid name collisions as well, as it is quite common to have IFoo and a class named Foo that implements IFoo.
IWidget
Enumerations Standard Based Upon Microsoft .NET Library Standards
Follow class naming conventions. Do not add "Enum" to the end of the enumeration name. If the enumeration represents a set of bitwise flags, end the name with a plural.
Why: This convention is consistent with the .NET Framework and is easy to read.
SearchOptions (bitwise flags)
AcceptRejectRule (normal enum)
Functions and Subs Standard Based Upon Microsoft .NET Library Standards
Pascal Case, no underscores except in the event handlers. Try to avoid abbreviations. Many programmers have a nasty habit of overly abbreviating everything. This should be discouraged.
Functions and subs must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET
Why: This convention is consistent with the .NET Framework and is easy to read.
VB: Public Sub DoSomething(...)
C#: public void DoSomething(...)
Properties and Public * Member Variables Standard Based Upon Microsoft .NET Library Standards
Pascal Case, no underscores. Try to avoid abbreviations. Members must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET.
Why: This convention is consistent with the .NET Framework and is easy to read.
VB: Public Property RecordID As Integer
C#: public int RecordID
Parameters Standard Based Upon Microsoft .NET Library Standards
Camel Case. Try to avoid abbreviations. Parameters must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET.
Why: This convention is consistent with the .NET Framework and is easy to read.
VB: ByRef recordID As Integer
C#: ref int recordID
Procedure-Level Variables Standard Based Upon De facto Industry-Accepted Practices
Camel Case
Why: This convention is consistent with the .NET Framework and is easy to read. It also avoids naming collisions with class-level variables (see below)
VB: Dim recordID As Integer
C#: int recordID ;
Class-Level Private and Protected Variables Standard Based Upon De facto Industry-Accepted Practices
Camel Case with Leading Underscore. In VB.NET, always indicate "Protected" or "Private", do not use "Dim". Use of "m_" is discouraged, as is use of a variable name that differs from the property by only case, especially with protected variables as that violates compliance, and will make your life a pain if you program in VB.NET, as you would have to name your members something different from the accessor/mutator properties.
Of all the items here, the leading underscore is really the only controversial one. I personally prefer it over straight underscore-less camel case for my private variables so that I don't have to qualify variable names with "this." to distinguish from parameters in constructors or elsewhere where I likely will have a naming collision. With VB.NET's case insensitivity, this is even more important as your accessor properties will usually have the same name as your private member variables except for the underscore.
As far as m_ goes, it is really just about aesthetics. I (and many others) find m_ ugly, as it looks like there is a hole in the variable name. It's almost offensive. I used to use it in VB6 all the time, but that was only because variables could not have a leading underscore. I couldn't be happier to see it go away.
Microsoft recommends against the m_ (and the straight _) even though they did both in their code. Also, prefixing with a straight "m" is right out. Of course, since they code mainly in C#, they can have private members that differ only in case from the properties. VB folks have to do something else. Rather than try and come up with language-by-language special cases, I recommend the leading underscore for all languages that will support it.
If I want my class to be fully CLS-compliant, I could leave off the prefix on any C# protected member variables. In practice, however, I never worry about this as I keep all potentially protected member variables private, and supply protected accessors and mutators instead.
Why: In a nutshell, this convention is simple (one character), easy to read (your eye is not distracted by other leading characters), and successfully avoids naming collisions with procedure-level variables and class-level properties.
VB: Private _recordID As Integer
C#: private int _recordID ;
Controls on Forms An Extension to the Standards
In recent projects (since 2002 or so), I have taken to a single prefix for all my UI controls. I typically use "ux" (I used to use "ui", but it wasn't set apart well in intellisense). "ux" comes from my usual design abbreviations where it means "User eXperience", which has also since become a popular acronym. I have found this to be extremely helpful in that I get the desired grouping in the intellisense even better than if I use "txt", "lbl" etc. It also allows you to change combo boxes to text boxes etc. without having to change the names - something that happens often during initial prototyping, or when programming using highly iterative agile/xp methodologies.
Why: This convention avoids problems with changing control types (textboxes to drop-down lists, or simple text box to some uber textbox, or text box to date picker, for example), and groups the items together in intellisense. It is also much shorter than most Hungarian conventions, and definitely shorter and less type-dependent than appending the control type to the end of the variable name. I will use generic suffixes which allow me enough freedom to change them around.
"ux" prefix
uxUserID, uxHeader, uxPatientDateOfBirth, uxSubmit
Constants Standard Based Upon Microsoft .NET Library Standards
Same naming conventions as public/private member variables or procedure variables of the same scope. If exposed publicly from a class, use PascalCase. If private to a function/sub, use camelCase..
Do not use SCREAMING_CAPS
Why: This convention is consistent with the .NET Framework and is easy to read. A sizable section of the Framework Design Guidelines is dedicated to why they chose not to go the SCREAMING_CAPS route. Using SCREAMING_CAPS also exposes more of the implementation than is necessary. Why should a consumer need to know if you have an enum, or (perhaps because they are strings) a class exposing public constants? In the end, you often want to treat them the same way, and black-box the implementation. This convention satisfies that criteria.
SomeClass.SomePublicConstant
localConstant
_privateClassScopedConstant
case and loops in java Part 1
The switch statement in Java provides a convenient method for branching a program based on a number of conditionals. This recipe describes the use of the Java switch statement.
The basic format of a switch statement in Java is:
switch (expression) {
case cond1: code_block_1;
case cond2: code_block_2;
...
case condn: code_block_n;
default: code_block_default;
}
where expression is an integral expression (like int, char, short, or byte, but not long). In each case statement within the switch statement, a comparison is made which is equivalent to if (expression == cond1). If the comparison evaluates to true, the code within the block is executed. The final default: line is analogous to a final else statement.
This arrangement is similar to a cascade of if/else if/else if statements but with one substantial difference. At the end of each code block, an optional break statement alters the flow through the switch statement. Without any break statements, all subsequent code blocks will be executed once a true evaulation is found. To make a switch statement behave just like an if/else if/else if statement, always put break statements at the end of code blocks. However, leaving out break statements can provide a capability very difficult to achieve with if statements.
For example, consider the following code:
public class TestSwitch {
public final static int TITANIUM = 0;
public final static int PLATINUM = 1;
public final static int GOLD = 2;
public final static int SILVER = 3;
public final static int TIN = 4;
public static void main(String[] args) {
System.out.println("Tin -----");
printGift(TIN);
System.out.println("Titanium -----");
printGift(TITANIUM);
}
public static void printGift(int serviceLevel) {
switch(serviceLevel) {
case TITANIUM: case PLATINUM:
System.out.println(" Free toaster");
case GOLD:
System.out.println(" Free stapler");
case SILVER: case TIN:
System.out.println(" Free staple remover");
break;
default:
System.out.println("No gift");
}
}
}
The example demonstrates break usage since any match will cause one or more println commands to output text but will not print the "No gift" line from the default code block. In addition, note that multiple case statements can be placed before each code block. Running this sample code results in the following output:
Tin -----
Free staple remover
Titanium -----
Free toaster
Free stapler
Free staple remover
The for loop provides a simple mechanism for repeating a code block a fixed number of times or for iterating through a set of values.
The generic syntax for a Java for loop is:
for ( {initialization}; {exit condition}; {incrementor} )
code_block;
For example, to execute a simple loop 5 times printing out the iteration number each time through the loop:
for ( i=1; i<6; i++ ) {
System.out.println(i);
}
In this example, the loop starts with an initialization of the (int) variable i to the value 1. Each time the loop iteration starts, a the exit condition is evaluated (is i less than 6?) and if true, continues. When the loop iteration is complete, the incrementor code is executed (i++ means increment the variable i by one). The loop continues until the exit condition is met (when i is equal to or greater than 6), so the code block will be executed for i values of 1, 2, 3, 4, and 5.
The exit condition code can be more complex as needed because it is computed each time through the loop, so the condition can be based on variables which may change during the loop iteration. To run a code block on each value of an array, the loop condition could be i < array.length.
The incrementor code can also be more complex, essentially any valid Java code. Another simple example would be a decrementor using i-- which would subtract one from the variable i each time through the loop.