ide

  • submit to reddit

Getting Started with Selenium

By Frank Cohen

16,803 Downloads · Refcard 67 of 151 (see them all)

Download
FREE PDF


The Essential Selenium Cheat Sheet

Selenium is a portable software testing framework for Web applications. Selenium works well for QA testers needing record/playback authoring of tests and for software developers needing to author tests in Java, Ruby, Python, PHP, and several other languages using the Selenium API. The Selenium architecture runs tests directly in most modern Web browsers. This DZone Refcard starts with how to install Selenium and then moves on to cover working with TinyMCE, Ajax Objects, Reporting options and even the Future of Selenium.
HTML Preview
Getting Started with Selenium

Getting Started with Selenium

By Frank Cohen

About Selenium

Selenium is a portable software testing framework for Web applications. Selenium works well for QA testers needing record/playback authoring of tests and for software developers needing to author tests in Java, Ruby, Python, PHP, and several other languages using the Selenium API. The Selenium architecture runs tests directly in most modern Web browsers, including MS IE, Firefox, Opera, Safari, and Chrome. Selenium deploys on Windows, Linux, and Macintosh platforms.

Selenium was developed by a team of programmers and testers at ThoughtWorks. Selenium is open source software, released under the Apache 2.0 license and can be downloaded and used without royalty to the originators.

Architecture in a Nutshell

Selenium Browserbot is a JavaScript class that runs within a hidden frame within a browser window. The Browserbot runs your Web application within a sub-frame. The Browserbot receives commands to operate against your Web application, including commands to open a page, type characters into form fields, and click buttons.

Selenium architecture offers several ways to play a test.

Selenium architecture

Functional testing (Type 1) uses the Selenium IDE add-on to Firefox to record and playback Selenium tests in Firefox. Functional testing (Type 2) uses Selenium Grid to run tests in a farm of browsers and operating environments. For example, run install Selenium Grid on 3 operation environments (for example, Windows Vista, Windows XP, and Ubutu) and on each install 2 browser (for example, Microsoft Internet Explorer and Firefox) to smoke test, integration test, and functional test your application on 6 combinations of operating environment and browser. Many more combinations of operating environment and browser are possible. An option for functional testing (Type 2) is to use the PushToTest TestMaker/TestNode open source project. It uses Selenium RC to provide Selenium Gridlike capability with the added advantage of providing datadriven Selenium tests, results analysis charts and graphs, and better stability of the test operations.

The PushToTest open-source project provides Selenium datadriven testing, load testing, service monitoring, and reporting. TestMaker runs load and performance tests (Type 3) in a PushToTest TestNode using the PushToTest SeleniumHTMLUnit library and HTMLUnit Web browser (and Rhino JavaScript engine.)

Hot Tip

HTMLUnit runs Selenium tests faster than a real browser and requires much less memory and CPU resources.

Installing selenium

Selenium IDE installs as a Firefox add-on. Below are the steps to download and install Selenium IDE:

  1. Download selenium-ide-1.0.2.xpi (or similar) from http://seleniumhq.org.
  2. From Firefox open the .xpi file. Follow the Firefox instructions.
  3. Note: Selenium Grid runs as an Ant task. You need JDK 1.6, Ant 1.7, and the Selenium Grid 1.0 binary distribution. Additional directions can be found at http://selenium-grid.seleniumhq.org/get_started.html
  4. See http://www.pushtotest.com/products for TestMaker installation instructions.

Record/playback using selenium ide

Hot Tip

Selenium IDE is a Firefox add-on that records clicks, typing, and other actions to make a test, which you can play back in the Firefox browser. Open Selenium IDE from the Firefox Tools drop-down menu, Selenium IDE command.

Selenium IDE

Selenium IDE preferences

Selenium IDE records interactions with the Web application, with one command per line. Clicking a recorded command highlights the command, displays a reference page, and displays the command in a command form editor. Click the command form entry down-triangle to see a list of all the Selenium commands.

Run the current test by clicking the Run Test Case icon in the icon bar. Right click a test command to choose the Set Breakpoint command. Selenium IDE runs the test to a breakpoint and then pauses. The icon bar Step icon continues executing the test one command at a time.

With Selenium IDE open, the menu bar context changes to provide access to Selenium commands: Open/Close Test Case and Test Suite. Test Suites contain one or more Test Cases.

Use the Options dropdown menu, Options command to set general preferences for Selenium IDE.

Selenium IDE provides an extensibility API set called User Extensions. You can implement custom functions and modify Selenium IDE behavior by writing JavaScript functions. We do not recommend writing User Extensions as the Selenium project makes no guarantees to be backwardly compatible from one version to the next.

Selenium Context Menu provides quick commands to insert new Selenium commands, evaluate XPath expressions within the live Web page, and to show all available Selenium commands. Right click on commands in Selenium IDE, and right-click on elements in the browser page to view the Selenium Context Menu commands.

Selenese Table Format

Selenium IDE is meant to be a light-weight record/playback tool to facilitate getting started with Selenium. It is not designed to be a full test development environment. While Selenium records in an HTML table format (named Selenese) the table format only handles simple procedural test use cases. The Selenese table format does not provide operational test data support, conditionals, branching, and looping. For these you must Export Selenese files into Java, Ruby, or other supported languages.

Selenium Command reference

Selenium comes with commands to: control Selenium test operations, browser and cookie operations, pop-up, button, list, edit field, keyboard, mouse, and form operations. Selenium also provides access operations to examine the Web application (details are at http://release.seleniumhq.org/selenium-core/0.8.0/reference.html).

Command Value, Target, Wait Command
Selenium Control
setTimeout milliseconds
setMouseSpeed number of pixels
setMouseSpeedAndWait
setSpeed milliseconds
setSpeedAndWait
addLocationStrategy strategyName
addLocationStrategyAndWait
allowNativeXpath boolean
allowNativeXpathAndWait
ignoreAttributesWithoutValue boolean
ignoreAttributesWithoutValueAndWait
assignId locator
assignIdAndWait
captureEntirePageScreenShot filename, kwargs
captureEntirePageScreenShotAndWait
echo message
pause milliseconds
runScript javascript
runScriptAndWait
waitForCondition javascript
waitForPageToLoad milliseconds
waitForPopUp windowID
fireEvent locator
fireEventAndWait
Browser Operations
open url
openAndWait
openWindow url
openWindowAndWait
goBack goBackAndWait
refresh refreshAndWait
close
deleteCookie name
deleteCookieAndWait
deleteAllVisibleCookies deleteAllVisibleCookiesAndWait
setBrowserLogLevel logLevel
setBrowserLogLevelAndWait
Cookie Operations
createCookie nameValuePair
createCookieAndWait
deleteCookie name
deleteCookieAndWait
deleteAllVisibleCookies deleteAllVisibleCookiesAndWait
Popup Box Operations
answerOnNextPrompt answer
answerOnNextPromptAndWait
chooseCancelOnNextConfirmation chooseCancelOnNextConfirmationAndWait
chooseOkOnNextConfirmation chooseOkOnNextConfirmationAndWait
Checkbox & Radio Buttons
check locator
checkAndWait
uncheck locator
uncheckAndWait
Lists & Dropdowns
addSelection locator
addSelectionAndWait
removeSelection removeSelectionAndWait
removeAllSelections removeAllSelectionsAndWait
Edit Fields
type locator
typeAndWait
typeKeys locator
typeKeysAndWait
setCursorPosition locator
setCursorPositionAndWait
Keyboard Operations
keyDown locator
keyDownAndWait
keyPress locator
keyPressAndWait
keyUp locator
keyUpAndWait
altKeyDown altKeyDownAndWait
altKeyUp altKeyUpAndWait
controlKeyDown controlKeyDownAndWait
controlKeyUp controlKeyUpAndWait
metaKeyDown metaKeyDownAndWait
metaKeyUp metaKeyUpAndWait
shiftKeyDown shiftKeyDownAndWait
shiftKeyUp shiftKeyUpAndWait
Mouse Operations
click locator
clickAndWait
clickAt locator
clickAtAndWait
doubleClick locator
doubleClickAndWait
doubleClickAt locator
doubleClickAtAndWait
contextMenu locator
contextMenuAndWait
contextMenuAt locator
contextMenuAtAndWait
mouseDown locator
mouseDownAndWait
mouseDownA locator
mouseDownAtAndWait
mouseMove locator
mouseMoveAndWait
mouseMoveAt locator
mouseMoveAtAndWait
mouseOut locator
mouseOutAndWait
mouseOver locator
mouseOverAndWait
mouseUp locator
mouseUpAndWait
mouseUpAt locator
mouseUpAtAndWait
dragAndDrop locator
dragAndDropAndWait
dragAndDropToObject sourceLocator
dragAndDropToObjectAndWait
Form Operations
submit formLocator
submitAndWait
Windows/Element Selection
select locator
selectAndWait
selectFrame locator
selectWindow windowID
focus locator
focusAndWait
highlight locator
highlightAndWait
windowFocus windowFocusAndWait
windowMaximize windowMaximizeAndWait

Selenese Table Format

Selenium commands identify elements within a Web page using:

identifier=id Select the element with the specified @id attribute. If no match is found, select the first element whose @name attribute is id.
name=name Select the first element with the specified @name attribute. The name may optionally be followed by one or more elementfilters, separated from the name by whitespace. If the filterType is not specified, value is assumed. For example, name=style value=carol
dom=javascriptExpression Find an element using JavaScript traversal of the HTML Document Object Model. DOM locators must begin with "document." For example: dom=document.forms['form1'].myList dom=document.images[1]
xpath=xpathExpression Locate an element using an XPath expression. Here are a few examples:

xpath=//img[@alt='The image alt text']
xpath=//table[@id='table1']//tr[4]/td[2]
/html/body/table/tr/td/a
//div[@id='manage_messages_iterator']
//tr[@class='SelectedRow']/td[2]
//td[child::text()='myemail@me.com']
//td[contains(child::text(),'@')]

link=textPattern Select the link (anchor) element which contains text matching the specified pattern.
css=cssSelectorSyntax Select the element using css selectors. For example:

css=ahref="/sites/all/modules/dzone/assets/refcardz/067/#id1"]
css=span#firstChild + span

Selenium 1.0 css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nthof-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after). Without an explicit locator prefix, Selenium uses the following default strategies:

dom, for locators starting with "document." xpath, for locators starting with "//" identifier, otherwise

Your choice of element locator type has an impact on the test playback performance. The following table compares performance of Selenium element locators using Firefox 3 and Internet Explorer 7.

Locator used Type Firefox 3 Internet Explorer 7
q Locator 47 ms 798 ms
//input[@name='q'] XPath 32 ms 563 ms
//html[1]/body[1]//form[1]//input[2] XPath 47 ms 859 ms
//input[2] XPath 31 ms 564 ms
document.forms[0].elements[1] DOM Index 31 ms 125 ms

Additional details on Selenium performance can be found at: http://www.pushtotest.com/docs/thecohenblog/symposium

Script-Driven Testing

Selenium implements a domain specific language (DSL) for testing. Some applications do not lend themselves to record/ playback: 1) The test flow changes depending on the results of a step in the test, 2) The input data changes depending on the state of the application, and 3) The test requires asynchronously operating test flows. For these conditions, consider using the Selenium DSL in a script driven test. Selenium provides support for Java, Python, Ruby, Groovy, PHP, and C#.

Selenium IDE helps get a script-driven test started by exporting to a unit test format. For example, consider the following test in the Selenese table format:

Selenese table format

Use the Selenium IDE File menu, Export, Python Selenium RC command to export the test to a jUnit-style TestCase written in Python. The following shows the Java source code:


package com.example.tests;

from selenium import selenium
import unittest, time, re

class franktest(unittest.TestCase):
	def setUp(self):
		self.verificationErrors = []
		self.selenium = selenium("localhost", 4444, "*chrome", \
			"http://change-this-to-the-site-you-are-testing/")
		self.selenium.start()
	def test_franktest(self):
		sel = self.selenium
		sel.open("/")
		sel.type("q", "sock puppet")
		sel.click("sa")
		sel.wait_for_page_to_load("30000")
		sel.click("//div[@id='res']/div[1]/ol/li[1]/div/h2/a/em")
		sel.click("//div[@id='res']/div[1]/ol/li[1]/div/h2/a/em")
		sel.wait_for_page_to_load("30000")
		
	def tearDown(self):
		self.selenium.stop()
		self.assertEqual([], self.verificationErrors)
		
if __name__ == "__main__":
unittest.main()

An exported test like the one above has access to all of Python's functions, including conditionals, looping and branching, reusable object libraries, inheritance, collections, and dynamically typed data formats.

Selenium provides a Selenium RC client package for Java, Python, C#, Ruby, Groovy, PHP, and Perl. The client object identifies the Selenium RC service in its constructor:


self.selenium = selenium("localhost", 4444, "*iexplore", \
	"http://change-this-to-the-site-you-are-testing/")
self.selenium.start()

The above code identifies the Selenium RC service running on the localhost machine at port 4444. This client will run the test in Microsoft Internet Explorer. The third parameter identifies the base URL from which the recorded test will operate.

Selenium RC service

Using the selenium.start() command initializes and starts the Selenium RC service. The Selenium RC client module (import selenium in Python) provides methods to operate the Selenium DSL commands (click, type, etc.) in the Browserbot running in the browser. For example, selenium.click("open") tells the Browserbot to a click command to the element with an id tag equal to "open". The browser responds to the click command and communicates with the Web application.

At the end of the test the selenium.stop() command ends the Selenium RC service.

Selenium and Ajax

Ajax uses asynchronous JavaScript functions to manipulate the browser's DOM representation of the Web page. Many Selenium commands are not compatible with Ajax. For example, ClickAndWait will time-out waiting for the browser to load the Web page because Ajax functions that manipulate the current Web page in response to a click event do not reload the page. We recommend using Selenium commands that poll the DOM until the Ajax methods complete their tasks. For example, waitUntilElementPresent polls the DOM until the JavaScript function adds the desired element to the page before continuing with the rest of the Selenium script.

Consider the following checklist when using Selenium with Ajax applications:

Check mark

Your Selenium tests may require a large number of extra commands to ensure the test stays in synchronization with the Ajax application. Consider an Ajax application that requires a log-in, then displays a selection list of items, then presents an order form. Ajax enabled applications often deliver multiple steps of function on a single page and show-and-hide elements as you work with the application. Some even disable form submit buttons and other user interface elements until you enter enough valid information. For an application like this you will need a combination of Selenium commands. Consider the following Selenium test:

waitForElementPresent pauses the test until the Ajax application adds the requisite element to the page. waitForCondition pauses the test until the JavaScript function evaluates to true.

Check mark

Some Ajax applications use lazy-loading techniques to improve user interaction with the application. A stock market application provides a list of 10 stock quotes asynchronously after the user clicks the submit button. The list may take 10 to 50 seconds to completly update on the screen. Using waitForXPathCount pauses the test until the page contains the number of nodes that match the specified XPath expression.

Check mark

Many Ajax applications use dynamic element id tags. The Ajax application that named the Log-out button app_6 may later rename the button to app_182. We recommend using DOM element locator techniques, or XPath techniques if needed, to dynamically find elements on a positional or other attribute means.

Command window

Working with tinymce and Ajax objects

Ajax is about moving functions off the server and into the browser. Selenium architecture supports innovative new browser-based functions because Selenium's Browserbot is a JavaScript class itself. The Browserbot even lets Selenium tests operate JavaScript functions as part of the test. For example, TinyMCE (http://tinymce.moxiecode.com) is a graphical text editor component for embedding in Web pages. TinyMCE supports styled text and what-you-see-is-what-you-get editing. Testing a TinyMCE can be challenging. Selenium offers click and type functions that interact with TinyMCE but no direct commands for TinyMCE's more advanced functions. For example, imagine testing TinyMCE's ability to stylize text. The test needs to insert test, move the insertion point, select a sentence, bold the text, and drag the sentence to another paragraph. This is beyond Selenium's DSL. Instead, the Selenium test may include JavaScript commands that interact with TinyMCE's published API (http://tinymce.moxiecode.com/documentation.php).

Here is an example of using the TinyMCE API from a Selenium test context:


this.browserbot.getCurrentWindow().tinyMCE.execCommand
('mceInsertContent',false,'<b>Hello world!!</b>');

Run the above JavaScript function from within a Selenium test using the AssertEval command.


AssertEval javascript:this.browserbot.getCurrentWindow().tinyMCE.
execCommand('mceInsertContent',false,'<b>Hello world!!</b>');

Data Production

Selenium offers no operational test data production capability itself. For example, a Selenium test of a sign-in page usually needs sign-in name and sign-in password operational test data to operate. Two options are available: 1) Use the data access features in Java, Ruby, or one of other supported languages, 2) Use PushToTest TestMaker's Selenium Script Runner to inject data from comma separated value (CSV) files, relational databases, objects, and Web services. See http://tinyurl.com/btxvn4 for details.

Create a Comma-Separated-Value file. Use your favorite text editor or spreadsheet program. Name the file data.csv. The contents must be in the following form.

Comma-Separated-Value file

The first row of the data file contains column names. These will be used to map values into the Selenium test. Change the Selenium test to refer to mapping name. PushToTest maps the data from the named column in the CSV data file to the Selenium test data using the first row definitions.

Connect the Data Production Library (DPL) to the Selenium test in a TestMaker TestScenario. Begin by definition a HashDPL. This DPL reads from CSV data files and provides the data to the test.


<DataSources>
	<dpl name="mydpl" type="HashDPL">
		<argument name="file" dpl="rsc" value="getDataByIndex" index="0"/>
	</dpl>
</DataSources>

Next, tell the TestScenario to send the data.csv and Selenium test files to the TestNodes that will operate the test.


<resources>
	<data path="data.csv"/>
	<selenese path="CalendarTest.selenium"/>
</resources>

Then tell the Selenium ScriptRunner to use the DPL provided data when running the Selenium test.


<run name="CalendarTest" testclass="CalendarTest.selenium"
	method="runSeleneseFile" langtype="selenium">
	<argument dpl="mydpl" name="DPL_Properties" value="getNextData"/>
</run>

The getNextData operation gets the next row of data from the CSV file. The Selenium ScriptRunner injexts the data into the Selenium test.

Browser Sandbox, Redirect, and proxy issues

Selenium RC launches the browser with itself as the proxy server to inject the Javascript of the Browserbot and your test. This architecture makes it possible to run the same test on multiple browsers. However, some browsers will warn the user of possible security threats when the proxy starts and when the test requests functions or pages outside of the originating domain. The browser takes control and stops the Browserbot operations to display the warning message. When this happens, the test stops until a user dismisses the warning. There are no reliable cross-browser workarounds.

Some Web applications redirect from http to https URLs. The browser will often issue a warning that stops the Selenium test.

Selnium does not support a test moving across domains. For example, a test that started with a baseurl of www.mydomain. com may not open a page on www.secondomain.com.

selenium RC browser profiles

Selenium Remote Control (RC) enables test operation on multiple real browsers. A browser profile attribute may be any of the following installed browsers: chrome, konqueror, piiexplore, iehta, mock, opera, pifirefox, safari, iexplore and custom. Append the path to the real browser after browser profile if your system path does not state the path to the browser. For example:


*firefox /Applications/Firefox.app/Contents/MacOS/firefox

Component approach example

Many organizations pursue a "Test and Trash" methodology to achieve agile software development lifecycles. For example, an organization in pursuit of agile techniques may change up to 30% of an application with an application lifecycle of 8 weeks. Without giving the change much thought, up to 30% of their recorded tests break!

Sample test

We recommend a component approach to building tests. Test components perform specific test operations. We write or record tests as individuals components of test function. For example, a component operates the sign-in function of a private Web application. When the sign-in portion of the application changes, we only need to change the sign-in test and the rest of test continues to perform normally.

Selenium supports the component approach in three ways: Selenium IDE supports Test Suites and Test Cases, exporting Selenium tests to dynamic languages (Java, Ruby, Perl, etc.) creates reusable software classes, and 3) PushToTest TestMaker supports multiple use cases with parameterized test use cases.

In Selenium IDE, the File menu enables tests to be saved as test cases or test suites. Record a test, use File -> Save Test Case. Create a second Test Case by choosing File -> New Test Case. Record the second test use case. Save the TestSuite for these two test use cases by choosing File -> Save TestSuite. Click the "Run entire test suite" icon from the Selenium IDE tool bar.

TestMaker defines test use cases using a simple XML notation:


<usecases>
	<usecase name="MailerCheck_usecase">
		<test>
		<run name="LogIn" testclass="Login.selenium" instance="myinst"
			method="runSeleneseFile" langtype="selenium">
		</run>
		<run name="OrderProduct" testclass="OrderProduct.selenium" instance="myinst"
			method="runSeleneseFile" langtype="selenium">
		</run>
		</test>
	</usecase>
</usecases>

Reporting options

Selenium offers no results reporting capability of its own. Two options are available: 1) Write your tests as a set of JUnit tests and use JUnit Report (http://ant.apache.org/manual/OptionalTasks/junitreport.html) to plot success/failure charts, 2) Use PushToTest TestMaker Results Analysis Engine to produce more than 300 charts from the transaction and step time tracking of Selenium tests.

For example, TestMaker tracks Selenium command duration in a test suite or test case. Consider the following chart. This shows the "Step" time it takes to process each Selenium command in a test use case over 10 equal periods of time that the test took to operate.

Step contribution

Selenium Biosphere

Test Maker allows repurposing Selenium tests as load test service monitors. http://www.pushtotest.com

BrowserMob facilitates low-cost Selenium load testing. http://browsermob.com/load-testing

SauceLabs provides a farm of Selenium RC servers for testing. http://saucelabs.com/

ThoughtWorks Twist can be used for test authoring and management. http://studios.thoughtworks.com/twist-agile-test-automation

Running a Selenium test as a functional test in TestMaker. TestMaker displays the success/failure of each command in the test and the duration in milliseconds of each step.

The Future, Selenium 2.0 (AKA Webdriver )

The Selenium Project started the WebDriver project, to be delivered as Selenium 2.0. WebDriver is a new architecture that plays Selenium tests by driving the browser through its native interface. This solves the test playback stability issue in Selenium 1.0 but requires the Selenium project to maintain individual API drivers for all the supported browsers. While there is no release date for Selenium 2.0, the WebDriver code is already functional and available for download at http://code.google.com/p/webdriver.

Available Training

SkillsMatter.com, Think88com, PushToTest.com, RTTSWeb.com, and Scott Bellware (http://blog.scottbellware.com) offer training courses fro Selenium. PushToTest offers free Open Source Test Workshops (http://workshop.pushtotest.com) as a meet-up for Selenium and other Open Source Test tool users.

About The name Selenium

Selenium lore has it that the originators chose the name of Selenium after learning that Selenium is the antidote to Mercury poisoning. There appears to be no love between the Selenium team and HP Mercury, but perhaps a bit of envy

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Getting Started with Eclipse RCP

By James Sugrue

15,445 Downloads · Refcard 62 of 151 (see them all)

Download
FREE PDF


The Essential Eclipse RCP Cheat Sheet

The Eclipse Rich Client Platform (RCP) provides a foundation for building and deploying rich client applications. It includes Equinox, a component framework based on the OSGi standard, and an integrated update mechanism for deploying desktop applications from a central server. This DZone Refcard introduces you to the Eclipse plug-in development environment and shows you how to add key functionality to your RCP application using Views, Perspectives and Editors. Learn how to add a Menu to your Plug-in, create a Help system for your user, and how to brand and productize your Eclipse RCP application.
HTML Preview
Getting Started with Eclipse RCP

Getting Started with Eclipse RCP

By James Sugrue

About the Rich client platform

The Eclipse Rich Client Platform (RCP) is a platform for building and deploying rich client applications. It includes Equinox, a component framework based on the OSGi standard, the ability to deploy native GUI applications to a variety of desktop operating systems, and an integrated update mechanism for deploying desktop applications from a central server. Using the RCP you can integrate with the Eclipse environment, or can deploy your own standalone rich application.

Introducing the Plug-in development environment

To get started in developing your own plug-ins, first download a version of Eclipse including the Plug-in Development Environment (PDE). Eclipse Classic is the best distribution for this.

When developing plug-ins, you should use the Plug-in Development perspective. You'll notice this perspective provides another tab in your Project Navigator listing all the plug-ins available.

To create an RCP application, go to the File menu and select New > Project where you will be presented with the new project wizard. From here choose Plug-in Project.

New project wizard

Figure 1: The New Project Wizard

The next screen allows you to assign a name to your plugin. Usually, plug-in name follow Java's package naming conventions. RCP applications should be targeted to run on a particular version of Eclipse, here we choose to run on Eclipse 3.5.

RCP Project Settings Page

Figure 2: RCP Project Settings Page

The next page in the project wizard allows you to set some important attributes of your plug-in. This page allows you to specify whether your plug-in will make contributions to the UI. In the case of RCP plug-ins, this will usually be true. You can choose whether to create your own RCP application, or to create a plug-in that can be integrated with existing Eclipse installations.

The following table summarizes other plug-in settings and what they mean for your application. All of these settings can be changed in the generated MANIFEST.MF file for your project at any stage.

Attribute Name Default Value Meaning
id <project name> The identifier for this RCP plug-in
Version 1.0.0.qualifier The plug-in version. Multiple versions of any plug-in are possible in your Eclipse environment provided they have unique version numbers
Name RCP Application The readable name of this plug-in
Provider The second part of your project package name. The provider of this plug-in

Hot Tip

Get started quickly with your first RCP application by using the included RCP Mail Template, available when you choose to create a standalone RCP application.

Manifest.mf explained

The generated META-INF/MANIFEST.MF file is the centre of your RCP plug-in. Here you can define the attributes, dependencies and extension points related to your project. In addition, you may have a plugin.xml file. The contents of both these files are show in the plug-in manifest editor.

Plug-In manifest editor

Figure 3: The plug-in manifest editor

The Overview tab in this editor allows you to change the settings described earlier in the new project wizard. It also provides a shortcut where you can launch an Eclipse application containing your new RCP plug-in.

The Dependencies tab describes how this plug-in interacts with others in the system. All plug-ins which you are dependent on will need to be added here.

The Runtime tab allows you to contribute packages from your own plug-in to others to use or extend. You can also add libraries that don't exist as plug-ins to your own project in the Classpath section.

Hot Tip

While you may change your build path through the Dependencies or Runtime tab, changing dependent plug-ins in the Java Build Path of the project properties tab will not reflect properly in the plug-ins manifest.

The Extensions tab is where you go to define how this plug-in builds on the functionality of other plug-ins in the system, such as for adding menus, views or actions. We will describe these extension points in more detail in the relevant sections. The Extension Points tab allows you to define your own extensions for other plug-ins to use.

The Standar d Widget Toolkit and Jface

While developing UI code for your RCP application, it is important to understand the Standard Widget Toolkit (SWT). This is a layer that wraps around the platform's native controls. JFace provides viewers, in a similar way to Swing, for displaying your data in list, tables, tree and text viewers.

The UI toolkits used in Eclipse applications are a large topic, so we assume that the reader will be aware of how to program widgets in SWT and JFace.

Adding a menu to your plug-in

One of the first things that you will want to do with your RCP plug-in is to provide a menu, establishing its existence with the Eclipse application that it is built into. To do this, as with any additions to our plug-in, we start in the Extensions tab of the plug-in manifest editor.

Up to Eclipse 3.3 Actions was the only API available to deal with menus, but since then the commands API has become available, which we will focus on here.

To add a menu in the command API you will need to follow similar steps to these:

Declare a command

To do this we use the org.eclipse.ui.commands extension point. Simply click on the Add... button in the Extensions tab and chose the relevant extension point.

First, you will need to associate this command with a category. Categories are useful for managing large numbers of commands. From the org.eclipse.ui.commands node, select New > Category. The required fields are a unique ID and a readable name.

After this right click on the node and choose New>Command. The important attributes for a command are listed below.

Attribute Name Required Use
id Yes A unique id for this command
Name Yes A readable name for the command
Description No A short description for display in the UI
CategoryID No The id of the category for this command (that you described in the previous step).
DefaultHandler No A default handler for this command. Usually you will create your own handler.

Declare a Menu Contribution for the Command

To create a menu, you will first need to add the org.eclipse. ui.menus extension point. From the created node in the UI, select New>menuContribution. The required attribute for the menu contribution is it's locationURI, which specifies where the menu should be placed in the UI. This URI takes the format of [scheme]:[id]?[argument-list]

An example of the more useful locationURI's in the Eclipse platform follow:

Attribute Name Required
menu:org.eclipse.ui.main.
menu?after=window
Insert this contribution on the main menu bar after the Window menu
menu:file?after=additions Inserts contribution in the File menu after the additions group
toolbar:org.eclipse.ui.main.
toolbar?after=additions
Insert this contribution on the main toolbar
popup:org.eclipse.ui.popup.
any?after=additions
Adds this contribution to any popup menu in the application

Once the location of your contribution is chosen, click on New>command on this contribution to define the menu. The following attributes exist for each command:

Attribute Required Use
commandId Yes The id of the Command object to bind to this element, typically already defined, as in our earlier step. Click Browse... to find this
Label No The readable label to be displayed for this menu item in the user interface
id No A unique identifier fo this item. Further menu contributions can be placed under this menu item using this id in the locationURI
mnemonic No The Character within the label to be assigned as the mnemonic
icon No Relative path to the icon that will be displayed to the left of the label
tooltip No The tooltip to display for this menu item

Hot Tip

Defining a toolbar item is a similar process. Based on a menuContribution with the correct locationURI, select New>Toolbar providing a unique id. Create a new command under the toolbar similar to the menu item approach.

Create a Handler for the Command

The final extension point required for the menu is org.eclipse. ui.handlers. A handler has two vital attributes. The first is the commandId which should be the same as the command id specified in the beginning. As you can see, this is the glue between all three parts of the menu definition.

You will also need to create a concrete class for this handler, which should implement the org.eclipse.core.commands. IHandler interface.

Hot Tip

Clicking on the class hyperlink on the manifest editor will pop up a New Class Wizard with the fields autofilled for this.

Finally, you will need to define when this command is enabled or active. This can be done programmatically in the isEnabled() and isHandled() methods. While this is easiest, the recommended approach is to use the activeWhen and enabledWhen expressions in the plug-ins manifest editor which avoids unnecessary plug-in loading.

Hot Tip

Once you have added in an extension point plugin. xml will become available. All extension points can be added through the manifest editor, or in XML format through this file.

Views

In an RCP applications Views are used to present information to the user. A viewer must implement the org.eclipse. ui.IViewPart interface, or subclass org.eclipse.ui.parts.ViewPart.

Difference between perspective, editor and view

Figure 4: An illustration of the difference between perspective, editor and view.

To create a View, you will need to add the org.eclipse. ui.views extension point. In order to group your views, it is useful to create a category for them. Select New>Category from the org.eclipse.ui.views node to do this. The required fields are a unique ID and a readable name.

Next, choose New>View from the extension point node and fill in the necessary details.

Attribute Required Use
id Yes The unique id of the View
name Yes A readable name for this view
class Yes The class that implements the IViewPart interface
category No The id of the category that contains this view. This category should be used if you wish to group views together in the Show Views... dialog.
icon No The image to be displayed in the top left hand corner of the view
allowMultiple No Flag indicating whether multiple views can be instantiated. The default value is false.

The code behind the view is in a class that extends org.eclipse.ui.ViewPart. All controls are created programmatically In the createPartControl() method in this class.

To facilitate lazy loading, a workbench page only holds IViewReference objects, so that you can list out the views without loading the plug-in that contains the view definition.

When created, you will see your view in the Window>Show View>Other... dialog

Hot Tip

It's good practice to store the view's id as a public constant in your ViewPart implementation, for easy access.

Loose Coupling

To facilitate loose coupling, your ViewPart should implement org.eclipse.ui.ISelectionListener. You will also need to register this as a selection listener for the entire workbench:


getSite().getWorkbenchWindow().getSelectionService().
addSelectionListener(this);

This allows your view to react to selections made outside of the view's own context.

Editors

An editor is used in an Eclipse RCP application when you want to create or modify files, or other resources. Eclipse already provides some basic text and Java source file editors.

In your plug-in manifest editor, add in the org.eclipse. ui.editors extension point, and fill in the following details

Attribute Required Use
id Yes The unique id of this editor
name Yes A readable name for this editor
icon No The image to be displayed in the top left hand corner of the editor when it is open
extensions No A string of comma separated file extensions that are understood by the editor
class No The class that implements the IEditorPart interface
command No A command to run to launch and external editor
launcher No The name of a class that implements IEditorLauncher to an external editor
contributorClass No A class that implements IEditorActionBarContributor and adds new actions to the workbench menu and toolbar which reflect the features of the editor type
default No If true this editor will be used as the default for this file type. The default value is false
filenames No A list of filenames understood by the editor. More specific than the extensions attribute
matchingStrategy No An implementation of IEditorMatchingStrategy that allows an editor to determine whether a given editor input should be opened

Editors implement the org.eclipse.ui.IEditorPart interface, or subclass org.eclipse.ui.parts.EditorPart.

Like views, to facilitate lazy loading, a workbench page only holds IEditorReference objects, so that you can list out the editors without loading the plug-in that contains the editor definition.

Perspectives

Perspectives are a way of grouping you views and editors together in a way that makes sense to a particular context, such as debugging. By creating your own perspective, you can hook into the Window>Open Perspective dialog.

To create a perspective, you need to extend the org.eclipse.ui.perspectives extension point.

Attribute Required Use
id Yes The unique id of this perspective
name Yes A readable name for the perspective
class Yes The class that implements the IPerspectiveFactory interface
icon No The image to be displayed related to this perspective
Fixed No Whether this perspective can be closed or not. Default is false

The class driving the perspective implements org.eclipse. ui.IPerspectiveFactory. This class has one method createInitialLayout(), within which you can use the IPageLayout.addView() method to add views directly to the perspective. To group many views together in a tabbed fashion, rather than side by side, IPageLayout.createFolder() can be used.

Hot Tip

When running your application you need to ensure that you have all required plug-ins included. Do this by checking your Run Configurations. Go to the plugins tab and click Validate Plug-ins. If there are errors click on Add Required Plug-ins to fix the error.

Preferences

Now that you have created a perspective and a view for your RCP application, you will probably want to provide some preference pages. Your contributed preference pages will appear in the Window>Preferences dialog.

To provide preference pages you will need to implement the org.eclipse.ui.preferencePages extension in the plug-in manifest editor.

Attribute Required Use
id Yes The unique id of this preference page
name Yes A readable name for the preference page
class Yes The class that implements the IWorkbenchPreferencePage interface
category No Path indicating the location of the page in the preferences tree. The path may be defined using the parent preference page id or a sequence of ids separated by "/". If no category is specified, the page will appear at the top level of the preferences tree.

While the preference page class will implement org.eclipse. ui.IWorkbenchPreferencePage, it is useful to extend org. eclipse.jface.preference.FieldEditorPreferencePage as it provides createFieldEditors() method which is all you need to implement, along with the init() method in order to display a standard preference page. A complete list of FieldEditors is provided in the org.eclipse.jface.preference package.

Loading and Storing Preferences

Preferences for a plug-in are stored in an org.eclipse.jface. preference.IPreferenceStore object. You can access a plug-ins preference through the Activator, which will typically extend org.eclipse.ui.plugin.AbstractUIPlugin. Each preference you add to the store has to be assigned a key. Preferences are stored as String based values, but methods are provided to access the values in number of formats such as double, int and Boolean.

Property Sheets

While preferences are used to display the overall preferences for the plug-in, property sheets are used to display the properties for views, editors or other resources in the Eclipse environments. By hooking into the Properties API, the properties for you object will appear in the Properties view (usually displayed at the bottom of your Eclipse application).

The Properties view will check if the selected object in the workspace can supports the org.eclipse.ui.views. properties.IPropertySource interface, either through implementation or via the getAdapter() method of the object. Each property gets a descriptor and a value through the IPropertySource interface.

Help

All good applications should provide some level of user assistance. To add help content to the standard Help>Help Contents window, you can use the org.eclipse.help.toc extension point. Add a number of toc items to this extension point, the only mandatory attribute for each toc entry is the file that contains the table of contents definition.

Hot Tip

To see a quick example of what help content should look like, choose the Help Content item from the Extension Wizards tab when adding to the plug-ins manifest.


<toc label="Getting Started" link_to="toc.xml#gettingstarted">
<topic label="Main Topic" href="html/gettingstarted/
maintopic.html">
<topic label="Sub Topic" href="html/gettingstarted/
subtopic.html" />
</topic>
<<topic label="Main Topic 2">
<topic label="Sub Topic 2" href="html/gettingstarted/
subtopic2.html" />
</topic>
</toc>

Each topic entry should have a link to a HTML file with the full content for that topic. The above XML extract from a table of contents file illustrates this. There is also the choice to use the definition editor for help content. This will open by default in Eclipse when choosing a toc file.

Cheat Sheets

Another user assistance mechanism used in Eclipse is a cheat sheet, which guides the user through a series of steps to achieve a task. To create your initial cheat sheet content, use the New>Other...>User Assistance>Cheat Sheet. This presents you with an editor to add an Intro and a series of items, with the option to hook in commands to automate the execution of the task.

To add this cheat sheet to your plug-in manifest, the cheat sheet editor has a Register this cheat sheet link on the top right hand corner. When registering the cheat sheet you will need to provide it with a category and a description.

Cheat sheet registration dialog

Figure 5: Cheat sheet registration dialog

Clicking finish on this dialog will add the org.eclipse. ui.cheatsheets.cheatSheetContent extension point to your manifest. You can modify the details of the cheat sheet from here if necessary.

Features

You can help the user to load up your plug-in(s) as a single part, by combining them into one feature. Eclipse provides a wizard to create your feature through the New Project> Plug-in Development >Feature Project wizard.

This wizard generated a feature.xml file which has an editor, similar to the plug-in manifest editor, where you can change the details of your feature.

The most important section is the Plug-ins tab, which lists the plug-ins required for your feature. The Included Features tab allows you to specify sub-features to include as part of your feature. On the Dependencies tab, you can get all the plugins or features that you are dependent on by clicking on the Compute button.

A simple feature.xml may look as follows:


<?xml version="1.0" encoding="UTF-8"?>
<feature
id="my.feature"
label="Feature"
version="1.0.0.qualifier"
provider-name="James">
<description url="http://www.example.com/description">
[Enter Feature Description here.]
</description>
<copyright url="http://www.example.com/copyright">
[Enter Copyright Description here.]
</copyright>
<license url="http://www.example.com/license">
[Enter License Description here.]
</license>
<requires>
<import plugin="org.eclipse.ui"/>
<import plugin="org.eclipse.core.runtime"/>
</requires>
<plugin
id="com.dzone.refcard.rcpapp"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
</feature>

Branding

The feature also provides a single location where you can define all the branding for your application. In the Overview tab, you can assign a Branding Plug-in to the feature.

The branding plug-in needs to contain the following artefacts:

Item Purpose
about.html A HTML file that will be displayed in the Plug-in Details>More Info dialog
about.ini This file contains most of the branding information for the feature described below
about.properties Used for localisation of the strings from the about.ini file. The values are referenced using the %key notation

about.ini

Property Purpose
aboutText Multiline description containing name, version number and copyright information. Will appear in the About>Feature Details>About Features dialog.
featureImage A 32x32 pixel icon representation of the feature to be used across the relevant About dialogs

All of the icons and files referenced by the about.ini file should be placed in this plug-in also.

Product Branding

A product is an entire distribution of an RCP application, rather than a feature intended to be part of an existing distribution. As such, products have additional branding requirements. To specify these extra parameters, a contribution to the org. eclipse.core.runtime.products extension point is required.

The product must be assigned the application to run, the name of the product (for the title bar) and a description. Further properties are added as name/value pairs underneath the product.

Hot Tip

An application can be provided by using the org. eclipse.core.runtime.applications extension point

Property Purpose
windowImages The image used for this application, in windows and dialogs. This should be in the order of the 16x16 pixel image, followed by the 32x32
aboutImage Larger image to be placed in the About dialog
aboutText Multiline description containing name, version number and copyright information. Will appear in the About>Feature Details>About Features dialog.

You can also provide most of these details in the Branding tab of the generated .product file.

Splash Screen

The .product file that is generated while creating your product includes a Splash tab. Here you can specify the plug-in that contains the splash.bmp file for your Splash screen. Typically, this should reside in your branding plug-in. The splash screen can also be customized with templates, and can include a progress bar with messages.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

IntelliJ IDEA

Updated for 8.1

By Hamlet DArcy

7,699 Downloads · Refcard 52 of 151 (see them all)

Download
FREE PDF


The Essential IntelliJ IDEA Cheat Sheet

IntelliJ IDEA Looking to update your IntelliJ IDEA IDE? In this DZone Refcard, updated for IntelliJ IDEA 8.1, author Hamlet D’Arcy helps you navigate the various facets of this world-class IDE, including the Editor, Project, and Structure panes. With a rich collection of editing shortcuts, debugging tips and techniques for writing less code, IntelliJ newbies and IDEA-savvy developers will both benefit with this cheat sheet by their side. Still using IntelliJ IDEA 6.0? Relax, our original IntelliJ IDEA Refcard is exactly what you need.
HTML Preview
IntelliJ IDEA

IntelliJ IDEA

By Hamlet D'Arcy

ABOUT INTELLIJ IDEA

Software developers know the importance of using the best tool for the job. Often this means choosing a world-class integrated development environment (IDE), which JetBrains’ IntelliJ IDEA certainly is. But the best developers don’t just have the right tools, they are experts in those tools. This is a guide to becoming that expert. The basics of navigating and understanding the IDE are covered; but this guide is really about unlocking all the powerful features of the tool and helping you be more productive.

Getting Yourself Oriented

Editor

The three most important elements of the IDE are the Editor pane (a), where your code is shown, the Project pane (b), where your project’s contents are shown, and the Structure pane (c), where the details of the open object are shown.

Editor Pane: Shows the currently active file, with recently viewed files in the tab bar. IntelliJ IDEA shows the most recently used files in the tabs, and there is seldom a need to manually close tabs. If the maximum number of tabs is reached, then the oldest tab is closed when a new tab is opened. Also, there is seldom a need to save a file; file saving is performed automatically in the background. The IDE supports syntax highlighting for many languages, but is also language aware and shows syntax errors as they occur.

Navigate faster by learning these commands:

Back Ctrl+Alt+Left Move back to the last cursor position
Forward Ctrl+Alt+Right Move forward to the next cursor position
Next Tab Alt+Right Activate tab to the right of the active one
Previous Tab Alt+Left Activate tab to the left of the active one
Goto Line Ctrl+G Go to a specific line in the active file
Goto Last Edit
Location
Ctrl+Shift+Backspace Go to the position of the last edit

Hot Tip

Toolbar icons are shown throughout this guide, but you’ll be much faster if you learn the key bindings. The mouse is slow: stop using it! IntelliJ IDEA key bindings have received praise over the years, and many believe they are simply better than other IDE’s default bindings. If you’re switching from another tool, consider learning the new bindings rather than loading an alternate key map. The KeyPromoter plugin can help you with this.

Edit faster by learning these commands:

Move Statement Up Ctrl+Shift+Up Moves the current code block up in the file
Move Statement Down Ctrl+Shift+
Down
Moves the current code block down in the file
Copy/Paste Line Ctrl+C /
Ctrl+V
When nothing is selected, copy, cut, and paste operate on the entire line
Clipboard Stacking Ctrl+Shift+V When copying text, the IDE remembers your previous copies. Use Ctrl+Shift+V to show the clipboard history dialog and paste from a previous copy instead of the most recent clipboard contents
Select/Unselect Word at Caret Ctrl+W /
Ctrl+Shift+W
Selects and unselects the word at the caret. Quickly select or unselect the word, statement, block, and method by repeating this action. Experiment to learn how this works differently depending on where your cursor starts
Toggle Bookmark F11 Sets or removes a bookmark on the current line, which shows as black in both the left and right gutter
Comment/
Uncomment
Ctrl+/ Comments out current selection, or removes comments from current selection. This is supported across many languages
Column Mode Ctrl+Shift+
Insert
Column mode allows you to select a rectangular fragment of code. Effectively using this can greatly speed up bulk edits on structured data like SQL or csv files

Getting Yourself Oriented, continued

Project Pane: Shows the contents of the current project, allowing you to view the project as files, packages, or scopes (more about this later). Objects in the project view visually indicate their type with an icon (which also appears on the editor tabs).

Find objects faster by learning what the icons mean:

code Class code Class with main( )
(indicated by green triangle)
interface Interface interface public
Protector Abstract Class Protector protected
Enumeration Enumeration package package
Exception Exception private private
Annotation Annotation ReadOnly Read Only (indicated by lock)
TestCase Test Case (indicated by red and
green triangles)
Not in version control (object
name appears in red)
FinalClass Final Class (Indicated by pin) In version control (object name
appears black, or blue if edited)

Properly configuring the Project pane makes it more effective:

Autoscroll Autoscroll to Source When an object or method is clicked in the Project pane, that item is opened in the Editor pane.
AutoscrollFrom Autoscroll from Source When an item is opened in the Editor pane, that item is scrolled to in the Project pane
StructurePane Show structure Shows the Structure pane (explained next) as a window nested within the Project pane
FinalClass Show/Hide Members Shows the methods and properties of objects within the Project pane
FinalClass Sort by type Sorts the Java classes by type from the most abstract to the most concrete

Structure Pane: Shows the structure of the active file, including methods, properties, and inner classes. Leaving this pane open helps you quickly locate the desired point within a class. Make this pane more useful by tweaking the configuration options:

Autoscroll Autoscroll to source Properties Show properties
AutoscrollFrom Autoscroll from source inherited Show inherited
visibility Sort by visibility ShowFields Show fields
SortAlphabetically Sort alphabetically non-public Show non-public
GroupMethods Group Methods by defining type

Hot Tip

IntelliJ IDEA provides almost endless amounts of configuration through the Settings (Ctrl+Alt+S) window. Use the search box to quickly find what you need. Just start typing what the option might be called and the window will highlight to show which buttons lead to a panel containing that keyword. Wildcards work too!

Finding What You Need

IntelliJ IDEA sets itself apart by offering incredibly advanced ways to find objects and files within large projects. Mastering the act of finding what you need is key to faster development.

Goto Class Ctrl+N Provides dialog for finding classes. Accepts wildcards, camel case, and package prefixes. For example, “BOS” matches BufferedOutputStream, “Str*Buff” matches StringBuffer, and “java.lang.I” matches all objects starting with “I” in the java.lang package. Use Up/Down error to select the class, and Shift+Up/ Down or Ctrl+Click to perform multiple selections.
Goto File Ctrl+Shift+N Provides a similar dialog for finding files that are not classes. For example, “*spring*xml” matches any xml files with the word “spring” in the name, and “*Test.groovy” matches any test case implemented in Groovy.

The navigation bar is a useful alternative to the Project pane. This horizontal bar provides breadcrumb style navigation based on the active file. To navigate to a different package, simply click the + to expand a node higher up in the tree. The navigation bar can be a faster alternative to the Project pane.

navigationbar

You can also use Alt+Home to quickly open the navigation bar from the current editor pane.

Navigating a single class is done through the Structure pane (described earlier) and the file structure popup.

File Structure Popup: (Ctrl+F12) allows quick navigation to methods, fields, and properties. Use the Up/Down arrows to select an entry, or (better) use the search as you type field. Just start typing to narrow the list down. The field provides wildcard and camel case matching. Selecting an entry scrolls the active file to that entry’s declaration.

Navigating large object oriented codebases is greatly simplified by learning these commands:

Ctrl+B /
Middle Click
Go to declaration. Navigates to the declaration of the selected instance or type.
Ctrl+Alt+B Go to implementers or overriders of the selected method. Clicking the icon in the left gutter performs the same action
Ctrl+U Go to the parent of the selected method or type. Clicking the icon in the left gutter performs the same action
Ctrl+Mouse
Over
Shows the declaration of a local variable or field in a popup window
Ctrl+H Opens the Type Hierarchy pane for the active class. This pane explores the super and subclasses of the current object with a variety of different views
Ctrl+Shift+H Opens the Method Hierarchy pane for the active method. This pane explores the definitions and implementations of the current method.
F4 Jump to Source. Many tool windows display objects within project. Used from a tool window, F4 universally opens the element from the tool in the editor. If you’re in the Ant, Hierarchy, or Find window, then F4 will open the selection in the editor pane.

Finding usages is an important feature of any IDE. Being Java aware, IntelliJ IDEA offers more intelligent searching than simple string matching.

Highlight Usages in File (Ctrl+Shift+F7) takes the current mouse selection and highlights all occurrences of that element in the file. The Editor pane and the right gutter provide visual keys to where the occurrences appear. Use F3 and Shift+F3 to jump to the next and previous occurrence.

Finding What You Need, continued

Show Usages Popup (Ctrl+Alt+F7) takes the current mouse selection and searches the project for any references made to the field or type. Results appear in an in-editor popup window.

Show Usages in Find Panel (Alt+F7) behaves the same as the Show Usages Popup, except that results are displayed in the Find pane. Learning to operate the Find pane with the keyboard helps you move faster to the intended object.

Rerun Rerun the last find
Shift+Esc Rerun Close the Find pane
Ctrl+NumPad + Expand Expand all the nodes in the list
Ctrl+NumPad - Collapse Collapse all the nodes in the list
Ctrl+Alt+Up Rerun Navigate to the previous occurrence
Ctrl+Alt+Down Rerun Navigate to the next occurrence
Ctrl+E Recent Find Usages dialog. Quickly jump to a past search result.

Hot Tip

Turn on Scroll to Source in the Find pane and use Ctrl+Alt+Up and Ctrl+Alt+Down to quickly cycle through the usages in the main editor window.

Search Structurally (Ctrl+Shift+S) and Replace Structurally (Ctrl+Shift+M) allows searching (and replacing) references using patterns. Again, this is Java aware and done structurally, and is not just text string search and replace. This very rich feature is best explained with an example. Here are the steps to find any factory methods within the project (ie, methods whose name starts with “create”):

  • Open Search Structurally (Ctrl+Shift+S)
  • Click “Copy the existing template” and select method calls, which is $Instance$.$MethodCall$($Parameter$)
  • Click “Edit variables” and select MethodCall
  • For the MethodCall variable, enter “create.*” in the Text / Regular Expression. This is the regular expression for the word create followed by any number of other characters
  • Click “Find” to open the Find pane showing all the factory methods

Scopes

Often, you only want to search a subset of your project, for instance just the test or production source. IntelliJ IDEA provides Scopes to create smaller filesets used in searching, replacing, and inspections. Some default scopes are “Project Production Files”, “Project Test Files”, and “Changed Files”. Fine tune your searching by defining your own scope, perhaps based on a set of packages. Scopes can also be helpful to speed up searches on large projects. Here are the steps to define a scope:

  1. Open Settings (Ctrl+Alt+S) and select Scopes
  2. Click Rerun to create a new scope
  3. Select a package to include from the project browser. Use include and include recursively to broaden the fileset, and exclude and exclude recursively to narrow the fileset
  4. Save. New Scope is now available for many operations

Finding Documentation

There are many ways to find documentation on objects within your project and dependencies. Master these commands to get the information you need without leaving the IDE:

Ctrl+P Parameter Info. Displays quick information on the parameter types (and overloading options) of a method call when the caret is within the parenthesis of a method declaration
Ctrl+Q Quick Documentation Lookup. Displays Javadoc in a popup for the item at the caret
Ctrl+Shift+I Quick Definition. Displays the source code for the item at the caret
Shift+F1 External Javadoc. Opens an external browser to the Javadoc for the item at the caret. May require setting Javadoc locations within Settings (Ctrl+Alt+S) Project Settings (1)

Hot Tip

Is an option you need buried deep in the menu system? Use Ctrl+Shift+A to bring up the Action finder. Type the name of the action you’re looking for and IntelliJ IDEA searches the keymap, menus, and toolbars for the item you need to invoke. Wildcards and camelCase works, of course

Running and Debugging Your Project

Running and debugging the project is an essential part of any IDE. The easiest way to run an application is to right click the object within the Editor pane and select Run. This works for classes with main() and test cases. You can also right click the object and do the same thing in the Project pane. To run tests in an entire package simply right click the package.

Manage run targets by using the Run/Debug configurations window, adding any VM parameters or advanced settings you may need. Open the window by clicking Edit Configurations within the toolbar's dropdown.

Toolbar Dropdown

Common run targets can be saved here for future runs.

Running an entry point will display the Run pane. This pane provides diagnostics on the running process. Get the information you need from running processes by learning to use the pane:

Ctrl+F5 Run Run the last target
pause Pause execution
Ctrl+F2 stop Stop execution
Ctrl+Break Dump Thread Dump Thread information to a new window or clipboard
Ctrl+Alt+Up Move Up Move Up Stack Trace, opening the Editor pane to the exception location
Ctrl+Alt+Down Move Down Move Down Stack Trace, opening the Editor pane to the exception location

Running and Debugging Your Project, continued

When debugging an application, the IDE provides a variety of ways to set breakpoints and watchpoints. The easiest is to click the left gutter of the line or method on which you want a breakpoint. More advanced breakpoints are available through the Breakpoints window (Ctrl+Shift+F8).

Line Break on the specified line of code
Exception Break when the specified exception is thrown
Method Break when the specified method is called
Field Break when the specified field instance is accessed or changed

Once stopped on a breakpoint, the Debug pane will open. This pane provides features common to all debuggers, as well as more advanced, uncommon actions.

Alt+F10 ExecutionPoint Show Execution Point
F8 Step Over Step Over
F7 Step Into Step Into
Shift+F7 Smart Step Into. Pick which method to step into when multiple calls exist on one line.
Alt+Shift+F7 Force Step Force Step Into
Shift+F8 Step Out Step Out
Drop Frame Drop Frame
Ctrl+Alt+Up Previous Frame Previous Stack Frame
Ctrl+Alt+Down Next Stack Frame Next Stack Frame
Alt+F9 Cursor Run to Cursor

Hot Tip

Control what not to step into in Settings (Ctrl+Alt+S) Debugger (G). Exclude certain library classes using the “Do not step into” list, skip simple getters, skip constructors, and more.

Once in the debugger, several panels provide different views of the application state. The Frames Panel shows the current stack frames on the selected thread, and you can navigate quickly between frames and threads. The Variables Panel shows any variables currently in scope. And the Watches Panel shows expanded information on selected variables. When entering variables to watch, autocompletion and smart-type both work.

Expression Evaluation (Alt+F8) allows quick execution of code snippets or blocks. From this window you can reference any in-scope variable of the application. It works a bit like a REPL window open with the current breakpoint’s environment, and is most useful in code fragment mode, where you can evaluate multi-line statements.

Hot Tip

Drop Frame within the debugger pops the current stack frame and puts control back out to the calling method, resetting any local variables. This is very useful to repeatedly step through a function, but be warned: field mutations or global state changes will remain.

Code Coverage: IntelliJ IDEA offers code coverage statistics using the EMMA or IntelliJ IDEA toolkit. Enable tracking in the Code Coverage tab of the Run/Debug Configurations window. The built in runner provides more accurate branching coverage when tracing is enabled. Results appear in several places:

Package Coverage Project pane shows % class and % line coverage per package
Class Coverage Project pane shows % class and % line coverage per class
Line Coverage Editor pane left gutter shows red for uncovered line, green for covered line

Code Coverage Data (Ctrl+Alt+F6) displays a list of previous runs, and selecting an entry shows the coverage data for that run. You can use this to compare coverage between subsequent runs.

Hot Tip

Under certain circumstances, code coverage may make your automated tests fail because instrumented bytecode is different than normal bytecode (I’ve seen this happen when remote CORBA interfaces were invoked). If this happens then simply exclude the affected classes from code coverage within the Run/Debug Configurations window.

Write Less Code

Typing less to produce more is a feature of any modern IDE. IntelliJ IDEA provides top tier code completion support, as well as many other code generation, file template, and refactoring features.

Code Completion: Leveraging code completion is essential to productivity:

Ctrl+Space Basic. Completes the names of in-scope classes, methods, fields and keywords. Also complete paths, when appropriate
Ctrl+Shift+Space Smart Type. Displays a suggestion list where the type of the object required can be inferred from the code, such as in the right hand side of assignments, return statements, and method call parameters
Ctrl+Alt+Space Class Name. Completes the names of classes and interfaces. Accepts camel case matching on input
Ctrl+Shift+Enter Complete Statement. Adds closing punctuation and moves cursor to next line
Alt+Slash Expand Word. Cycles through suggested word choices, highlighting the prototype in the editor

Hot Tip

Confused by all the options? Just start using them and let muscle memory take over. It works.

Code Generation: Letting the IDE infer the code you need to create and drop in the appropriate template can be a huge time saver.

Ctrl+O Override Methods... quickly specify a parent method to override and create a stub implementation
Ctrl+I Implement Methods... quickly specify a parent method to implement and create a stub
Code->Delegate Methods... Delegate Methods... creates adapter classes by delegating method calls to member fields. A small wizard guides you through the delegation
Ctrl+Alt+T Surround With... surrounds the current selection with a variety of code wrappers, like if/else, for, try/catch, synchronized, Runnable, and more

Write Less Code, continued

Generate (Alt+Insert) provides its own set of powerful options for code generation:

Constructor Select any of your object’s fields from a list to create a constructor with the proper parameters and body
Getter Select a field from a list to create an accessor method
Setter Select a non-final field from a list to create a mutator method
equals() /
hashCode()
Provides a dialog to automatically create equals() and hashCode() methods based on your object’s fields

Live Templates are fragments of commonly occurring code, which can be inserted into the active file in a variety of ways. Learning the live templates will save you many, many keystrokes. A full list is available in Settings (Ctrl+Alt+S) Live Templates.

To insert a live template, press Ctrl+J followed by the following keys:

psf public static final thr throw new
itar Iterate elements of an
array
sout Prints a string to
System.out
itco Iterate elements of
collection
soutm Prints the current class and method name to System.out
ritar Iterate elements of array
in reverse order
soutv Prints the value of a variable to System.out
toar Stores members of
Collection in Array
psvm main() method declaration

Hot Tip

Logging live templates are very useful, but many projects use log4J or Commons Logging instead of System.out. Replace the System.out calls with your framework within Settings (Ctrl+Alt+S) Live Templates.

Surround with Live Template (Ctrl+Alt+J) will surround the current selection with a block of code. Some of the useful surrounds are:

B Surround with { }
R Surround with Runnable
C Surround with Callable

Hot Tip

Use the existing surrounds templates to create your own, like surround with SwingUtilities.invokeLater() or new Thread().start()

Live Template in Multiple Languages: Many live templates exist for languages other than Java. JSP, XML, Spring definitions, and more all exist. Here are some examples of templates from other platforms and toolsets:

sb Creates an XML based Spring bean definition
sbf Creates an XML based Spring bean definition instantiated by a factory method (many more Spring intentions exist, too)
itws Generate Axis web service invocation (many more flavors of web services supported, too)
CD Surround with CDATA section
T Surround with <tag></tag>

Hot Tip

The free keymap from JetBrains provides a larger list of live templates. Post the keymap next to your monitor to learn the live templates quickly.

Refactoring: IntelliJ IDEA offers excellent refactoring support. Refactoring is aware of comments, reflection, Spring, AOP, JSP, and more. When the refactoring features are unsure on the safety of a refactoring, a preview mode is invoked so that you can verify the changes. Refactoring works on more than just Java code too: many refactorings exists for XML files as well as other languages. Learning the refactoring tools (and reading the refactoring literature, for that matter) is well worth your time. Here are some of the more common refactorings:

Rename Shift+F6 Renames a package, class, method, field or variable
Move F6 Moves an entity
Change Signature Ctrl+F6 Change the method or class name,parameters, return type, and more
Extract Method Ctrl+Alt+M Moves the current selection to a new method, replacing duplicates if found
Inline Ctrl+Alt+N Takes a method, variable, or inner class and replaces usages with a unique definition
Introduce Variable Ctrl+Alt+V Moves the selected expression into a local variable
Introduce Field Ctrl+Alt+F Moves the selected local variable into a field,prompting you for how initialization should occur
Introduce Constant Ctrl+Alt+C Moves the selected variable or field into a static final field, replacing duplicates if found
Introduce Parameter Ctrl+Alt+P Moves the selected local variable into a parameter argument, updating any callers in the process
Extract Interface Moves a set of methods from the object onto an interface, updating callers to reference the interface if possible
Pull Member Up Move a method from a subclass up to an interface or parent class
Encapsulate Fields Provides getter and/or setters for the selected field

Hot Tip

Ctrl+Shift+J will join two lines together, which is a sort of shorthand for inline variable.

Improve Your Project ’s Quality

The IDE’s features aren’t just about writing code faster, they are also about coding more accurately. Understanding the intentions, inspections, and analysis tools are key to keeping code high quality.

Intentions: Keeps code clean by flagging potential problems in the Editor pane as they occur, and then offers an automated solution. An available intention is signaled by a lightbulb appearing in the left gutter, and the suggested fix can be applied by pressing Alt+Enter. There are several types of intentions:

  • n “Create from usage” intentions allow you to use new objects and methods without defining them first. Need a new method? Just call it from code; IntelliJ IDEA will prompt you to create it, inferring the parameter and result types. This works for classes, interfaces, fields, and variables. If the missing reference is in all capital letters, then it will even create a constant for you.

Improve Your Project’s Quality, continued

  • n “Quick fix” intentions find common mistakes and makes context-based suggestions on how to fix them. Examples of issues flagged with a quick fix are assigning a value to the wrong type or calling a private method.
  • “Micro-refactorings” fix code that compiles but could be improved. Examples are removing an unneeded variable and inverting an if condition.

Some of the intentions or fixes might violate your coding standard. Luckily, they can all be configured within Settings (Ctrl+Alt+S) Intentions.

Intentions and Quick Fixes are indicated by different icons in the left gutter, but in practice there is little need to differentiate between the two:

Icon Box

Inspections: Keeps code clean by detecting inconsistencies, dead code, probable bugs, and much, much more. The near-1000 default inspections can do a lot to enforce common idioms and catch simple bugs across the project. There are way too many inspections to list, but here are examples to provide a flavor of what inspections can do:

  • Flag infinite recursion or malformed regular expression
  • Catch error handling issues like continue within finally block or unused catch parameter
  • Find threading issues like await() outside a loop or non-thread safe access
  • Error on Javadoc issues like missing tags or invalid links

Inspections work with many languages and tools beyond the Java language, like Spring, JSF, Struts, XML, JavaScript, Groovy, and many others. The inspection set is highly configurable through Settings (Ctrl+Alt+S) Errors. Each inspection can carry its own set of options, and most can be shown as warnings or errors within the IDE. When an inspection violation is shown in the right gutter, Alt+Enter triggers the suggestions to be shown.

Some inspections appear within the Editor pane, while others appear within the Inspection pane when they are run as a batch. To run inspections for a scope, go to Analyze Inspect Code in the menu.

Inspection settings can be configured and shared across the team. An “IDE” inspection profile is saved within the user’s $HOME directory, but a “Project” profile is saved within the IDEA project file. This means a shared, version controlled project file can be created which contains the team’s inspections.

Hot Tip

By default, IDEA uses a great set of inspections, but many more options are not turned on by default. Check out http://hamletdarcy.blogspot.com/ 2008/04/10-best-idea-inspections-youre-not.html to see some non-default inspections you might want to use.

Code Analysis: Provides several different views of dependencies and duplicates within your project. These tools help you modularize your code and find areas of potential reuse. All of the following features are available from the Analyze menu.

The Dependency Viewer provides a split tree-view of your project with a list panel at the bottom. From here you can navigate the dependencies or mark certain undesirable dependencies as illegal. Which analysis feature chosen determines what the Viewer displays:

Dependencies Left: Your packages. Right: Packages your code depends on
Backward Dependencies Left: Your packages. Right: Packages that depend on your
code. Bottom: Line by line usages
Cyclic Dependencies Left: All of your packages that have a cyclic dependency. Right: The objects that form the cycle. Bottom: Line by line usages

Not all analysis tools report to the Dependency Viewer, however. Module Dependencies uses a separate panel to display dependencies across all the included modules within the project. This is useful for multi-module projects. Dependency Matrix launches the Dependency Structure Matrix in a separate window. This tool helps you visualize module and class dependencies across the project using a colored matrix.

Locate Duplicates: Finds suspected copy and pastes within your project or desired scope. Use this to find and consolidate duplicate modules or statements. The results are displayed in the Duplicates pane, which ranks the copy/paste violations and allows you to extract methods on the duplicates by simply clicking the Eliminate duplicates icon Icon1

Work as a Tea m

IntelliJ IDEA includes many features that allow team members to collaborate effectively.

Version Control (VC) integration exists for Subversion, Git, CVS, Perforce, StarTeam, Visual SourceSafe, TFS, and ClearCase. When enabled, local changes appear as a blue bar in the left gutter:

Version Control

Clicking the blue bar displays some VC options, including a quick line diff (displayed), a rollback of the line changes, or a full file diff in the IntelliJ IDEA Diff Viewer. More VC options are available from the menu or by right-clicking the active editor:

View History See revision history for active file with check-in comments
View
Differences
Launch the side-by-side file comparison window. Merge changes from one file to another, accept non conflicting changes, and more
Annotate Show the user ID of the last person to touch each line in the left gutter

Local History can be used even if you don’t have version control. The IDE keeps track of saves and changes to files, allowing you to rollback to previous versions if desired. Older versions can also be labeled, making it easy to find previous save points.

Shared Project: The project file can be put in version control, keeping all environments up to date as changes are made. Use this guide to the project files to determine what files need to be shared:

.ipr Contains project info like module paths, compiler settings, and library locations. This should be in version control
.iml Used in a multi-module project, each module is described by an .iml file. This should be in version control
.iws Contains workspace and personal settings. This should not be in version control

Work as a Team, continued

File Templates: Shared file templates provide a common starting point for frequently typed code. Templates exist, and can be changed, for creating new classes, interfaces, and enumerations. Templates for includes, like a copyright notice, can also be stored and shared, as well as code templates, like default catch statements and method bodies. Modify the file templates in Settings (Ctrl+Alt+S) File Templates.

Ant Integration: Many projects use Ant as a common build script, and IntelliJ IDEA offers integration with it. Features include syntax highlighting, code completion, and refactorings. Several inspections and intention settings are also available. Use the Ant Build Window to run one or several Ant targets. For larger projects with many targets, use the filter targets feature to hide uncommon targets. The Maven build system is also supported.

Work With the Database

IntelliJ IDEA 8 ships with a data source editor and JDBC console. Once configured with a JDBC or SQL data source, the console is a great environment for working with the database, providig SQL syntax completion, error and syntax highlighting, and completion of the table and column names. Middle click entities like table names or columns to navigate to their definition in the DDL view, and run the entire script (Ctrl+Enter) or snippits (Ctrl+Shift+Enter) using the controls provided. The results pane can be copied to the clipboard as comma separated values. You can also use parameters within the scripts, which are variables marked with the @, #, $, or ? characters. Any parameters found are displayed in the parameters Pane, and from there they can be edited without modifying the SQL source script.

Endless tweaking awaits

A massive amount of configuration options are available in Settings (Ctrl+Alt+S). Beyond that, you may wish to experiment with different plugins. Plugins are installed and managed using Settings (Ctrl+Alt+S) Plugins. Many plugins exist, adding features like Scala, Ruby, or web framework support. JetBrains holds plugin contests annually, so check the site periodically.

About The Author

Photo of author Hamlet D’Arcy

Hamlet D’Arcy

Hamlet D’Arcy has been writing software for over a decade, and has spent considerable time coding in Groovy, Java, and C++. He’s passionate about learning new languages and different ways to think about problems, and recently he’s been discovering the joys of both F# and Scheme. He’s an active member and speaker at the Groovy Users of Minnesota and the Object Technology User Group, and is involved with several open source projects including the Groovy language and the IDEA Jet- Groovy plugin. He blogs regularly at http://hamletdarcy.blogspot.com, tweets as HamletDRC, and can be contacted at hamletdrc@gmail.com.

Recommended Book

Easy PHP Websites with the Zend Framework

For new users, IntelliJ IDEA in Action is a logically organized and clearly expressed introduction to a big subject. For veterans, it is also an invaluable guide to the expert techniques they need to know to draw a lot more power out of this incredible tool. You get a broad overview and deep understanding of the features in IntelliJ IDEA.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Getting Started with Visual Studio 2010

By Alessandro Del Sole

16,952 Downloads · Refcard 118 of 151 (see them all)

Download
FREE PDF


The Essential Visual Studio 2010 Cheat Sheet

The Visual Studio 2010 Refcard focuses on the new features in this release and the most common keyboard shortcuts. It will get you started with the IDE and show you how to create, build and debug applications. Youll learn about the WPF Code Editor, which has improved extensibility and code reusability. Youll learn about the "Generate from Usage" tool. Youll also learn about drag and drop data binding with WPF and Silverlight. This Refcard is the perfect companion for the .NET developer working in Visual Studio 2010, whether its WPF, Silverlight, C#, VB, or F# development.
HTML Preview
Getting Started with Visual Studio 2010

Getting Started with Visual Studio 2010

By Alessandro Del Sole

INTRODUCTION

The new version of the Visual Studio 2010 Integrated Development Environment ships with a number of new important features. Such features are both related to the IDE architecture and to the coding experience, with the addition of new tools as well. This Refcard is a quick reference to the most important new features and instruments in Visual Studio 2010, also providing tips to most common shortcuts.

STARTING WITH VISUAL STUDIO 2010

Visual Studio 2010 is the developer tool used for creating .NET applications. There are different editions which cover every need, such as the Ultimate edition or the free Express editions (the latter are specific for hobbyists and students).

Starting the IDE

When you run Visual Studio 2010, the first thing you notice is a new Start Page which provides shortcuts, organized into tabs, to lots of learning resources about programming different Microsoft technologies with Visual Studio. These include the .NET Framework and programming languages, data platform, cloud computing or tools for teams. The following figure shows how the Start Page looks:

Visual Studio 2010 face

Visual Studio 2010 offers a convenient way for managing the most recently used projects by simply right-clicking each project name in the list. With this action you can pin or remove items from the list itself.

Creating applications

You create .NET applications in Visual Studio 2010 by first creating projects. A project is the place where all the parts composing your application, such as code, libraries, dialogs, pages and resources, reside. An application can be composed of one or more projects. Multiple projects bound together are combined into a Solution. Thus, the first step is creating a new project. You accomplish this by selecting the New|Project command from the File menu. This will show the New Project dialog which looks like this:

Visual Studio 2010 face2

As you can see, there are a number of available project types, grouped by programming language or by typology. As you can see from the above figure, the programming language project types are sub-grouped by technology. Once you have selected the desired project type, just assign a name and click OK. The Visual Studio documentation that ships with the product provides full descriptions for both Windows and Web projects.

In Visual Studio 2010 you can also target different versions of the .NET Framework (as shown in the figure above) or search specific project templates using the Search Installed Templates search box.

Building and debugging applications

You can build and run your executable application by pressing F5. This is common to both Windows and Web applications and will run your application with an instance of the Visual Studio debugger attached. Visual Studio provides a lot of debugging tools available in the Debug menu. For example, you can place breakpoints (also by pressing F9) or check for the value of local variables via the Locals tool window. If you don’t want to run the application under the debugger investigation, simply press Shift+F5.

You can quickly deploy your application using the ClickOnce technology, which you access via the Build|Publish command.

Browsing the documentation

You can access the Visual Studio documentation in different situations by pressing F1. For example you can get general information by pressing F1 anywhere or get specific help for an element in your code by selecting the code element (such as the name of a type) and, again, press F1. In Visual Studio 2010 the help system has been rebuilt completely and now allows you to browse the documentation inside your Web browser. The following figure shows an example:

Browsing the documentation

WPF-BASED CODE EDITOR

Most of the Visual Studio 2010 architecture now relies on Windows Presentation Foundation, the most recent technology from Microsoft for building rich client applications. If you are an existing Visual Studio developer this is something you immediately notice when running the IDE for the first time; it affects a number of areas such as the Start Page and tabbed dialogs or tool windows. The code editor is also built upon WPF which provides some great benefits, including:

  • Better text r endering
  • Code editor zoom by pr essing CTRL + mouse wheel
  • Automatic selection of all occurr ences of a word
  • Tabbed code dialogs can be undocked and tr eated like any other window outside the IDE
  • Improved extensibility: the code editor also takes advantage of MEF (Managed Extensibility Framework) to receive pluggable components. This allows hosting rich content inside the code editor, such as images, videos, WPF controls, comment adornments and so on.
  • Reusability: you can reuse the code editor as a component in your own Visual Studio add-ins.

You interact with the code editor via the IWPFTextView interface which is described in the MSDN Library. The following image shows how the WPF-based code editor looks:

WPF-based code editor

Notice that the zoom percentage is greater than 100%. This was accomplished simply by pressing CTRL + mouse wheel. A good number of code editor extensions are available in the Visual Studio Gallery Web site.

“GENERATE FROM USAGE” TOOL

In its continuous evolution, the Visual Studio environment has committed to offer even more sophisticated tools for helping developers write code. IntelliSense®, syntax highlighting, and auto-completion are just a few examples. It previously lacked the ability to create new objects on the fly. With Visual Studio 2010 you can now create new objects while writing code. This is useful when you realize that you need an object that you did not consider before or that you need to extend an existing object with new members. This functionality is integrated into the code editor and is known as Generate From Usage; it is available for both Visual Basic and C#.

Creating new types on the fly

Let’s start describing Generate From Usage by creating a new Console application. Consider the following situation, in which the code attempts to create an instance of the Contact class that actually does not exist yet and pay attention to the error correction options provided by the IDE:

IDE

Click Generate ‘Class Contact’ and Solution Explorer you will notice the presence of a file named Contact.vb (or .cs in C#) which contains the empty definition of the new class.

Hot Tip

The class declaration gets the default visibility modifier, according to the current programming language, which is Friend for Visual Basic and Internal for C#. You need to change this manually if you want to expose the class outside the assembly.

Now you can populate your class with new members, like in the following figure, where the code attempts to assign a non-inexistent property, but the IDE provides the possibility of generating a property or a field:

IDE2

If you select the first option, Visual Studio will add a property named LastName of type String to the Contact class. Similarly you can add both instances and shared methods on the fly. It is worth mentioning that Visual Studio:

  • generates members of the appropriate type when possible.
  • is able to generate interfaces and methods referring to delegates according to the current scenario. When generating such methods, it is able to add the appropriate signature.

You saw how to create a class, which is the default type, and members with default visibility. But you can do more with Generate From Usage as explained in next subsection.

Creating different kinds of types

There are situations in which you need to create different kinds of objects, such as structures or enumerations. Generate From Usage makes this task easy. For example, you might want to create a new structure. If you type the following line of code:


Dim someData As New CustomData

the IDE marks CustomData as non-existent. From the error correction suggestions popup, simply select Generate New Type. This will prompt you with the Generate New Type dialog shown in the next figure:

Type dialog

Here you can:

  • Provide the new object’s visibility by setting the Access property
  • Decide what kind of object you want to cr eate from the Kind property
  • Add the new member to a dif ferent project in your solution via the Project combo box
  • Create a new code file or add the new object to an existing code file inside the File Name box

Simply click OK when you are done and the new object will be added to your solution according to the specified settings. At this point you can add new members as described in the previous section.

WPF & SILVERLIGHT: DRAG AND DROP DATA-BINDING

Visual Studio 2010 introduces an important feature for data development to both WPF and Silverlight: drag and drop data-binding. This technique has been very popular in the past among Windows Forms developers since it allows creating data forms quickly and easily. In order to make the data development experience easier in modern client technologies, such a technique is now available for WPF and Silverlight. In WPF full support is offered for DataSets and ADO.NET Entity Framework. With full support we intend complete UI and codebehind code generation. Support is also offered for custom business objects or different data sources such as LINQ to SQL or WCF Data Services, but only on the UI side, meaning that you need to write all the data access code from scratch. In Silverlight you don’t have DataSets, so you can use this kind of data-binding with Entity Framework and custom objects.

Hot Tip

The drag and drop data-binding is also available for WPF 3.5 and Silverlight 3 projects.

Creating the data-bound interface

Whatever your data source is, you may open the Data Sources window and then simply drag your desired data item from the window onto the designer surface, as it was done previously in Windows Forms applications. The following figure provides an example based on the Entity Framework as the data source:

figure2

Hot Tip

The Data Sources window in Visual Studio 2010 provides full support for entities exposed by the Entity Framework.

As in older technologies, you can still create grid views or details views and you are allowed to replace the default controls with different ones. You can drag an entire object to create a view or a single object onto an items container control such as the ListBox for creating lists.

Hot Tip

Visual Studio adds controls to the user interface depending on the version of the .NET Framework you are targeting. For example, if you want to create a grid view, Visual Studio uses the DataGrid control in .NET 4 and a ListView control in .NET 3.5.

Dragging and dropping the data is just the first step since you obviously need some code.

A tour of the code

When you use the drag and drop binding, Visual Studio generates some useful code for you. This not only refers to the user interface and controls, but also to querying data. On the XAML side, it first generates the appropriate CollectionViewSource objects acting like “bridges” between data and UI:


<Window.Resources>
	  <CollectionViewSource x:Key=”CategoriesViewSource” d:DesignSo
urce=”{d:DesignInstance my:Category, CreateList=True}” />
	  <CollectionViewSource x:Key=”CategoriesProductsViewSo
urce” Source=”{Binding Path=Products, Source={StaticResource
CategoriesViewSource}}” />
	</Window.Resources>

Next it generates data-bound controls, such as a DataGrid and Label/TextBox couples if considering the previous image (notice the Binding markup extension pointing to the bound property):


<DataGrid AutoGenerateColumns=”False” EnableRowVirtualization=”True”
Height=”128” HorizontalAlignment=”Left” ItemsSource=”{Binding}”
Name=”CategoriesDataGrid” RowDetailsVisibilityMode=”VisibleWhenSelect
ed” VerticalAlignment=”Top” Width=”248”>
	<DataGrid.Columns>
		<DataGridTextColumn x:Name=”CategoryIDColumn”
Binding=”{Binding Path=CategoryID}” Header=”Category ID”
Width=”SizeToHeader” />
		<DataGridTextColumn x:Name=”CategoryNameColumn”
Binding=”{Binding Path=CategoryName}” Header=”Category Name”
Width=”SizeToHeader” />
		<DataGridTextColumn x:Name=”DescriptionColumn”
Binding=”{Binding Path=Description}” Header=”Description”
Width=”SizeToHeader” />
	</DataGrid.Columns>
  </DataGrid>
…
	<Label Content=”Product ID:” Grid.Column=”0” Grid.Row=”0”
HorizontalAlignment=”Left” Margin=”3” VerticalAlignment=”Center” />
	<TextBox Grid.Column=”1” Grid.Row=”0” Height=”23”
HorizontalAlignment=”Left” Margin=”3” Name=”ProductIDTextBox”
Text=”{Binding Path=ProductID, Mode=TwoWay,
ValidatesOnExceptions=true, NotifyOnValidationError=true}”
VerticalAlignment=”Center” Width=”100” />
…

It is worth mentioning that Visual Studio also maps data types to the appropriate controls. A typical example is when you have data of type System.DateTime that is represented via a DatePicker control (available in .NET 4 only). On the managed code side, Visual Studio generates some starting code for querying data. In case you use the Entity Framework as the Data Access Layer, the generated code looks like this (continuing the example from the previous image):


Class MainWindow
	Private Function GetCategoriesQuery(ByVal NorthwindEntities As _
										WpfApplication1.
NorthwindEntities) _
										As System.Data.Objects.
ObjectQuery(Of WpfApplication1.Category)


	Dim CategoriesQuery As System.Data.Objects.ObjectQuery(Of
WpfApplication1.Category) =
		   NorthwindEntities.Categories
		‘Update the query to include Products data in Categories. You
can modify this code as needed.
		CategoriesQuery = CategoriesQuery.Include(“Products”)
		‘Returns an ObjectQuery.
		Return CategoriesQuery
	End Function
	
	Private Sub Window_Loaded(ByVal sender As System.Object,
							  ByVal e As System.Windows.
RoutedEventArgs) _
							  Handles MyBase.Loaded
		Dim NorthwindEntities As WpfApplication1.NorthwindEntities =
			New WpfApplication1.NorthwindEntities()
		‘Load data into Categories. You can modify this code as
needed.
		Dim CategoriesViewSource As System.Windows.Data.
CollectionViewSource =
			CType(Me.FindResource(“CategoriesViewSource”), System.
Windows.Data.CollectionViewSource)
		Dim CategoriesQuery As System.Data.Objects.ObjectQuery(Of
WpfApplication1.Category) =
		  Me.GetCategoriesQuery(NorthwindEntities)
		CategoriesViewSource.Source = CategoriesQuery.
									  Execute(System.Data.Objects.
MergeOption.AppendOnly)
   End Sub
End Class

This will allow loading some data when you run the application. Once you have your starting code, you can write your own queries or extend the auto-generated code with additional features, such as Insert/Update/Delete operations or provide data navigation functionalities.

WPF & SILVERLIGHT: MULTI-TARGETING DESIGNER

In previous versions of Visual Studio the design-time experience for WPF and Silverlight developers did not offer specialized design tools. For WPF developers, the IDE lacked some tooling familiar to Windows Forms developers. Visual Studio 2008 introduced some improvements to the WPF design experience, like the ability to drag controls from the toolbox and drop them onto the designer surface, or the possibility to access event handlers by double-clicking the controls. But no support was available for setting special properties inside the Properties Window (e.g. brushes) so developers needed to manually write the code to set them. For Silverlight developers, things were even worse, in that you had neither drag and drop support nor design time support such as adjusting the application layout, so everything had to be set in code. Although Visual Studio is a developer tool, Microsoft Expression Blend is the tool best suited for deep customization of the user interface. While lots of developers use only Visual Studio to create the user interface for their applications, the need for better VS designer program was paramount. This is what happened with the release of Visual Studio 2010. In the next section you get an overview of the new and improved features, while later you will get information about how this targets multiple .NET Framework versions.

Improved experience

With Visual Studio 2010, both the WPF and Silverlight esigners now provide a full design-time experience and, most importantly, both technologies share the same tools. This means that you have the same instrumentation available for both WPF and Silverlight projects. You now have full support for dragging and dropping controls from the toolbox, for rearranging controls on the controls’ surface and you can also set complex properties within the Properties Window. The following figure represents such a description with regard to a WPF project:

figure3

If you try to do this inside a Silverlight project, you get exactly the same result and tools available. Notice how you now have a new color picker editor available for properties of type brush, which allows specifying the brush color, its type (e.g. a gradient or an image) and manually entering the color code. Prior to Visual Studio 2010 this had to be performed by writing pure XAML code. There are a number of other improvements in this area that are listed below.

Setting grid columns and rows

You can easily set rows and columns within a Grid control by selecting the RowDefinitions and ColumnDefinitions properties in the Property Window and then by taking advantage of a new dialog that looks like the following figure:

figure4

You simply click Add, then set properties for each row or column, such as the Height or Width.

Searching for a property

The Properties Window has been enhanced with a number of new features. You got a taste of this in the previous section when discussing how to set properties of type Brush. Another interesting addition is that you can now search for a specified property by writing its name in the search box at the top of the window. Also, you do not need to write the entire property name since Visual Studio filters the property list as you type characters inside the search box:

figure5

This way you can easily reach and set the properties you want to assign.

Hot Tip

The search field is also available in the Events tab of the Properties Window.
Setting controls’ fonts

In Visual Studio 2010 you can now easily set font properties to controls supporting fonts via an integrated tool inside the Properties Window.

Hot Tip

This is available only when you enable the Categorized view.

For instance, you can select the font from a combo box and then set text alignment, size and weight all together, as shown in the following figure:

figure6
Visually setting data-binding and resources

The Properties Window also improves the way you assign data-bound properties or resources. You select the data-bound property for your control and then you can easily use the Binding popup as follows:

  1. Select your data source. This can be the DataContext—another control or a resource as shown in the followingfigure:

    figure7

  2. Switch to the Path tab in order to select the property you wish to be bound;
  3. Select any value converter you want to apply via the Converter tab; and
  4. Finally go to the Options tab and apply any other additional options. This is really impressive in that you have a great number of available properties such as data error validation or triggering property changes.

You can apply resources similarly. For example, if you defined a style for a button and then you want to apply such a style, just right click the Style property in the Properties Window and select Apply Resource. This will provide a useful popup where you will be able to pick both default and local resources, as demonstrated in the following figure:

figure8

You can also choose between static and dynamic resources and you are offered a preview of the result you get once the resource is applied.

Multiple .NET Framework versions targeted

Visual Studio 2010 ships with integrated support for Silverlight 3 but it also supports Silverlight 4 when you install the appropriate developer tools. The good news is that all the stuff you have seen so far, including the drag and drop databinding, is available for both .NET Framework 3.5 SP 1 and 4.0 in Visual Studio 2010. This is what is usually referred to as multi-targeting, when talking about the designer. This basically means that you can create applications for WPF 3.5, WPF 4, Silverlight 3 and 4 taking advantage of all the new designer features independent of the technology or its version. If you want to check this out by yourself, simply create a new WPF or Silverlight project and in the New Project dialog select the .NET Framework 3.5 as the target Framework. You will notice no difference in the designer if compared to .NET 4.

COMMON SHORTCUTS AND TIPS

Visual Studio 2010 offers both shortcuts for quick access to common tools and instruments that you may find really useful. This section provides information on both topics.

Common shortcuts

  • Start the application in debugging mode by pr essing F5 or without attaching the debugger by pressing Shift+F5
  • Save all files in your solution by pr essing Ctrl+Shift+S
  • Build your solution by pr essing Ctrl+Shift+B
  • Run your application without the debugger by pr essing Shift+F5
  • Show the toolbox by pr essing Ctrl+Alt+T
  • Navigate to a specific member definition by pr essing Ctrl+
  • Comment multiple line of codes by pr essing CTRL+K and CTRL+C in sequence or uncomment lines by pressing CTRL+K and CTRL+U in sequence
  • Show up the Properties window by pressing F4
  • Select code blocks by pr essing ALT + mouse
  • Place a breakpoint by pressing F9 on the specified line of code

Common tips

  • Download and manage Visual Studio extensions via the Tools|Extension Manager tool
  • Add menu items for running external tools via the Tools|External Tools command
  • Add IntelliSense code snippets within the code editor by pr essing Ctrl+K or right-click and then Insert Snippet
  • Export project or item templates in or der to create reusable templates with File|Export template
  • Find all references of a type or member by performing right click inside on a member inside the code editor and then selecting Find All References

About The Authors

Photo of author Alessandro Del Sole

Alessandro Del Sole

Alessandro Del Sole, Microsoft Most Valuable Professional (MVP) for Visual Basic since 2008, is well known throughout the global Visual Basic community. The author of four books about .NET development with Visual Studio, he is a community leader on the Italian Visual Basic Tips and Tricks (www.visual-basic.it) web site that serves more than 42,500 VB developers. He is also a frequent contributor to the MSDN Visual Basic Developer Center (msdn.com/vbasic). He enjoys writing articles on .NET development, writing blog posts on both his Italian and English blogs, and producing instructional videos. You can find him online in forums or newsgroups.

Recommended Book

Photo of Book: Visual Basic 2010

This book’s broad coverage includes advanced features such as generics and collections; a thorough introduction to the Visual Studio 2010 IDE and Visual Studio Team System; a full section on data access with ADO.NET and LINQ; practical overviews of WPF and WCF; coverage of web and cloud development with Silverlight and Azure; and advanced topics such as multithreading, testing, and deployment.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Objective-C for the iPhone and iPad

By Ben Ellingson and Matthew McCullough

19,235 Downloads · Refcard 110 of 151 (see them all)

Download
FREE PDF


The Essential Objective-C for iOS Cheat Sheet

Objective-C is the primary language used to create applications for Apples Mac OS X and iOS (iPhone and iPad) platforms. This DZone Refcard offers an in-depth explanation of the Syntax and Tools used for Objective-C. The Syntax section covers everything from Class Declaration to Memory Management. The Tools section covers Xcode, debugging, and the iPhone and iPad Simulator, among other things. Whether you are a beginner or a veteran, this DZone Refcard is an excellent resource for any iDeveloper.
HTML Preview
Objective-C for the iPhone and iPad

Objective-C: for the iPhone and iPad

By Ben Ellingson and Matthew McCullough

An Introduction to the Language and tools

Objective-C is the primary language used to create applications for Apple’s Mac OS X and iOS (iPhone and iPad) platforms. Objective-C was created by Brad Cox and Tom Love in the early 1980s. In 1988, Objective-C was licensed by NeXT, a company founded and helmed by Steve Jobs during his absence from Apple. Apple acquired NeXT in 1996, bringing Objective-C to the Macintosh platform.

Objective-C is an object oriented superset of ANSI C. Its object syntax is derived from Smalltalk. It supports single inheritance, implementation of multiple interfaces via the @protocol syntax, and the redefinition and augmentation of (open) classes via categories. Apple’s iPhone SDK for the iOS mobile operating system offers developers a rich set of Objective-C APIs. This free SDK, which includes the Xcode IDE, is used to create applications for the iPhone, iPad, and iPod Touch.

The Syntax

Class Declaration

Objective-C classes typically include an interface .h and an implementation .m pair of files. The .h file contains property and method declarations. The .m file contains method implementations.

Example .h interface file

@interface Speaker : NSObject {
	NSInteger *ID;
	NSString *name;
}
@property NSInteger *ID;
@property(nonatomic,retain) NSString *name;
- (void) doSomething: (NSString *) value anotherValue: (int) value2;
@end

Example .m implementation file

#import “Speaker.h”
@implementation Speaker
@synthesize ID,name;
- (void) doSomething: (NSString *) value anotherValue: (int) value2 {
	// do something
}
@end

Inheritance

Class inheritance is specified in the .h interface file with the syntax: @interface <MyClass> : <ParentClass>. The following example tells the compiler that the Employee class inherits from (extends) the Person class.


// Employee.h file
@interface Employee : Person {
}
@end

Hot Tip

The keyword @interface can distract developers coming from some languages such as Java, suggesting this is a mere contract. However, @interface is indeed the keyword for defining the properties and method signatures of a concrete class in Obj-C.

Interfaces

Objective-C interfaces are created using the @protocol declaration. Any class can implement multiple interfaces. Interfaces are typically declared in a .h header file and can be included via #import statements in the .h header file of other classes.


// Mappable.h: Declare the Mappable @protocol
@protocol Mappable
- (double) latitude;
- (double) longitude;
@end
// Location.h: Specify that Location class implements the Mappable
// @protocol
#import “Mappable.h”
@interface Location : NSObject <Mappable> {
}
@end
// Location.m: Provide implementations for the Mappable methods
@implementation Location
- (double) latitude {
	return 46.553666;
}
- (double) longitude {
return -87.40551;
}
@end

Primitive Data Types

As a superset of ANSI C, Objective-C supports its same primitive data types.

int Integral numbers without decimal points
float Numbers with decimal points
double Same as float with twice the accuracy or size
char Store a single character such as the letter ‘a’
BOOL Boolean values with the constants YES or NO

Common Object Data Types

NSObject Root class of the object hierarchy
NSString String value
NSArray Collection of elements, fixed size, may include duplicates
NSMutableArray Variable sized array
NSDictionary Key-value pair collection
NSMutableDictionary Variable sized key-value pair collection
NSSet Unordered collection of distinct elements
NSData Byte buffer
NSURL URL resource

Instance Variables

Class instance variables are declared within a curly braced {} section of the .h file.


// Book.h: Variables declared in a header file
@interface Book : NSObject {
	NSString *title;
	NSString *author;
	int pages;
}
@end

Notice that the object variable declarations are preceded by * symbol. This indicates that the reference is a pointer to an object and is required for all object variable declarations.

Dynamic Typing

Objective-C supports dynamic typing via the id keyword.


NSString *name1 = @”Bob”;
// name2 is a dynamically typed NSString object
id name2 = @”Bob”;
if ([name1 isEqualToString:name2]) {
	// do something
}

Methods

Methods are declared in the .h header file and implemented in the .m implementation file.


// Book.h: Declare methods in the header file
@interface Book : NSObject {
}
- (void) setPages: (int) p;
- (int) pages;
@end
// Book.m: Implement methods in the implementation file
@implementation Book
- (void) setPages: (int) p {
	pages = p;
}
- (int) pages {
	return pages;
}
@end

Method Declaration Syntax

Method Declaration Syntax

Method Invocation Syntax

Method invocations are written using square bracket [] notation.

Method Invocation Syntax

Using Dot Notation Method Invocation

Objective-C 2.0 added the ability to invoke property accessor methods (getters/setters) using “.” notation.


// Using dot notation calls the book instance’s setAuthor method
book.author = @”Herman Melville”;
// equivalent to
[book setAuthor: @”Herman Melville”];

Multi Parameter Methods

Multi-Parameter methods are more verbose than other languages. Each parameter includes both an external name, data type, and a local variable name. The external parameter name becomes a formal part of the method name.


// declare a method with multiple parameters
- (void) addBookWithTitle: (NSString *) aTitle andAuthor: (NSString *)
anAuthor;
// invoke a method with multiple parameters
[self addBookWithTitle: @”Moby Dick” andAuthor: @”Herman Melville”];

Self and Super Properties

Objective-C objects include a self property and a super property. These properties are mutable and can be assigned in an advanced technique called “swizzling”. Most commonly, the self attribute is used to execute a method on the enclosing object.


[self setAuthor: @”Herman Melville”];
// Invoke methods on the “super” property to execute parent class
// behavior. a method that overrides a parent class method will likely call
// the parent class method
- (void) doSomething: (NSString *)value {
	[super doSomething: value];
	// do something derived-class specific
}

Properties using @property and @synthesize

Objective-C 2.0 added property declaration syntax in order to reduce verbose coding of getter and setter methods.


// use of @property declaration for the title variable is equivalent to
// declaring a “setTitle” mutator and “title” accessor method.
@interface Book : NSObject {
	NSString *title;
}
@property (retain, nonatomic) NSString *title;
@end
// use the @synthesize declaration in the .m implementation file
// to automatically implement setter and getter methods.
@implementation Book
@synthesize title, author; //Multiple variables
@synthesize pages; //Single variable
@end

Multiple variables may be included in a single @synthesize declaration. Alternatively, a class may include multiple @synthesize declarations.

@property Attributes

Property attributes specify behaviors of generated getter and setter methods. Attribute declarations are placed in parenthesis () after the @property declaration. The most common values used are (retain, nonatomic). retain indicates that the [retain] method should be called on the newly assigned value object. See the memory management section for further explanation. nonatomic indicates that the assignment operation does not check for thread access protection, which may be necessary in multi-threaded environments. readonly may be specified to indicate the property’s value can not be set.

Object Initialization

Object instances are created in two steps. First, with a call to alloc and second, with a call to init.



// example of 2 step object initialization
Book *book = [[Book alloc] init];
// equivalent to
Book *book2 = [Book alloc];
book2 = [book init];

In order to perform specific object initialization steps, you will often implement the init or an initWith method. Notice the syntax used around the self property in the following example. This is a standard init pattern found in Objective-C. Also notice the method uses a dynamic id return type.


// Event.m: Implementation overrides the “init” method to assign a default
// date value
@implementation Event
- (id) init {
	self = [super init];
	if (self != nil) {
	self.date = [[NSDate alloc] init];
	}
	return self;
}
@end

Class Constructors

Classes often include constructor methods as a convenience. The method type is + to indicate that it is a class (static) method.


// Constructor method declaration
+ (Book *) createBook: (NSString *) aTitle withAuthor: (NSString *)
anAuthor;
// Invoke a class constructor
Book *book2 = [Book createBook: @”Moby Dick” withAuthor: @”Herman
Melville”];

#import Statements

#import statements are required to declare the classes and frameworks used by your class. #import statements can be included at the top of both .h header and .m implementation files.


// import a class
#import “Book.h”
// import a framework
#import <MapKit/MapKit.h>

Control Flow


// basic for loop
for (int x=0; x < 10; x++) {
	NSLog(@”x is: %d”,x);
}
// for-in loop
NSArray *values = [NSArray arrayWithObjects:@”One”,@”Two”,@”Three”,nil];
for(NSString *value in values) {
	// do something
}
// while loop
BOOL condition = YES;
while (condition == YES) {
	// doSomething
}
	// if / else statements
BOOL condition1 = NO;
BOOL condition2 = NO;
if (condition1) {
	// do something
} else if(condition2) {
	// do other thing
} else {
	// do something else
}
	// switch statement
int x = 1;
switch (x) {
	case 1:
		// do something
break;
	case 2:
		// do other thing
		break;
	default:
		break;
}

Strings

Objective-C string literals are prefixed with an “@” symbol (e.g. @”Hello World”). This creates instances of the NSString class; instead of C language CFStrings.


// create a string literal via the “@” symbol
NSString *value = @”foo bar”;
NSString *value2 = [NSString stringWithFormat:@”foo %@”,@”bar”];
// string comparison
if ([value isEqualToString:value2]) {
	// do something
}
NSURL *url = [NSURL URLWithString:@”http://www.google.com”];
NSString *value3 = [NSString stringWithContentsOfURL:url];
NSString *value4 = [NSString stringWithContentsOfFile: @”file.txt”];

NSLog / NSString Formatters

Formatters are character sequences used for variable substitution in strings.


%@ for objects
%d for integers
%f for floats
// Logs “Bob is 10 years old”
NSLog(@”%@ is %d years old”, @”Bob”, 10);

Data Structures

Using NSArray

// Create a fixed size array. Notice that nil termination is required
NSArray *values = [NSArray arrayWithObjects:@”One”,@”Two”,nil];
// Get the array size
int count = [values count];
// Access a value
NSString *value = [values objectAtIndex:0];
// Create a variable sized array
NSMutableArray *values2 = [[NSMutableArray alloc] init];
[values2 addObject:@”One”];

Using NSDictionary

NSDictionary *di = [NSDictionary dictionaryWithObjectsAndKeys:
	@”One”,[NSNumber numberWithInt:1],
	@”Two”,[NSNumber numberWithInt:2],nil];
NSString *one = [di objectForKey: [NSNumber numberWithInt:1]];
NSMutableDictionary *di2 = [[NSMutableDictionary alloc] init];
[di2 setObject:@”One” forKey:[NSNumber numberWithInt:1]];

Memory Management

Objective-C 2.0 includes garbage collection. However, garbage collection is not available for iOS apps. iOS apps must manage memory by following a set of object ownership rules. Each object has a retain count which indicates the number of objects with an ownership interest in that object. Ownership of an object is automatically taken when you call a method beginning with alloc, prefixed with new, or containing copy. Ownership is manually expressed by calling the retain method. You relinquish object ownership by calling release or autorelease.

When an object is created it has a retain count of 1 When the “retain” message is sent to an object, the retain count is incremented by 1 When the “release” message is sent to an object, the retain count is decremented by 1 When the retain count reaches 0, it is deallocated


// alloc sets the retain count to 1
Book *book = [[Book alloc] init];
// do something...
// Release message decrements the retain count,
// Retain count reaches 0. Book will be deallocated
[book release];

dealloc Method

When an object’s retain count reaches 0, it is sent a dealloc message. You will provide implementations of the dealloc method, which will call release on the instances retained variables. Do not call dealloc directly.


// Book.m: Implement release of member variables
- (void) dealloc
{
	[title release];
	[author release];
	[super dealloc];
}

Autorelease Pools

An autorelease pool (NSAutoreleasePool) contains references to objects that have received an autorelease message. When the autorelease pool is deallocated, it sends a release message to all objects in the pool. Using an autorelease pool may simplify memory management; however, it is less fine grained and may allow an application to hold onto more memory than it really needs. Be watchful of which types and size of objects you use with autorelease.


// call autorelease on allocated instance to add it to the autorelease pool
Book *book = [[[Book alloc] init] autorelease];

Categories

Categories are a powerful language feature which allows you to add methods to an existing class without subclassing. Categories are useful to extend the features of existing classes and to split the implementation of large classes into several files. Categories are not subclasses. Generally, do not use methods in a category to extend existing methods except when you wish to globally erase and redefine the original method. Categories can not add instance variables to a class.


// BookPlusPurchaseInfo.h adds purchase related methods to the Book class
#import “Book.h”
@interface Book (PurchaseInfo)
- (NSArray *) findRetailers;
@end
// BookPlusPurchaseInfo.m implements the purchase related methods
#import “BookPlusPurchaseInfo.h”
@implementation Book (PurchaseInfo)
- (NSArray *) findRetailers {
	return [NSArray arrayWithObjects:@”Book World”,nil];
}
@end
// call a method defined in the BookPlusPurchaseInfo category
Book *book = [Book createBook:@”Moby Dick” withAuthor:@”Herman Melvile”];
NSArray *retailers = [book findRetailers];

Selectors

Selectors create method identifiers using the SEL datatype. A value can be assigned to a SEL typed variable via the @selector() directive. Selectors, along with NSObject’s method performSelector: withObject: enable a class to choose the desired message to be invoked at runtime.


// Execute a method using a SEL selector and the performSelector method
id target = [[Book alloc] init];
// Action is a reference to the “doSomething” method
SEL action = @selector(doSomething);
// The message sender need not know the type of target object
// or the message that will be called via the “action” SEL
[target performSelector: action withObject:nil ];

Working With Files

iOS applications have access to files in an app-specific home directory. This directory is a sand-boxed portion of the file system. An app can read and write files within this its own hierarchy, but it can not access any files outside of it.


// Get the path to a iOS App’s “Documents” directory
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject];
// List the contents of a directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *files = [fileManager contentsOfDirectoryAtPath:docDir error:nil];
for (NSString *file in files) {
	NSLog(file);
}
// Create a directory
NSString *subDir = [NSString stringWithFormat:@”%@/MySubDir”,docDir];
[fileManager createDirectoryAtPath:subDir attributes:nil];
// Does the file exist?
NSString *filePath = [NSString stringWithFormat:@”%@/MyFile.txt”,docDir];
BOOL exists = [fileManager fileExistsAtPath: filePath];

Tools

Xcode

The IDE included in the iOS SDK is named Xcode. It is the primary tool in the suite of utilities that ship with the SDK. Xcode has a long history but has been given a dramatic set of feature additions in the modern iPhone and iPad releases, including detection of common user-coded memory leaks and quick-fixing of other syntax and coding mistakes.

Plain text editors and command line Make files can be used to produce iOS applications. However, Xcode offers compelling features such as syntax highlighting and code completion. These features make writing Objective-C in the Xcode IDE a delight and a favorite of developers everywhere.

Xcode

Once the code is in a valid-syntax state, compile it by choosing Build ➡ Build from the menus, or > B. If there are code errors, they will appear as a yellow or red icon in the lower right corner of the IDE. Clicking on the icon will reveal a panel detailing the warnings and errors.

valid-syntax

Deploying an application to the simulator has two simple steps. First, choose the Simulator target from the main Xcode toolbar. Building and Deploying can be done in one seamless step by pressing the Command and Enter keys. The simulator will receive the compiled application and launch it.

simulator

To deploy to an iPhone or iPad, first select Device from the aforementioned toolbar menu. Second, right click on the element beneath the Target node of the Groups and Files tree and choose Get Info. Choose the Properties tab and ensure the Identifier matches the name or pattern you established with Apple for your Provisioning Profile at http://developer.apple.com/iphone

deploy1

Organizer

The Organizer window provides a list of favorite projects, enumerates your attached iOS devices, streams the current device console log to screen and displays details of past crash logs. It can be opened from Xcode via htment29

Organizer window

Debugging

The Xcode platform provides a robust debugger and supplementary mechanisms for stepping through code. Breakpoints are easily set by single clicking in the gutter next to any line of code. A blue arrow indicates a breakpoint is set and active.

debugger

Once a breakpoint is hit, variables can be inspected and the stack examined via the key combination htment The bottommost panel is called the console, and is where all logging output, written via calls such as NSLog(@“My counter is: %d”, myIntCount), is routed.

NSLog

Hot Tip

During the debugging and testing phase of development, activate Zombies to place “markers” in deallocated memory, thereby providing a stack trace in the console if any invalid attempts are made to access the freed memory. This is accomplished in three simple steps:
  • Double-click the name of any node beneath the Executables group of an Xcode project.
  • In the dialog that opens, click the Arguments tab.
  • In the lower “Variables to be set” region, click the + button and create a new variable named “NSZombieEnabled” with its value set to “YES”.

Interface Builder

A tool as powerful as Xcode is Interface Builder. Its name clearly expresses its use for designing Objective-C NIBs and XIBs, which are the binary and XML form of user interface definition files on the Mac, iPhone, and iPad.

NIBs, though graphically designed, actually instantiate the objects declared via the tool when called upon via code. Accordingly, it may help to think of IB (as it is known in the community) primarily as a class-instance designer and property value setter.

New elements can be added to a design canvas in a dragand- drop WYSIWYG approach via the Library panel, which can be accessed via the htment2 key combination. After saving changes, the design’s behavior can be immediately tested through the Simulate Interface command, which can be invoked via htment3 + R.

Simulate Interface command

Simulator

The iPhone and iPad Simulator is another distinct application in the iPhone SDK that communicates and integrates with the Xcode IDE and with Interface Builder. In the Xcode section, we saw how to deploy our application to the Simulator, which both installs the application and launches it.

While the Simulator offers a great desktop testing experience that requires no purchase of hardware, it has a few shortcomings such as the lack of a camera, gyroscope, or GPS facilities. The lack of camera is somewhat mitigated by a supply of several stock photos in the Photo application. The harsh absence of a gyroscope is minimized only by the shake and rotate gestures possible through the Hardware menu. And last, the omission of a true GPS simulator is performed by GPS calls always resolving to 1 Infinite Loop, Cupertino, CA, USA.

The iPhone Simulator offers iPad, iPhone and iPhone 4 simulation modes. The modes are toggled via the Hardware ➡ Device menu.

Device Menu

The Simulator ships with a limited number of core applications; namely, the Photos, Settings, Camera, Contacts and Safari programs. These are the applications that offer API connectivity from the source code of your application. For a broader set of programs and more realistic mobile horsepower CPUs, testing on an actual iOS device is critical. Commercial apps that you’ve purchased from the iTunes App Store cannot be installed on the Simulator for DRM reasons and the vast difference in CPU architecture of x86 desktops and ARM mobile devices.

Xcode Keyboard Shortcuts

Common XCode Shortcuts
Htment4
Htment5 toggle between .h and .m file
Htment6 quickly open a file via search dialog
Htment7 build
Htment8 build and run
Htment9 clean the build
Htment20 go to console view
Htment21 go to project view
Htment22 show / hide upper right pane
Htment23 show / hide all but the active document window
Htment24 while in file editor - show / navigate list of recent files
Htment25 while in file editor - show / navigate list of class methods
Htment26 build and debug
Htment27 debugger continue
Htment28 open quick documentation for class at mouse cursor

Unit Testing and Code Coverage

Currently, the unit testing tools for Objective-C are less mature than those of other languages. XCode currently includes the OCUnit unit testing framework. OCUnit tests are coded similarly to those of xUnit tests in languages such as Java. The Google Toolbox for Mac provides several useful enhancements to OCUnit and is the testing solution currently recommended by ThoughtWorks for the iOS platform. Complementing OCUnit is OCMock, an Objective-C implementation of mock objects. CoverStory can be used in concert with OCUnit and OCMock to check the code coverage of your tests.

Resources

SDK

Apple Developer Programs - http://developer.apple.com/
iOS SDK - http://developer.apple.com/iphone/index.action

Testing

Google Toolbox for Mac - http://code.google.com/p/google-toolbox-for-mac/
OCMock - http://www.mulle-kybernetik.com/software/OCMock/
CoverStory - http://code.google.com/p/coverstory/

Blogs, Videos, Books

WWDC 2010 Session Videos - http://developer.apple.com/videos/wwdc/2010/ Objective-C Basics -

http://en.wikibooks.org/wiki/Cocoa_Programming/Objective-C_basics iPhone Development Wiki - http://iphonedevwiki.net/index.php/Main_Page The Objective-C Programming Language -

http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/ Bookmarks - http://delicious.com/matthew.mccullough/objectivec

About The Authors

Photo of author Ben Ellingson

Ben Ellingson

Ben Ellingson is a software engineer and consultant. He is the creator of nofluffjuststuff.com, many related No Fluff Just Stuff websites and mobile applications. During Ben’s 13 years of development experience, he has helped create systems for conference management, video-on-demand, and online travel. You can keep up with Ben’s work at http://benellingson.blogspot.com and http://twitter.com/benellingson.

Photo of author Matthew McCullough

Matthew McCullough

Matthew McCullough is an energetic 15 year veteran of enterprise software development, open source education, and co-founder of Ambient Ideas, LLC, a Denver, Colorado, USA consultancy. Matthew is a published author, open source creator, speaker at over 100 conferences, and author of three of the top 10 Refcardz of all time. He writes frequently on software and presenting at his blog: http://ambientideas.com/blog.

Recommended Book

Objective-C

The second edition of this book thoroughly covers the latest version of the language, Objective-C 2.0. And it shows not only how to take advantage of the Foundation framework’s rich built-in library of classes but also how to use the iPhone SDK to develop programs designed for the iPhone/iPad platform.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Upgrading to IntelliJ IDEA 8.1? Get this cheat sheet!

Upgrading to IntelliJ 8.1? Click here to get a free PDF and see what you can do with IntelliJ! IntelliJ is a commercial Java IDE.

2 replies - 7273 views - 05/04/09 by Lyndsey Clevesy in Announcements