Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Application Development

357 Articles
article-image-article-creating-holiday-request-infopath-form-publishing-form-library
Packt
02 Nov 2011
3 min read
Save for later

Creating a holiday request InfoPath form and publishing it to a form library

Packt
02 Nov 2011
3 min read
(For more resources on Microsoft Sharepoint, see here.) Creating a holiday request InfoPath form and publishing it to a form library InfoPath forms are capable of containing repeating data, optional fields, and presenting different views to different users. To access the full power of InfoPath, you will want to create a custom form and publish it to a SharePoint form library. In this recipe we learn how to create a holiday request form and publish it to SharePoint. Getting ready This recipe works for: SharePoint 2010 Enterprise Edition Office 365 (SharePoint Online) You will need a SharePoint site where you want to create an InfoPath form. This recipe creates a holiday request form for illustration. You will need the Design or Full Control permission level to run this recipe. You will need InfoPath Designer 2010 installed on your client machine. How to do it... Open the Microsoft InfoPath Designer 2010 on your computer. The backstage view is displayed. Double click the on SharePoint Form Library button. A new blank form opens. Change the form title to Holiday Request. Change the first subheading to Employee Details. Place the cursor on the first Add control cell in the Employee Details table. Click on Text Box in the Controls section of the Home ribbon. A new textbox will be inserted into the form (field1) and a new field is added to the forms data source (Fields view). Double on click field1 in the Fields view to open the properties dialog. Rename the field to FirstName and click on the OK button. Repeat steps 4 and 5 to add textboxes for LastName, EmailAddress, and Department. Add labels to the form for each of the textboxes that you have added. Highlight the last row in the Employee Details table and delete it. Rename the next section in the form Holiday Details. Add labels for Start Date and End Date. Expand the Controls section in the ribbon. Select the Date Picker control. Add date controls for StartDate and EndDate to the form. Click on the File tab to access the backstage view. Click on the Publish button. The Publish options are displayed. Click on the SharePoint Server button. You will be prompted to first save your form template. Enter the filename holidayrequest.xsn and click on the Save button. The Publishing Wizard will open. Enter the URL of the SharePoint site where you want to publish your form and click on the Next button. Tick the Enable this form to be filled out using a browser. Select the Form Library option. Click on the Next button. Select the Create a new form library option. Click on the Next button. Name the new library Holiday Requests. Click on the Next button. To promote data items in the form to SharePoint list columns, click on the Add button. Select the FirstName column and click on the OK button. Repeat for the LastName, EmailAddress, Department, StartDate, and EndDate fields. Click on the Publish button. The form is published to SharePoint. Click on the Open this form in a browser link. The InfoPath form opens in the web browser. Enter some data to test the form and click on the Save button. You will be prompted for a filename for your form. Enter request1 and click on Save. Your holiday request is saved to the form library. Click on the Close button.
Read more
  • 0
  • 0
  • 1525

article-image-microsoft-sharepoint-recipes-automating-business-processes
Packt
01 Nov 2011
5 min read
Save for later

Microsoft SharePoint: Recipes for Automating Business Processes

Packt
01 Nov 2011
5 min read
(For more resources on Microsoft Sharepoint, see here.) Creating an InfoPath Form for a SharePoint List You can replace the default SharePoint list forms with an InfoPath form on any SharePoint list. This gives you much more flexibility and control over how you edit and display the data. Getting ready This recipe works for: SharePoint 2010 Enterprise Edition Office 365 (SharePoint Online) You will need a SharePoint List where you want to create an InfoPath form. You will need the Design or Full Control permission level to run this recipe. You will need InfoPath Designer 2010 installed on your client machine. This recipe uses a SharePoint 2010 Team Site with a contacts list added for illustration. How to do it... Open Internet Explorer and navigate to your SharePoint 2010 Team Site. Select the Contacts list from the Quick Launch menu. Select the List tab of the List Tools ribbon. Select the Customize Form icon. InfoPath Form Designer 2010 will open displaying an auto-generated InfoPath form for the contacts list. (Move the mouse over the image to enlarge.) Select the File tab in the ribbon to access the backstage view. Select the Quick Publish button. The InfoPath form is now published and replaces the default form on the SharePoint list. Click on the OK button in the Publish dialog displayed. How it works... When you create a SharePoint list, SharePoint automatically creates default edit, display, and new forms for you. While these forms are functional, they are somewhat limited in the presentation and customization options that they provide. If you have SharePoint Server Enterprise Edition installed, you replace these forms with an InfoPath 2010 form. InfoPath forms offer you many more options for creating and controlling how you edit and display your list data. This recipe demonstrates the mechanics of replacing the forms; once you have done this a whole range of new customization options is available to you. Every time you want to edit the form, just repeat this procedure. One gotcha that you may run into is if you have added a taxonomy field (that is, one that shows a term set) to your list. Unfortunately these fields are not supported in the current InfoPath release, and you will receive an error when you try to edit the list form. It's a big omission from the current version of SharePoint, and not one that there is an obvious workaround for. There's more... Having run this recipe, you may be left thinking "so what?" However, once you have created an InfoPath form for your list, you have all the power of the InfoPath form designer at your disposal. You can now remove columns, add graphics, text, and business rules to the form to fit your needs. Techniques for performing these customizations are described in the following sections. Removing columns It's quite common to have columns in a list that you don't want the user to fill in. When you have an InfoPath attached to the list, simply open the form, delete the field that you don't want the users to edit, and republish. If you have used the table-editing tools in Microsoft Word, you will find the InfoPath experience very familiar. The following screenshot shows the Attachments row being deleted from the form: It's important to realize that you are only removing columns from the form, not from the underlying list itself. Also, if you add a new column to your list after you have customized the form, SharePoint won't automatically add the new column to your form for you. It will prompt you that there are new columns available the next time you open the InfoPath form designer. Click on Yes to update the fields list. You can then select the new fields that you require and drag-and-drop them into the form. Adding images, explanatory text, and tooltips Normal SharePoint list forms are a bit dull. Now that you have an InfoPath form, you can start to brighten things up. You can change colors, fonts, add images, text, and tooltips. To add an image, use the Picture button on the Insert ribbon. Then simply browse to the picture that you want to add and republish the form. Adding text to your form can help guide your users when they are filling it in. You can add the text directly to the form or you can add it to the controls ScreenTip. The ScreenTip text will only be shown when the user's mouse hovers over the control in the browser. This helps your users without cluttering up your form. Adding rules to validate data InfoPath forms allow you to add rules. Rules can be added to the form to validate data, apply custom formatting, or perform custom actions. You can use actions to set field values, switch views, submit form data, and so on. InfoPath form rules are the way to implement and enforce custom business logic in your forms, so I advise you to invest some time learning how to build them up and exploring what they can do. The following screenshot shows how to apply InfoPath built in e-mail validation rule to the e-mail textbox field. This rule uses a regular expression to ensure that the value entered is in a valid e-mail format, and shows a validation error if it is not. InfoPath Designer versus InfoPath Filler You may notice two Microsoft Office InfoPath programs on your computer, Microsoft InfoPath Designer 2010 and Microsoft InfoPath Filler 2010. When creating forms for use in SharePoint, InfoPath Designer 2010 is the application you need to use. InfoPath is a standalone forms technology, while InfoPath Filler 2010 exists to allow users to fill in InfoPath forms without the use of SharePoint. That isn't something we cover in this book, though it's useful to know that you can use this if you need to.
Read more
  • 0
  • 0
  • 1450

article-image-introducing-xcode-tools-iphone-development
Packt
28 Sep 2011
9 min read
Save for later

Introducing Xcode Tools for iPhone Development

Packt
28 Sep 2011
9 min read
  (For more resources on iPhone Development, see here.) There is a lot of fun stuff to cover, so let's get started. Development using the Xcode Tools If you are running Mac OSX 10.5, chances are your machine is already running Xcode. These are located within the /Developer/Applications folder. Apple also makes this freely available through the Apple Developer Connection at http://developer.apple.com/. The iPhone SDK includes a suite of development tools to assist you with your development of your iPhone, and other iOS device applications. We describe these in the following table. iPhone SDK Core Components COMPONENT DESCRIPTION Xcode This is the main Integrated Development Environment (IDE) that enables you to manage, edit, and debug your projects. DashCode This enables you to develop web-based iPhone and iPad applications, and Dashboard widgets. iPhone Simulator The iPhone Simulator is a Cocoa-based application, which provides a software simulator to simulate an iPhone or iPad on your Mac OSX. Interface Builder   Instruments These are the Analysis tools, which help you optimize your applications and monitor for memory leaks in real-time. The Xcode tools require an Intel-based Mac running Mac OS X version 10.6.4 or later in order to function correctly. Inside Xcode, Cocoa, and Objective-C Xcode 4 is a complete toolset for building Mac OSX (Cocoa-Based) and iOS applications. The new single-windowed development interface has been redesigned to be a lot easier and even more helpful to use than it has been in previous releases. It can now also identify mistakes in both syntax and logical errors, and will even fix your code for you. It provides you with the tools to enable you to speed up your development process, therefore becoming more productive. It also takes care of the deployment of both your Mac OSX and iOS applications. The Integrated Development Interface (IDE) allows you to do the following: Create and manage projects, including specifying platforms, target requirements, dependencies, and build configurations. Supports Syntax Colouring and automatic indenting of code. Enables you to navigate and search through the components of a project, including header files and documentation. Enables you to Build and Run your project. Enables you to debug your project locally, run within the iOS simulator, or remotely, within a graphical source-level debugger. Xcode incorporates many new features and improvements, apart from the redesigned user interface; it features a new and improved LLVM (Low Level Virtual Machine) debugger, which has been supercharged to run 3 times faster and 2.5 times more efficient. This new compiler is the next generation compiler technology designed for high-performance projects and completely supports C, Objective-c, and now C++. It is also incorporated into the Xcode IDE and compiles twice as fast and quickly as GCC and your applications will run faster. The following list includes the many improvements made to this release. The interface has been completely redesigned and features a single-window integrated development interface. Interface Builder has now been fully integrated within the Xcode development IDE. Code Assistant opens in a second window that shows you the file that you are working on, and can automatically find and open the corresponding header file(s). Fix-it checks the syntax of your code and validates symbol names as you type. It will even highlight any errors that it finds and will even fix them for you. The new Version Editor works with GIT (Free Open-Source) version control software or Subversion. This will show you the files entire SCM (software configuration management) history and will even compare any two versions of the file. The new LLVM 2.0 compiler includes full support for C, Objective-C, and C++ The LLDB debugger has now been improved to be even faster, it uses less memory than the GDB debugging engine. The new Xcode 4 development IDE now lets you work on several interdependent projects within the same window. It automatically determines its dependencies so that it builds the projects in the right order. Xcode allows you to customize an unlimited number of build and debugging tools, and executable packaging. It supports several source-code management tools, namely, CVS "Version control software which is an important component of the Source Configuration Management (SCM)" and Subversion, which allows you to add files to a repository, commit changes, get updated versions and compare versions using the Version Editor tool. The iPhone Simulator The iPhone Simulator is a very useful tool that enables you to test your applications without using your actual device, whether this being your iPhone or any other iOS device. You do not need to launch this application manually, as this is done when you Build and run your application within the Xcode Integrated Development Environment (IDE). Xcode installs your application on the iPhone Simulator for you automatically. The iPhone Simulator also has the capability of simulating different versions of the iPhone OS, and this can become extremely useful if your application needs to be installed on different iOS platforms, as well as testing and debugging errors reported in your application when run under different versions of the iOS. While the iPhone Simulator acts as a good test bed for your applications, it is recommended to test your application on the actual device, rather than relying on the iPhone Simulator for testing. The iPhone Simulator can be found at the following location /Developer/Platforms/iPhoneSimulator.Platform/Developer/Applications. Layers of the iOS Architecture According to Apple, they describe the set of frameworks and technologies that are currently implemented within the iOS operating system as a series of layers. Each of these layers is made up of a variety of different frameworks that can be used and incorporated into your applications. Layers of the iOS Architecture We shall now go into detail and explain each of the different layers of the iOS Architecture; this will give you a better understanding of what is covered within each of the Core layers. The Core OS Layer This is the bottom layer of the hierarchy and is responsible for the foundation of the Operating system, which the other layers sit on top of. This important layer is in charge of managing memory - allocating and releasing of memory once it has finished with it, taking care of file system tasks, handles networking, and other Operating System tasks. It also interacts directly with the hardware. The Core OS Layer consists of the following components: COMPONENT NAME COMPONENT NAME OS X Kernel Mach 3.0 BSD Sockets Security Power Management Keychain Certificates File System Bonjour The Core Services Layer The Core Services layer provides an abstraction over the services provided in the Core OS layer. It provides fundamental access to the iPhone OS services. The Core Services Layer consists of the following components: COMPONENT NAME COMPONENT NAME Collections Address Book Networking File Access SQLite Core Location Net Services Threading Preferences URL Utilities The Media Layer The Media Layer provides Multimedia services that you can use within your iPhone, and other iOS devices. The Media Layer is made up of the following components: COMPONENT NAME COMPONENT NAME Core Audio OpenGL Audio Mixing Audio Recording Video Playback Image Formats: JPG, PNG and TIFF PDF Quartz Core Animations OpenGL ES The Cocoa-Touch Layer The Cocoa-Touch layer provides an abstraction layer to expose the various libraries for programming the iPhone, and other IOS devices. You probably can understand why Cocoa-Touch is located at the top of the hierarchy due to its support for Multi-Touch capabilities. The Cocoa-Touch Layer is made up of the following components: COMPONENT NAME COMPONENT NAME Cocoa-Touch Layer Multi-Touch Events Multi-Touch Controls Accelerometer/Gyroscope View Hierarchy Localization/Geographical Alerts Web Views People Picker Image Picker Controllers   Understanding Cocoa, the language of the Mac Cocoa is defined as the development framework used for the development of most native Mac OSX applications. A good example of a Cocoa related application is Mail or Text Edit. This framework consists of a collection of shared object code libraries known as the Cocoa frameworks. It consists of a runtime system and a development environment. These set of frameworks provide you with a consistent and optimized set of prebuilt code modules that will speed up your development process. Cocoa provides you with a rich-layer of functionality, as well as a comprehensive object-oriented like structure and APIs on which you can build your applications. Cocoa uses the Model-View-Controller (MVC) design pattern. What are Design Patterns? Design Patterns represent and handle specific solutions to problems that arise when developing software within a particular context. These can be either a description or a template, on how to go about to solve a problem in a variety of different situations. What is the difference between Cocoa and Cocoa-Touch? Cocoa-Touch is the programming language framework that drives user interaction on iOS. It consists and uses technology derived from the cocoa framework and was redesigned to handle multi-touch capabilities. The power of the iPhone and its User Interface are available to developers throughout the Cocoa-Touch frameworks. Cocoa-Touch is built upon the Model-View-Controller structure; it provides a solid stable foundation for creating mind blowing applications. Using the Interface builder developer tool, developers will find it both very easy and fun to use the new drag-and-drop method when designing their next great masterpiece application on iOS. The Model-View-Controller The Model-View-Controller (or MVC) comprises a logical way of dividing up the code that makes up the GUI (Graphical User Interface) of an application. Object-Oriented applications like Java and .Net have adopted the MVC design pattern. The MVC model comprises three distinctive categories:Model : This part defines your application's underlying data engine. It is responsible for maintaining the integrity of that data. View : This part defines the user interface for your application and has no explicit knowledge of the origin of data displayed in that interface. It is made up of Windows, controls, and other elements that the user can see and interact with. Controller : This part acts as a bridge between the model and view and facilitates updates between them. It binds the Model and View together and the application logic decides how to handle the user's inputs.  
Read more
  • 0
  • 0
  • 2516

article-image-microsoft-lightswitch-querying-multiple-entities
Packt
16 Sep 2011
4 min read
Save for later

Microsoft LightSwitch: Querying Multiple Entities

Packt
16 Sep 2011
4 min read
  (For more resources on this topic, see here.)   Microsoft LightSwitch makes it easy to query multiple entities and with queries you can fine tune the results using multiple parameters. In the following, we will be considering the Orders and the Shippers tables from the Northwind database shown next: What we would like to achieve is to fashion a query in LightSwitch which finds orders later than a specified date (OrderDate) carried by a specified shipping company (CompanyName). In the previous example, we created a single parameter and here we extend it to two parameters, OrderDate and CompanyName. The following stored procedure in SQL Server 2008 would produce the rows that satisfy the above conditions: Use NorthwindGoCreate Procedure ByDateAndShprName @ordDate datetime, @shprName nvarchar(30)asSELECT Orders.OrderID, Orders.CustomerID, Orders.EmployeeID,Orders.OrderDate, Orders.RequiredDate, Orders.ShippedDate,Orders.ShipVia, Orders.Freight, Orders.ShipName, Orders.ShipAddress, Shippers.ShipperID,Shippers.CompanyName, Shippers.PhoneFROM Orders INNER JOIN Shippers ON Orders.ShipVia = Shippers.ShipperIDwhere Orders.OrderDate > @OrdDate and Shippers.CompanyName=@shprName The stored procedure ByDateAndShprName can be executed by providing the two parameters (variables), @OrdDate and @shprName, as shown below. Exec ByDateAndShprName '5/1/1998 12:00:00','United Package' The result returned by the previous command is shown next copied from the SQL Server Management Studio (only first few columns are shown): The same result can be achieved in LightSwitch using two parameters after attaching these two tables to the LightSwitch application. As the details of creating screens and queries have been described in detail, only some details specific to the present section are described. Note that the mm-dd-yyyy appears in the result reversed yyyy-mm-dd. Create a Microsoft LightSwitch application (VB or C#). Here project Using Combo6 was created. Attach a database using SQL Server 2008 Express and bring the two tables, Orders and Shippers, to create two entities, Order and Shipper, as shown in the next screenshot: Create a query as shown in the next image: Here the query is called ByDate. Note that the CompanyName in the Shippers table is distinct. The completed query with two parameters appears as shown: Create a new screen (click on Add Screen in the query designer shown in the previous screenshot) and choose the Editable Grid Screen template. Here the screen created is named EditableGridByDate. Click on Add Data Item… and add the query NorthwindData.ByDate. The designer changes as shown next: Click on OrderDate parameter on the left-hand side navigation of the screen and drag and drop it just below the Screen Command Bar as shown. In a similar manner, drag and drop the query parameter CompanyName below the OrderDate of the earlier step. This will display as two controls for two parameters on the screen. Hold with mouse, drag and drop ByDate below the CompanyName you added in the previous step. The completed screen design should appear as shown (some fields are not shown in the display): The previous image shows two parameters. The DataGrid rows show the rows returned by the query. As is, this screen would return no data if the parameters were not specified. The OrderDate defaults to Current Date. Click on F5 to display the screen as shown: Enter the date 5/1/1998 directly. Enter United Package in the CompanyName textbox and click on the Refresh button on the previous screen. The screen is displayed as shown here: The above screen is an editable screen and you should be able to add, delete, and edit the fields and they should update the fields in the backend database when you save the data. Also note that the LightSwitch application returned 11 rows of data while the stored procedure in SQL Server returned 10 rows. This may look weird but SQL Server date time refers to PM but Microsoft LightSwitch order date is datetime data type with AM. Entering PM instead of AM returns the correct number of rows.  
Read more
  • 0
  • 0
  • 2563

article-image-microsoft-lightswitch-querying-and-filtering-data
Packt
16 Sep 2011
5 min read
Save for later

Microsoft LightSwitch: Querying and Filtering Data

Packt
16 Sep 2011
5 min read
  (For more resources on this topic, see here.)   Querying in LightSwitch The following figure is based on the one you may review on the link mentioned earlier and schematically summarizes the architectural details: Each entity set has a default All and Single as shown in the entity Category. All entity sets have a Save operation that saves the changes. As defined, the entity sets are queryable and therefore query operations on these sets are allowed and supported. A query (query operation) requests an entity set(s) with optional filtering and sorting as shown, for example, in a simple, filtered, and sorted query on the Category entity. Queries can be parameterized with one or more parameters returning single or multiple results (result sets). In addition to the defaults (for example, Category*(SELECT All) and Category), additional filtering and sorting predicates can be defined. Although queries are based on LINQ, all of the IQueryable LINQ operations are not supported. The query passes through the following steps (the pipeline) before the results are returned. Pre-processing CanExecute—called to determine if this operation may be called or not Executing—called before the query is processed Pre-process query expression—builds up the final query expression Execution—LightSwitch passes the query expression to the data provider for execution Post-processing Executed—after the query is processed but before returning the results ExecuteFailed—if the query operation failed   Querying a Single Entity We will start off creating a Visual Studio LightSwitch project LSQueries6 using the Visual Basic Template as shown (the same can be carried out with a C# template). We will attach this application to the SQL Server Express server's Northwind database and bring in the Products (table) entity. We will create a screen EditableProductList which brings up all the data in the Products entity as shown in the previous screenshot. The above screen was created using the Editable Grid Screen template as shown next with the source of data being the Products entity. We see that the EditableProductList screen is displaying all columns including those discontinued items and it is editable as seen by the controls on the displayed screen. This is equivalent to the SQL query, Select * from Products as far as display is concerned.   Filtering and sorting the data Often you do not need all the columns but only a few columns of importance for your immediate needs, which besides being sufficient, enormously reduces the cost of running a query. What do you do to achieve this? Of course, you filter the data by posing a query to the entity. Let us now say, we want products listing ProductID, ProductName excluding the discontinued items. We also need the list sorted. In SQL Syntax, this reduces to: SELECT [Product List].ProductID, [Product List].ProductNameFROM Products AS [Product List]WHERE ((([Product List].Discontinued) =0))ORDER BY [Product List].ProductName; This is a typical filtering of data followed by sorting the filtered data. Filtering the data In LightSwitch, this filtering is carried out as shown in the following steps: Click on Query menu item in the LSQueries Designer as shown: The Designer (short for Query Designer) pops-up as shown and the following changes are made in the IDE: A default Query1 gets added to the Products entity on which it is based as shown; the Query1 property window is displayed and the Query Designer window is displayed. Query1 can be renamed in its Properties window (this will be renamed as Product List). The query target is the Products table and the return type is Product. As you can see Microsoft has provided all the necessary basic querying in this designer. If the query has to be changed to something more complicated, the Edit Additional Query Code link can be clicked to access the ProductListDataService as shown: Well, this is not a SQL Query but a LINQ Query working in the IDE. We know that entities are not just for relational data and this makes perfect sense because of the known advantages of LINQ for queries (review the following link: http://msdn.microsoft.com/en-us/library/bb425822.aspx). One of those main advantages is that you can write the query inVB or C#, and the DataContext, the main player takes it to SQL and runs queries that SQL Databases understand. It's more like a language translation for queries with many more advantages than the one mentioned. Hover over Add Filter to review what this will do as shown: This control will add a new filter condition. Note that Query1 has been renamed (right-click on Query1 and choose Rename) to ProductList. Click on the Add Filter button. The Filter area changes to display the following: The first field in the entity will come up by default as shown for the filtered field for the 'Where' clause. The GUI is helping to build up "Where CategoryID = ". However, as you can see from the composite screenshot (four screens were integrated to create this screenshot) built from using all the drop-down options that you can indeed filter any of the columns and choose any of the built-in criteria. Depending on the choice, you can also add parameter(s) with this UI. For the particular SQL Query we started with, choose the drop-down as shown. Notice that LightSwitch was intelligent enough to get the right data type of value for the Boolean field Discontinued. You also have an icon (in red, left of Where) to click on should you desire to delete the query. Add a Search Data Screen using the previous query as the source by providing the following information to the screen designer (associating the ProductList query for the Screen Data). This screen when displayed shows all products not discontinued as shown. The Discontinued column has been dragged to the position shown in the displayed screen.  
Read more
  • 0
  • 0
  • 6556

article-image-xcode-4-ios-displaying-notification-messages
Packt
30 Aug 2011
8 min read
Save for later

Xcode 4 ios: Displaying Notification Messages

Packt
30 Aug 2011
8 min read
  Xcode 4 iOS Development Beginner's Guide Use the powerful Xcode 4 suite of tools to build applications for the iPhone and iPad from scratch  The iPhone provides developers with many ways in which they can add informative messages to their applications to alert the user. We will be looking at the various types of notification methods, ranging from alerts, activity indicators, audio sounds, and vibrations. Exploring the notification methods The applications on the iPhone are user-centric, meaning that they don't operate without a user interface and don't perform any background operations. These types of applications enable users to work with data, play games, or communicate with other users. Despite these, at some point an application will need to communicate with the user. This can be as simple as a warning message, or providing feedback or even asking the user to provide some information. The iPhone and Cocoa-Touch use three special methods to gain your attention and are explained below: CLASS DESCRIPTION UIAlertView This class creates a simple modal alert window that presents the user with a message and a few options. Modal elements require the user to interact with them before they can proceed. These types of elements are displayed (layered) on top of other windows and block the underlying objects until the user responds to one of the actions presented. UIActionSheet These types of classes are similar to the UIAlertView class, except that they can be associated with a given view, tab bar, or toolbar and become animated when it appears on the screen. Action Sheets do not have an associated message property; they contain a single title property. System Sound Services This enables playback and vibration and supports various file formats (CAF, AIF, and WAV Files) and makes use of the AudioToolBox framework.   Generating alerts There is no doubt that you will need to incorporate alerts into your applications. These can be very useful to inform the user of when the application is running, and can be a simple message such as memory running low, or that an application or internal error has occurred. We can notify the user in a number of ways using the UIAlertView class, and it can be used to display a simple modal message or gather information from the user. Time for action – creating the GetUsersAttention application Before we can proceed with creating our GetUsersAttention application, we must first launch the Xcode development environment. Select the View-based application template from the project template dialog box. Ensure that you have selected iPhone from under the Device Family dropdown, as the type of view to create. Next, you will need to provide a name for your project. Enter GetUsersAttention and then choose a location where you would like to save the project. Once your project has been created, you will be presented with the Xcode interface, along with the project files that the template created for you within the Project Navigator Window. What just happened? In this section, we looked at the steps involved in creating a View-based application for our GetUsersAttention application. In the next section, we will take a look at how we can add the AudioToolbox Framework into our project to incorporate sound.   Time for action – adding the AudioToolbox Framework to our application Now that we have created our project, we need to add the AudioToolbox Framework to our project. This is an important framework which will provide us the ability to play sound and vibrate the phone. To add the new frameworks or additional frameworks into your project, select the Project Navigator Group, and then follow these simple steps as outlined below: Select your Project within the Project Navigator Window. Then select your project target from under the TARGETS group. Select the Build Phases tab. Expand the Link Library with Libraries disclosure triangle. Then finally, use the + button to add the library that you want to add; if you want to remove a framework, highlight it from the group and click on the - button. You can also search for the framework if you can't find it in the list shown. If you are still confused on how to go about adding these frameworks, refer to the following image, which highlights what parts you need to select (highlighted by a red rectangle): (Move the mouse over the image to enlarge.) What just happened? In the above section, we looked at how we are able to add frameworks to our application. We looked at the differences between the MediaPlayer and AudioToolbox frameworks, and the limitations of the two. Adding frameworks to your application allows you to extend your application and utilise those features in your application to avoid reinventing the wheel. When you add frameworks to your application, the system loads them into memory as needed and shares the one copy of the resource among all applications whenever possible. Now that we have added the AudioToolbox.framework to our project, our next step is to start creating our user interface. In the next section, we will be taking a look at how we start to build our user interface and create events. Building our user interface User interfaces provide a great way to communicate with the user in order to either obtain information or to display notifications. A good interface is one that provides a good consistent flow throughout your application as you navigate from screen to screen. This involves considering the screen size of your view. In the next section, we look at how to add some controls to our view to build our interface. To obtain further information about what constitutes a good user interface, Apple provides these iOS Human Interface Guidelines which can be obtained at the following location: http://developer.apple.com/library/ios/documentation/userexperience/conceptual/mobilehig/MobileHIG.pdf.   Time for action – adding controls to our View We will be adding five button (UIButton) controls which will be handling our actions to display alerts and Action Sheets, playing sounds, and vibrating the iPhone. From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Show Activity Indicator". From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Display Alert Dialog". From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Display Action Sheet". From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Play Alert Sound". From the Object Library, select and drag a (UIButton) Round Rect Button control onto our view. Modify the Object Attributes of the Round Rect Button control and set its title to read "Vibrate iPhone". If you have followed everything correctly, your view should look something like the following screenshot. If it doesn't look quite the same, feel free to adjust yours: What just happened? In the above section, we looked at how we are able to use the Object Library to add controls to our view and customize their properties in order to build our user interface. In the next section, we will take a look at how to create events to respond to button events. Creating events Now that we have created our user interface, we need to create the events that will respond when we click on each of the buttons. We first need to create an instance of our UIAlertView class, called baseAlert, which will be used by our Show Activity indicator event and will be used to dismiss the activity after a period of time has lapsed. Open the GetUsersAttentionViewController.h interface file and add the following highlighted code as shown in the code snippet below: #import <UIKit/UIKit.h> @interface GetUsersAttentionViewController : UIViewController <UIAlertViewDelegate, UIActionSheetDelegate>{ UIAlertView *baseAlert; } @end We could have declared this within our GetUsersAttentionViewController.m implementation file, but I prefer to declare it in this class as it can be referenced throughout your application. You will notice from the code snippet above that we have made reference to two delegate protocols within our GetUsersAttentionViewController.h interface file; this enables us to capture and respond to the button event presses used by our Action Sheet and Alert Views. This will become apparent when we start adding the code events for our Alert Views and Action Sheets.  
Read more
  • 0
  • 0
  • 1900
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-getting-started-netbeans
Packt
04 Aug 2011
6 min read
Save for later

Getting Started with NetBeans

Packt
04 Aug 2011
6 min read
Java EE 6 Development with NetBeans 7 Develop professional enterprise Java EE applications quickly and easily with this popular IDE In addition to being an IDE, NetBeans is also a platform. Developers can use NetBeans' APIs to create both NetBeans plugins and standalone applications. For a brief history of Netbeans, see http://netbeans.org/about/history.html. Although the NetBeans IDE supports several programming languages, because of its roots as a Java only IDE it is a lot more popular with this language. As a Java IDE, NetBeans has built-in support for Java SE (Standard Edition) applications, which typically run in the user's desktop or notebook computer; Java ME (Micro Edition), which typically runs in small devices such as cell phones or PDAs; and for Java EE (Enterprise Edition) applications, which typically run on "big iron" servers and can support thousands of concurrent users.   Obtaining NetBeans NetBeans can be obtained by downloading it from http://www.netbeans.org. To download NetBeans, we need to click on the button labeled Download Free NetBeans IDE 7.0 (the exact name of the button may vary depending on the current version of NetBeans). Clicking on this button will take us to a page displaying all of NetBeans download bundles. NetBeans download includes different NetBeans bundles that provide different levels of functionality. The following table summarizes the different available NetBeans bundles and describes the functionality they provide: NetBeans bundleDescriptionJava SEAllows development of Java desktop applications.Java EEAllows development of Java Standard Edition (typically desktop applications), and Java Enterprise Edition (enterprise application running on "big iron" servers) applications.C/C++Allows development of applications written in the C or C++ languages.PHPAllows development of web applications using the popular open source PHP programming language.AllIncludes functionality of all NetBeans bundles. To follow the examples, either the Java EE or the All bundle is needed. The screenshots were taken with the Java EE bundle. NetBeans may look slightly different if the All Pack is used, particularly, some additional menu items may be seen. The following platforms are officially supported: Windows 7/Vista/XP/2000 Linux x86 Linux x64 Solaris x86 Solaris x64 Mac OS X Additionally, NetBeans can be executed in any platform containing Java 6 or newer. To download a version of NetBeans to be executed in one of these platforms, an OS independent version of NetBeans is available for download. Although the OS independent version of NetBeans can be executed in all of the supported platforms, it is recommended to obtain the platform-specific version of NetBeans for your platform. The NetBeans download page should detect the operating system being used to access it, and the appropriate platform should be selected by default. If this is not the case, or if you are downloading NetBeans with the intention of installing it in another workstation on another platform, the correct platform can be selected from the drop down labeled, appropriately enough, Platform. Once the correct platform has been selected, we need to click on the appropriate Download button for the NetBeans bundle we wish to install. For Java EE development, we need either the Java EE or the All bundle. NetBeans will then be downloaded to a directory of our choice. Java EE applications need to be deployed to an application server. Several application servers exist in the market, both the Java EE and the All NetBeans bundles come with GlassFish and Tomcat bundled. Tomcat is a popular open source servlet container, it can be used to deploy applications using the Servlets, JSP and JSF, however it does not support other Java EE technologies such as EJBs or JPA. GlassFish is a 100 percent Java EE-compliant application server. We will be using the bundled GlassFish application server to deploy and execute our examples.   Installing NetBeans NetBeans requires a Java Development Kit (JDK) version 6.0 or newer to be available before it can be installed. NetBeans installation varies slightly between the supported platforms. In the following few sections we explain how to install NetBeans on each supported platform. Microsoft Windows For Microsoft Windows platforms, NetBeans is downloaded as an executable file named something like netbeans-7.0-ml-java-windows.exe, (exact name depends on the version of NetBeans and the NetBeans bundle that was selected for download). To install NetBeans on Windows platforms, simply navigate to the folder where NetBeans was downloaded and double-click on the executable file. Mac OS X For Mac OS X, the downloaded file is called something like netbeans-7.0-ml-javamacosx.dmg (exact name depends on the NetBeans version and the NetBeans bundle that was selected for download). In order to install NetBeans, navigate to the location where the file was downloaded and double-click on it. The Mac OS X installer contains four packages, NetBeans, GlassFish, Tomcat, and OpenESB, these four packages need to be installed individually, They can be installed by simply double-clicking on each one of them. Please note that GlassFish must be installed before OpenESB. Linux and Solaris For Linux and Solaris, NetBeans is downloaded in the form of a shell script. The name of the file will be similar to netbeans-7.0-ml-java-linux.sh, netbeans-7.0-mljava-solaris-x86.sh, or netbeans-7.0-ml-java-solaris-sparc.sh, depending on the version of NetBeans, the selected platform and the selected NetBeans bundle. Before NetBeans can be installed in these platforms, the downloaded file needs to be made executable. This can be done in the command line by navigating to the directory where the NetBeans installer was downloaded and executing the following command: chmod +x ./filename.sh Substitute filename.sh with the appropriate file name for the platform and the NetBeans bundle. Once the file is executable it can be installed from the command line: ./filename.sh Again substitute filename.sh with the appropriate file name for the platform and the NetBeans bundle. Other platforms For other platforms, NetBeans can be downloaded as a platform-independent zip file. The name of the zip file will be something like netbeans-7.0-201007282301-mljava.zip (exact file name may vary, depending on the exact version of NetBeans downloaded and the NetBeans bundle that was selected). To install NetBeans on one of these platforms, simply extract the zip file to any suitable directory.  
Read more
  • 0
  • 0
  • 2356

article-image-biztalk-application-dynamics-ax-message-outflow
Packt
03 Aug 2011
4 min read
Save for later

BizTalk Application: Dynamics AX Message Outflow

Packt
03 Aug 2011
4 min read
  Microsoft BizTalk 2010: Line of Business Systems Integration A practical guide to integrating Line of Business systems with BizTalk Server 2010 We found that rather than repeating code in several BizTalk solutions when you need to retrieve data from the AIF Queue, it's relatively simple to create a general solution to accomplish this. This solution will retrieve all data via the BizTalk Dynamics AX adapter by polling the Queue at a set interval of time. The minimum polling interval is 1 minute, thus any messages you put in the AIF Queue will not be immediately consumed by BizTalk. The complete solution (Chapter9-AXMessageOutflow) is included with the source code. We'll start by creating a new BizTalk project, Chapter9-AXMessageOutflow, in Visual Studio. Add in a new orchestration, ProcessOutboundAXMessage.odx, which will be the only orchestration required for this example. Also, we'll need to add reference to the Microsoft.Dynamics.BizTalk.Adapter.Schemas assembly and sign the project with a strong name key.   Message setup Next, we'll add two messages to our orchestration: msgAxOutboundMessage and msgAXDocument. These will be the only two messages required in this example. The first message, msgAXOutboundMessage, is of type DynamicsAX5.Message.Envelope. The schema is located in the referenced Microsoft.Dynamics.BizTalk.Adapter.Schemas assembly. (Move the mouse over the image to enlarge.) All outbound messages from the AIF Queue are of this type. As you can see from the sample screenshot below, we have some metadata in the header node but what we are really interested in is the XML contents of the Body node. The contents of the MessageParts node in the Body node will be of type ExchangeRatesService_ExchangeRates.xsd. Thus, all the schemas we require for both inbound and outbound transactions can be generated using the adapter. For the second message, since we don't want to specify a document type, we will use System.Xml.XmlDocument for the Message Type. Using the System.Xml.XmlDocument message type allows for great flexibility in this solution. We can push any message to the AIF queue, and no changes to this BizTalk application are required. Only changes to consuming applications may need to add the AX schema of the message in order to process it. Orchestration setup Next, we create a new a logical port that will receive all messages from Dynamics AX via the AIF Queue with the following settings: Port NameReceiveAXOutboundMessage_PortPort Type NameReceiveAXOutboundMessage_PortTypeCommunication PatternOne-WayPort direction of communicationI'll always be receiving messages on this portPort BindingSpecify Later Also, create a new send port. For this example, we'll just send to a folder drop using the FILE adapter so that we can easily view the XML documents. In practice, other BizTalk applications will most likely process these messages, so you may choose to modify the send port to meet your requirements. Send port settings: Port NameSendAXDocument_PortPort Type NameSendAXDocument_PortTypeCommunication PatternOne-WayPort direction of communicationI'll always be sending messages on this portPort BindingSpecify Later Next, we will need to add the following to the orchestration: Receive shape (receive msgAXOutboundMessage message) Expression shape (determine the file name for msgAXDocument) Message assignment (construct msgAXDocument message) Send shape (send msgAXDocument message) We'll also add two variables (aifActionName and xpathExpression) of type System.String and xmlDoc of type System.Xml.XmlDocument. In the expression shape, we want to extract the AIF Action so that we can name the outbound XML documents in a similar fashion. This will allow us to easily identify the message type from AX. Next, we'll put the following inside expression shape below receive to extract the AIF action name. aifActionName = msgAXOutboundMessage(DynamicsAx5.Action); aifActionName = aifActionName.Substring(55,aifActionName. LastIndexOf('/') - 55); Now, we need to extract the contents of the body message, which is the XML document that we are interested in. Inside the message assignment shape, we will use XPath to extract the message. What we are interested in is the contents of the Body node in the DynamicsAX5.Message.Envelope message we will receive from AX via the AIF Queue. Add the following code inside the assignment shape to extract the XML, assign it to the message we are sending out, and set a common name that we can use in our send port: // Extract Contents of Body node in Envelope Message xpathExpression = "/*[local-name()='Envelope' and namespaceuri()=' http://schemas.microsoft.com/dynamics/2008/01/documents/ Message']/*[local-name()='Body' and namespace-uri()='http://schemas.microsoft.com/dynamics/2008/01/ documents/Message']"; xmlDoc = xpath(msgAXOutboundMessage, xpathExpression); // Extract the XML we are interested in xmlDoc.LoadXml(xmlDoc.FirstChild.FirstChild.InnerXml); // Set the message to the XML Document msgAXDocument = xmlDoc; // Assign FILE.ReceivedFileNameproperty msgAXDocument(FILE.ReceivedFileName) = aifActionName;  
Read more
  • 0
  • 0
  • 2136

article-image-integrating-microsoft-dynamics-ax-2009-using-biztalk-adapter
Packt
03 Aug 2011
5 min read
Save for later

Integrating with Microsoft Dynamics AX 2009 using BizTalk Adapter

Packt
03 Aug 2011
5 min read
  Microsoft BizTalk 2010: Line of Business Systems Integration What is Dynamics AX? Microsoft Dynamics AX (formally Microsoft Axapta) is Microsoft's Enterprise Resource Planning (ERP) solution for mid-size and large customers. Much like SAP, Dynamics AX provides functions that are critical to businesses that can benefit from BizTalk's integration. Microsoft Dynamics AX is fully customizable and extensible through its rich development platform and tools. It has direct connections to products such as Microsoft BizTalk Server, Microsoft SQL Server, Exchange, and Office. Often Dynamics AX is compared to SAP All in One. Those who are familiar with SAP are also familiar with high cost of implementation, maintenance, and customization associated with it. A Microsoft Dynamics AX solution offers more customizability, lower maintenance costs, and lower per-user costs than SAP. ERP implementations often fail in part due to lack of user acceptance in adopting a new system. The Dynamics AX user interface has a similar look and feel to other widely used products such as Microsoft Office and Microsoft Outlook, which significantly increases the user's comfort level when dealing with a new ERP system. For more information on Dynamics AX 2009 and SAP, please see http://www.microsoft.com/dynamics/en/us/compare-sap.aspx. Methods of integration with AX Included with Dynamics AX 2009, Microsoft provides two tools for integration with Dynamics AX: Dynamics AX BizTalk Adapter .NET Business Connector The BizTalk adapter interfaces via the Application Interface Framework Module (AIF) in Dynamics AX 2009, and the .NET Business Connector directly calls the Application Object Tree (AOT) classes in your AX source code. The AIF module requires a license key, which can add cost to your integration projects if your organization has not purchased this module. It provides an extensible framework that enables integration via XML document exchange. A great advantage of the AIF module is its integration functionality with the BizTalk Dynamics AX adapter. Other adapters include a FILE adapter and MSMQ, as well as Web Services to consume XML files are included out of the box. The AIF module requires a fair amount of setup and configuration. Other advantages include full and granular security, capability of synchronous and asynchronous mode integration mode, and full logging of transactions and error handling. The Microsoft BizTalk AX 2009 adapter can execute AX actions (exposed functions to the AIF module) to write data to AX in both synch and asynch modes. Which mode is used is determined by the design of your BizTalk application (via logical ports). A one-way send port will put the XML data into the AIF queue, whereas a two-way send-receive port will execute the actions and return a response message. Asynch transitions will stay in the AIF queue until a batch job is executed. Setting up and executing the batch jobs can be very difficult to manage. Pulling data from AX can also be achieved using the BizTalk adapter. Transactions pushed into the same AIF queue (with an OUTBOUND direction in an async mode) can be retrieved using the AX adapter which polls AX for these transactions. The .NET Business connector requires custom .NET code to be written in order to implement it. If your business requirements are for a single (or very small amount) of point-to-point integration data flows, then we would recommend using the .NET Business Connector. However, this often requires customizations in order to create and expose the methods. Security also needs to be handled with the service account that the code is running under. Installing the adapter and .NET Business Connector The Microsoft BizTalk adapter for Dynamics AX 2009 and the .NET Business Connector are installed from your Dynamics AX Setup install setup under Integration on the Add or Modify components window. Each component is independent of one another; however the BizTalk adapter leverages components of the business connector. You are not required to install the Dynamics AX client on the BizTalk server. When installed in BizTalk adapter, you can simply select all the defaults from the install wizard. For the .NET business connector, you'll be prompted for the location of your Dynamics AX instance. This will be used only as a default configuration and can easily be changed. Configuring Dynamics AX 2009 Application Integration Framework for BizTalk Adapter Configuration of the AIF module involves several steps. It also goes a long way to increasing your understanding of the granularity of Dynamics AX setup and security considerations that were taken into account for integration of what can be highly sensitive data.It is recommended that this setup be done with Admin level security, however, only full control of the AIF module is required. This setup is almost identical in version prior to Dynamics AX 2009; minor differences will be noted. All AIF setup tables can be found in Dynamics AX under Basic | Setup | Application Integration Framework. The first step is rather simple, however critical. In the Transport Adapters form, add in a new entry selecting Adapter Class drop down AifBizTalkAdapter, select Active, and Direction will be Receive and Respond. You also notice there are two other out-of-the-box adapters: FILE and MSMQ. This is a one-time setup that is effective across all companies. Next, using the Channels form, set up an active channel for your specific BizTalk server. Select a meaningful and identifiable Channel ID and Name such as BizTalkChannelID and BizTalkChannel. Select the Adapter to BizTalk Adapter, check Active, set Direction to Both, Response channel equal to the Channel ID of BizTalkChannelID. Set the Address to your BizTalk Server (I2CDARS1 as shown below). (Move the mouse over the image to enlarge.)  
Read more
  • 0
  • 0
  • 3681

article-image-biztalk-application-currency-exchange-rates
Packt
03 Aug 2011
7 min read
Save for later

BizTalk Application: Currency Exchange Rates

Packt
03 Aug 2011
7 min read
Microsoft BizTalk 2010: Line of Business Systems Integration A practical guide to integrating Line of Business systems with BizTalk Server 2010 We are going to assume that we have two companies in our Dynamics AX implementation; one that is Canadian Dollar (CAD) based, and one that is United States Dollar(USD) based. Thus, we need to use the LedgerExchangeRates.create and LedgerExchangeRates.find actions in both companies. For the remainder of this example, we'll refer to these as daxCADCompany and daxUSDCompany. The complete solution, titled Chapter9-AXExchangeRates, is included in the source code. Dynamics AX schemas We'll start by creating a new BizTalk project, Chapter9-AXExchangeRates, in Visual Studio. After the AIF actions setup is complete, the next step is to generate the required schemas that are needed for our BizTalk application. This is done by right clicking on the BizTalk project in Visual Studio 2010, click Add, highlight and click Add Generated Items. This will bring up the Add Generated Items window, under the Templates section—Visual Studio installed template, select Add Adapter Metadata, and click Add. This will bring up the Add Adapter Wizard window (shown in the following screenshot), so we'll simply select Microsoft Dynamics AX 2009 and click Next. Now, we'll need to fill in the AX server instance name (AX 2009-SHARED in our example) under Server name, and the TCP/IP Port number (2712, which is the default port number, but this can differ). Now, click Next from the BizTalk Adapter for Microsoft Dynamics AX Schema Import Wizard window. Specify the connection information in the next step. In the next window, you should see all the active AIF services. Note that since the AIF services table is a global table, so you will see all the active services in your Dynamics AX instance. This does not mean that each endpoint, thus each company, is configured to accept the actions that each AIF service listed has available. This is the point where you first verify that your connectivity and AIF setup is correct. An error here using the wizard typically is due to an error in the AIF channel configuration. In the wizard window above, you can see the AIF services that are enabled. In our case, the ExchangeRatesService is the only service currently enabled in our Dynamics AX instance. Under this service, you will see three possible modes (sync, async request, and async response) to perform these actions. All three will actually produce the same schemas. Which mode and action (create, find, findkeys, or read) we use is actually determined by the metadata in our message we'll be sending to AX and the logical port configurations in our orchestration. Now, click Finish. Now in the project solution, we see that the wizard will generate the two artifacts. The first ExchangeRates_ExchangeRates.xsd is the schema for the message type that we need to send when calling the LedgerExchangeRates.create action and it is also the same schema returned in the response message when calling the action LedgerExchangeRates.find. Since we are actually dealing with the same AX table in both actions, Exchange Rates, both actions will in part (one will be the inbound message, the other will be the outbound message) require the same schema. The second artifact, BizTalk Orchestration.odx, is also generated by default by the wizard. In the orchestration view, we can see that four Multi-part Message Types were also added to the orchestration. Rename the orchestration to something more meaningful such as ProcessExchangeRates.odx. Now that we have defined our message type that will be returned in our response message, we need to define what the request type will be. Notice from the orchestration view that two messages, ExchangeRatesService_create_Response and ExchangeRatesService_find_Request, have types which Visual Studio has in error 'does not exist or is invalid'. For the out-of-the-box find action, we need the message type DynamicsAX5.QueryCriteria. The other message type is return by AX when calling a create action is DynamicsAX5.EntityKey (if we called a createList action, the returned message would be of type DynamicsAX5.EntitiyKeyList). The schemas for these message types are in the Microsoft.Dynamics.BizTalk.Adapter.Schemas assembly, which can be found in the bin directory of the install location of the BizTalk adapter. Add this reference to the project in Visual Studio. Then, re-select the appropriate message type for each Message Part that is invalid from the Select Artifact Type window as shown. Next, depending on your organization, typically you may want to either populate the noon exchange rates or closing rates. For our example, we will use the closing USD/CAD exchange rates from the Bank of Canada. This is published at 16:30 EST on the website (http://www.bankofcanada.ca/rss/fx/close/fx-close.xml). Since this source is already in XML, download and save a sample. We then generate a schema from Visual Studio using the BizTalk Schema Generator (right click the solution, Add Generated Items, Add Generated Schemas, using the Well-Formed XML (Not Loaded) document type. This will generate the schema for the message that we need to receive by our BizTalk application daily. In the example provided, the schema is ClosingFxRates.xsd (the wizard will generate four other .xsd files that are referenced in ClosingFxRates.xsd). A simple way to schedule the download of this XML data file is to use the Schedule Task Adapter (http://biztalkscheduledtask.codeplex.com/), which can be downloaded and installed at no cost (the source code is also available). Download and install the adapter (requires Microsoft .NET Framework Version 1.1 Redistributable Package), then add using the BizTalk Server Administration Console with the name Schedule. We will use this adapter in our receive location to retrieve the XML via http. There are also RSS adapters available to be purchased from, for example, /nsoftware (http://www.nsoftware.com/). However, for this example, the scheduled task adapter will suffice. Now, since the source of our exchange rates is a third-party schema, and your specific requirements for the source will most likely differ, we'll create a canonical schema ExchangeRates.xsd. As you can see in the schema below, we are only interested in a few pieces of information: Base Currency (USD or CAD in our example), Target Currency (again USD or CAD), Rate, and finally, Date. Creating a canonical schema will also simplify the rest of our solution. Now that we have all the schemas defined for our message types defined or referenced, we can add the messages that we require to the orchestration. We'll begin by adding the message msgClosingFxRates. That will be our raw input data from the Bank of Canada with the message type from the generated schema ClosingFxRates.RDF. For each exchange rate, we'll need to first query Dynamics AX to see if it exists, thus we'll need a request message and a response message. Add a message msgAXQueryExchangeRatesRequest, which will be a multi-part message type ExchangeRatesService_find_Request, and msgAXQueryExchangeRatesResponse that will be a multi-part message type ExchangeRatesService_find_Response. Next, we'll create the messages for the XML that we'll send and receive from Dynamics AX to create an exchange rate. Add a message msgAXCreateExchnageRatesRequest, which will be a multi-part message type of ExchangeRatesService_create_Request, and msgAXCreateExchnageRatesResponse that will be a multi-part message type ExchangeRatesService_create_Response. Finally, we'll need to create two messages, msgExchangeRatesUSDCAD and msgExchangeRatesCADUSD, which will have the message type of the canonical schema ExchangeRates. These messages will contain the exchange rates for USD to CAD and for CAD to USD respectively. We'll create these two messages just to simplify our orchestration for this example. In practice, if you're going to deal with several exchange rates, you will need to add logic to the orchestration to loop through the list rates that you're interested in and have only one message of type ExchangeRates resent several times.
Read more
  • 0
  • 0
  • 2168
article-image-communicating-dynamics-crm-biztalk-server
Packt
20 Jul 2011
6 min read
Save for later

Communicating from Dynamics CRM to BizTalk Server

Packt
20 Jul 2011
6 min read
Microsoft BizTalk 2010: Line of Business Systems Integration A practical guide to integrating Line of Business systems with BizTalk Server 2010 There are three viable places where Dynamics CRM can communicate with BizTalk Server. First, a Dynamics CRM form is capable of executing client-side JavaScript at various points in the form lifecycle. One can definitely use JavaScript to invoke web services, including web services exposed by BizTalk Server. However, note that JavaScript invocation of web services is typically synchronous and could have a negative impact on the user experience if a form must constantly wait for responses from distributed services. Also, JavaScript that runs within Dynamics CRM is clientside and tied directly to the page on which it resides. If we programmatically interact with a Dynamics CRM entity, then any code existing in the client-side script will not get invoked. For instance, if after an "account" record is created we send a message, via JavaScript, to BizTalk, this logic would not fire if we created an "account" record programmatically. The second place where Dynamics CRM can communicate with BizTalk Server is through workflows. A workflow in Dynamics CRM is an automated process where a set of steps is executed according to rules that we define. For example, when a sales opportunity is closed, we run a workflow that adds a message to the customer record, notifies all parties tied to the opportunity, and sends a polite email to the lost prospect. Workflows are based on Windows Workflow 4.0 technology and can be built either in the Dynamics CRM application itself or within Visual Studio 2010. The Dynamics CRM web application allows us to piece together workflows using previously registered workflow steps. If we need new workflow steps or need to construct something complex, we can jump into Visual Studio 2010 and define the workflow there. Why would we choose to use a workflow to send a message to BizTalk Server? If you have a long-running process that can either be scheduled or executed on demand and want the option for users to modify the process, the workflow may be the right choice. The final strategy for communicating between Dynamics CRM and BizTalk Server is to use plugins. Plugins are server-based application extensions that execute business logic and get tied directly to an entity. This means that they are invoked whether we work in the Dynamics CRM web interface or through the API. I can run a plugin both synchronously and asynchronously, depending on the situation. For instance, if we need to validate the data on a record prior to saving it, we can set a plugin to run before the "save" operation is committed and provide some user feedback on the invalid information. Or, we could choose to asynchronously call a plugin after a record is saved and transmit data to our service bus, BizTalk Server. In the following exercise, we will leverage plugins to send data from Dynamics CRM to BizTalk Server. Integration with BizTalk Server In this first walkthrough, we will build a plugin that communicates from Dynamics CRM to a BizTalk Server located. An event message will be sent to BizTalk whenever a change occurs on an Account record in Dynamics CRM. Setup This exercise leverages a BizTalk Server project already present in your Visual Studio 2010 solution. We are going to publish a web service from BizTalk Server that takes in a message and routes it to a BizTalk send port that writes the message to the file system. If you have not already done so, go to the code package and navigate to C:LOBIntegrationChapter03Chapter3-DynamicsCRM and open the Visual Studio 2010 solution file named Chapter3-DynamicsCRM.sln. Find the BizTalk Server project named Chapter3-DynamicsCRM.AcctRouting and open it. The code package includes a custom schema named AccountEventChange_XML.xsd and notice which elements we want from Dynamics CRM 2011 when an account changes. The first element, EventSource, is used to designate the source of the change event, as there may be multiple systems that share changes in an organization's accounts. This BizTalk project should be set to deploy to a BizTalk application named Chapter3. Build and deploy the project to the designated BizTalk Server. After confirming a successful deployment, launch the BizTalk WCF Service Publishing Wizard. We are going to use this schema to expose a web service entry point into BizTalk Server that Dynamics CRM 2011 can invoke. On the WCF Service Type wizard page, select a WCF-BasicHttp adapter and set the service to expose metadata and have the wizard generate a receive location for us in the Chapter3 application: On the Create WCF Service wizard page, choose to Publish schemas as WCF service. This option gives us fine-grained control over the naming associated with our service. On the next page, delete the two-way operation already present in the service definition. Rename the topmost service definition to AccountChangeService and assign the service the same name. Right-click the service and create a new one-way operation named PublishAccountChange. Right-click the Request message of the operation and choose the AccountChangeEvent message from our BizTalk Project's DLL: On the following wizard page, set the namespace of the service to http://Chapter3/AccountServices. Next, set the location of our service to http://localhost/AccountChangeService and select the option to allow anonymous access to the generated service. Finally, complete the wizard by clicking the Create button on the final wizard page. Confirm that the wizard successfully created both an IIS-hosted web service, and a BizTalk receive port/location. Ensure that the IIS web service is running under an Application Pool that has permission to access the BizTalk databases. In order to test this service, first, go to the BizTalk Server Administration Console and locate the Chapter3 application. Right click the Send Ports folder and create a new, static one-way send port named Chapter3.SendAccountChange.FILE. Set the send port to use the FILE adapter and select the FileDropDropCustomerChangeEvent folder that is present in the code package: This send port should listen for all account change event messages, regardless of which receive location (and system) that they came from. Go to the Filters tab of this send port. Set the filter Property to BTS.MessageType and filter Value to http://Chapter3-DynamicsCRM.AcctRouting.AccountChangeEvent_XML#AccountChangeEvent. All that remains is to test our service. Open the WCF Test Client application and add a new service reference to http://localhost/AccountChangeService/AccountChangeService.svc. Invoke the PublishAccountChange method and, if everything is configured correctly, we will see a message emitted by BizTalk Server that matches our service input parameters: (Move the mouse over the image to enlarge.) We now are sufficiently ready to author the Dynamics CRM plugin, which calls this BizTalk service.  
Read more
  • 0
  • 0
  • 3108

article-image-integrating-biztalk-server-and-microsoft-dynamics-crm
Packt
20 Jul 2011
7 min read
Save for later

Integrating BizTalk Server and Microsoft Dynamics CRM

Packt
20 Jul 2011
7 min read
What is Microsoft Dynamics CRM? Customer relationship management is a critical part of virtually every business. Dynamics CRM 2011 offers a solution for the three traditional areas of CRM: sales, marketing, and customer service. For customers interested in managing a sales team, Dynamics CRM 2011 has a strong set of features. This includes organizing teams into territories, defining price lists, managing opportunities, maintaining organization structures, tracking sales pipelines, enabling mobile access, and much more. If you are using Dynamics CRM 2011 for marketing efforts, then you have the ability to import data from multiple sources, plan campaigns and set up target lists, create mass communications, track responses to campaigns, share leads with the sales team, and analyze the success of a marketing program. Dynamics CRM 2011 also serves as a powerful hub for customer service scenarios. Features include rich account management, case routing and management, a built-in knowledge base, scheduling of call center resources, scripted Q&A workflows called Dialogs, contract management, and more. Besides these three areas, Microsoft pitches Dynamics CRM as a general purpose application platform called xRM, where the "X" stands for any sort of relationship management. Dynamics CRM has a robust underlying framework for screen design, security roles, data auditing, entity definition, workflow, and mobility, among others. Instead of building these foundational aspects into every application, we can build our data-driven applications within Dynamics CRM. Microsoft has made a big move into the cloud with this release of Dynamics CRM 2011. For the first time in company history, a product was released online (Dynamics CRM Online) prior to on-premises software. The hosted version of the application runs an identical codebase to the on-premises version meaning that code built to support a local instance will work just fine in the cloud. In addition to the big play in CRM hosting, Microsoft has also baked Windows Azure integration into Dynamics CRM 2011. Specifically, we now have the ability to configure a call-out to an Azure AppFabric Service Bus endpoint. To do this, the downstream service must implement a specific WCF interface and within CRM, the Azure AppFabric plugin is configured to call that downstream service through the Azure AppFabric Service Bus relay service. For BizTalk Server to accommodate this pattern, we would want to build a proxy service that implements the required Dynamics CRM 2011 interface and forwards requests into a BizTalk Server endpoint. This article will not demonstrate this scenario, however, as the focus will be on integrating with an onpremises instance only. Why Integrate Dynamics CRM and BizTalk Server? There are numerous reasons to tie these two technologies together. Recall that BizTalk Server is an enterprise integration bus that connects disparate applications. There can be a natural inclination to hoard data within a particular application, but if we embrace real-time message exchange, we can actually have a more agile enterprise. Consider a scenario when a customer's full "contact history" resides in multiple systems. The Dynamics CRM 2011 contact center may only serve a specific audience, and other systems within the company hold additional details about the company's customers. One design choice could be to bulk load that information into Dynamics CRM 2011 on a scheduled interval. However, it may be more effective to call out to a BizTalk Server service that aggregates data across systems and returns a composite view of a customer's history with a company. In a similar manner, think about how information is shared between systems. A public website for a company may include a registration page where visitors sign up for more information and deeper access to content. That registration event is relevant to multiple systems within the company. We could send that initial registration message to BizTalk Server and then broadcast that message to the multiple systems that want to know about that customer. A marketing application may want to respond with a personalized email welcoming that person to the website. The sales team may decide to follow up with that person if they expressed interest in purchasing products. Our Dynamics CRM 2011 customer service center could choose to automatically add the registration event so that it is ready whenever that customer calls in. In this case, BizTalk Server acts as a central router of data and invokes the exposed Dynamics CRM services to create customers and transactions. Communicating from BizTalk Server to Dynamics CRM The way that you send requests from BizTalk Server to Dynamics CRM 2011 has changed significantly in this release. In the previous versions of Dynamics CRM, a BizTalk "send" adapter was available for communicating with the platform. Dynamics CRM 2011 no longer ships with an adapter and developers are encouraged to use the WCF endpoints exposed by the product. Dynamics CRM has both a WCF REST and SOAP endpoint. The REST endpoint can only be used within the CRM application itself. For instance, you can build what is called a web resource that is embedded in a Dynamics CRM page. This resource could be a Microsoft Silverlight or HTML page that looks up data from three different Dynamics CRM entities and aggregates them on the page. This web resource can communicate with the Dynamics CRM REST API, which is friendly to JavaScript clients. Unfortunately, you cannot use the REST endpoint from outside of the Dynamics CRM environment, but because BizTalk cannot communicate with REST services, this has little impact on the BizTalk integration story. The Dynamics CRM SOAP API, unlike its ASMX web service predecessor, is static and operates with a generic Entity data structure. Instead of having a dynamic WSDL that exposes typed definitions for all of the standard and custom entities in the system, the Dynamics CRM 2011 SOAP API has a set of operations (for example, Create, Retrieve) that function with a single object type. The Entity object has a property identifying which concrete object it represents (for example, Account or Contract), and a name/value pair collection that represents the columns and values in the object it represents. For instance, an Entity may have a LogicalName set to "Account" and columns for "telephone1", "emailaddress", and "websiteurl." In essence, this means that we have two choices when interacting with Dynamics CRM 2011 from BizTalk Server. Our first option is to directly consume and invoke the untyped SOAP API. Doing this involves creating maps from a canonical schema to the type-less Entity schema. In the case of doing a Retrieve operation, we may also have to map the type-less Entity message back to a structured message for more processing. Below, we will walk through an example of this. The second option involves creating a typed proxy service for BizTalk Server to invoke. Dynamics CRM has a feature-rich Solution Development Kit (SDK) that allows us to create typed objects and send them to the Dynamics CRM SOAP endpoint. This proxy service will then expose a typed interface to BizTalk that operates as desired with a strongly typed schema. An upcoming exercise demonstrates this scenario. Which choice is best? For simple solutions, it may be fine to interact directly with the Dynamics CRM 2011 SOAP API. If you are updating a couple fields on an entity, or retrieving a pair of data values, the messiness of the untyped schema is worth the straightforward solution. However, if you are making large scale changes to entities, or getting back an entire entity and publishing to the BizTalk bus for more subscribers to receive, then working strictly with a typed proxy service is the best route. However, we will look at both scenarios below, and you can make that choice for yourself. Integrating Directly with the Dynamics CRM 2011 SOAP API In the following series of steps, we will look at how to consume the native Dynamics CRM SOAP interface in BizTalk Server. We will first look at how to query Dynamics CRM to return an Entity. After that, we will see the steps for creating a new Entity in Dynamics CRM. Querying Dynamics CRM from BizTalk Server In this scenario, BizTalk Server will request details about a specific Dynamics CRM "contact" record and send the result of that inquiry to another system.
Read more
  • 0
  • 0
  • 5243

article-image-generating-jsf-applications-jpa-entities
Packt
20 Jun 2011
6 min read
Save for later

Generating JSF Applications from JPA Entities

Packt
20 Jun 2011
6 min read
Java EE 6 Development with NetBeans 7 Develop professional enterprise Java EE applications quickly and easily with this popular IDE To generate JSF pages from existing JPA entities, we need to right-click on the project, select File | New File, then select the JavaServer Faces category and the JSF Pages from Entity Classes file type. In order for us to be able to generate JSF pages from existing JPA entities, the current project must be a Web Application project. After clicking on Next>, we need to select one or more JPA entities. We would typically want to select all of them, they can easily be selected by clicking on the Add All>> button. The next page in the wizard allows us to specify a package for newly created JSF managed beans. Two types of classes are generated by the wizard, JPA Controllers and JSF Classes, we can specify packages for both of these individually. We are also given the opportunity to specify a folder for the JSF pages to be created, if we leave this field blank, pages will be created in our project's Web Pages folder. The value of the Session Bean Package and JSF Classes Package text fields default to the package where our JPA entities reside. It is a good idea to modify this default since placing the JSF managed beans in a different package separates the data access layer classes from the user interface and controller layers of our application. After clicking on Finish, a complete web application that can perform CRUD operations will be created. As we can see, NetBeans generates a folder for each of our entities under the Web Pages folder of our application. Each of the folders has a Detail, Edit, List, and New XHTML files. These files are JSF pages using Facelets as their view technology. The Detail page will display all properties for a JPA entity, the Edit page will allow users to update information for a specific entity, the List page will display all instances of a specific entity in the database, and the New page will provide functionality to create new entities. The generated application is a standard JSF application. We can execute it by simply right-clicking on the project and selecting Run. At that point the usual things happen, the application server is started if it wasn't up already, the application is deployed, and a web browser window is opened displaying the welcome page for our application. As we can see, the welcome page contains a link corresponding to each of our JPA entities. The links will display a table displaying all existing instances of our entity in the database. When we click on the Show All Customer Items, the following page is shown: Since we haven't inserted any data to the database yet, the page displays the message (No Customer Items Found). We can insert a customer into the database by clicking on the Create New Customer link. Notice how an input field is generated for each property in our entity, which in turn corresponds to a column in the database table. As we can see, an input field was generated for the primary key field of our entity. This field is only generated if the JPA entity does not use a primary key generation strategy. After entering some information on the page and clicking on the Save link, the data is saved, or the form is cleared and the message Customer was successfully created is shown. We can see our newly created customer by clicking on Show All Customer Items. At this point we can see our newly created customer in the list of customers on this JSP. Notice that the page has links to View, Edit, and Destroy (delete) the entity. Let's say we would want to add an address for our customer, we could do so by clicking on the Index link, then clicking on Show All Address Items, then on New Address. The Address entity is at the "one" end of several one-to-many relationships, notice how a combo box is generated for each one of the entities at the "many" end. Since we wish to assign this address to the customer we just added, we attempt to select a customer from the CustomerId combo box. A better name could be used for the CustomerId field, the reason this is the label for the combo box is because it matches the property name on the Address JPA entity, which in turn could have a better name such as customer. Recall that all entities on this project were automatically generated from an existing database schema. Clicking on the combo box reveals a cryptic, almost undecipherable (from the users' point of view anyway) label for our customer. The reason we see this label is because the labels generated for each item in the combo box come from the toString() method of the entities used to populate it. We can work around this issue by modifying the toString() method so that it returns a user-friendly String suitable to use as a label. As we can see, the generated code from NetBeans wizards could certainly use some tweaking, such as modifying the toString() methods of each JPA entity so that it can be used as a label, modifying some of the property names on the entities so that they make more sense to us developers, modifying the labels on the generated JSF pages so that they are more user-friendly, and last but not least, the pages themselves are not very visually appealing. It would be a good idea to modify them so that they don't look so plain. Nevertheless, as we can see we can have a fully working application completely created by a few clicks of the mouse. This functionality certainly saves us a lot of time and effort. Summary In this article we saw how NetBeans can generate a complete JSF application from existing JPA entities. Further resources on this subject: Java Refactoring in NetBeans [Article] NetBeans IDE 7: Building an EJB Application [Article] Java Data Objects and Service Data Objects in SOA [Article]
Read more
  • 0
  • 0
  • 2522
article-image-how-create-new-jsf-project
Packt
20 Jun 2011
17 min read
Save for later

How to Create a New JSF Project

Packt
20 Jun 2011
17 min read
  Java EE 6 Development with NetBeans 7 Develop professional enterprise Java EE applications quickly and easily with this popular IDE       Introduction to JavaServer faces Before JSF existed, most Java web applications were typically developed using non-standard web application frameworks such as Apache Struts, Tapestry, Spring Web MVC, or many others. These frameworks are built on top of the Servlet and JSP standards, and automate a lot of functionality that needs to be manually coded when using these APIs directly. Having a wide variety of web application frameworks available, often resulted in "analysis paralysis", that is, developers often spend an inordinate amount of time evaluating frameworks for their applications. The introduction of JSF to the Java EE specification resulted in having a standard web application framework available in any Java EE compliant application server. We don't mean to imply that other web application frameworks are obsolete or that they shouldn't be used at all. However, a lot of organizations consider JSF the "safe" choice since it is part of the standard and should be well supported for the foreseeable future. Additionally, NetBeans offers excellent JSF support, making JSF a very attractive choice. Strictly speaking, JSF is not a web application framework per se, but a component framework. In theory, JSF can be used to write applications that are not web-based, however, in practice JSF is almost always used for this purpose. In addition to being the standard Java EE component framework, one benefit of JSF is that it provides good support for tools vendors, allowing tools such as NetBeans to take advantage of the JSF component model with drag and drop support for components.   Developing our first JSF application From an application developer's point of view, a JSF application consists of a series of XHTML pages containing custom JSF tags, one or more JSF managed beans, and an optional configuration file named faces-config.xml. faces-config.xml used to be required in JSF 1.x, however, in JSF 2.0, some conventions were introduced that reduce the need for configuration. Additonally, a lot of JSF configuration can be specified using annotations, reducing, and in some cases, eliminating the need for this XML configuration file. Creating a new JSF project To create a new JSF project, we need to go to File | New Project, select the Java Web project category, and Web Application as the project type. After clicking Next>, we need to enter a project name, and optionally change other information for our project, although NetBeans provides sensible defaults. On the next page in the wizard, we can select the server, Java EE version, and context path of our application. In our example we will simply pick the default values. On the next page of the new project wizard, we can select what frameworks our web application will use. Unsurprisingly, for JSF applications we need to select the JavaServer Faces framework. When clicking on Finish, the wizard generates a skeleton JSF project for us, consisting of a single facelet file called index.xhtml, a web.xml configuration file. web.xml is the standard, optional configuration file needed for Java web applications, this file became optional in version 3.0 of the Servlet API, which was introduced with Java EE 6. In many cases, web.xml is not needed anymore, since most of the configuration options can now be specified via annotations. For JSF applications, however, it is a good idea to add one, since it allows us to specify the JSF project stage. <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>faces/index.xhtml</welcome-file> </welcome-file-list> As we can see, NetBeans automatically sets the JSF project stage to Development, setting the project stage to development configures JSF to provide additional debugging help not present in other stages. For example, one common problem when developing a page is that while a page is being developed, validation for one or more of the fields on the page fails, but the developer has not added an <h:message> or <h:messages> tag to the page. When this happens and the form is submitted, the page seems to do nothing, or page navigation doesn't seem to be working. When setting the project stage to Development, these validation errors will automatically be added to the page, without the developer having to explicitly add one of these tags to the page (we should, of course, add the tags before releasing our code to production, since our users will not see the automatically generated validation errors). The following are the valid values for the javax.faces.PROJECT_STAGE context parameter for the faces servlet: Development Production SystemTest UnitTest The Development project stage adds additional debugging information to ease development. The Production project stage focuses on performance. The other two valid values for the project stage (SystemTest and UnitTest), allow us to implement our own custom behavior for these two phases. The javax.faces.application.Application class has a getProjectStage() method that allows us to obtain the current project stage. Based on the value of this method, we can implement the code that will only be executed in the appropriate stage. The following code snippet illustrates this: public void someMethod() { FacesContext facesContext = FacesContext.getCurrentInstance(); Application application = facesContext.getApplication(); ProjectStage projectStage = application.getProjectStage(); if (projectStage.equals(ProjectStage.Development)) { //do development stuff } else if (projectStage.equals(ProjectStage.Production)) { //do production stuff } else if (projectStage.equals(ProjectStage.SystemTest)) { // do system test stuff } else if (projectStage.equals(ProjectStage.UnitTest)) { //do unit test stuff } } As illustrated in the snippet above, we can implement the code to be executed in any valid project stage, based on the return value of the getProjectStage() method of the Application class. When creating a Java Web project using JSF, a facelet is automatically generated. The generated facelet file looks like this: <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <h:head> <title>Facelet Title</title> </h:head> <h:body> Hello from Facelets </h:body> </html> As we can see, a facelet is nothing but an XHTML file using some facelets-specific XML name spaces. In the automatically generated page above, the following namespace definition allows us to use the "h" (for HTML) JSF component library: The above namespace declaration allows us to use JSF specific tags such as <h:head> and <h:body> which are a drop in replacement for the standard HTML/XHTML <head> and <body> tags, respectively. The application generated by the new project wizard is a simple, but complete JSF web application. We can see it in action by right-clicking on our project in the project window and selecting Run. At this point the application server is started (if it wasn't already running), the application is deployed and the default system browser opens, displaying our application's default page. Modifying our page to capture user data The generated application, of course, is nothing but a starting point for us to create a new application. We will now modify the generated index.xhtml file to collect some data from the user. The first thing we need to do is add an <h:form> tag to our page. The <h:form> tag is equivalent to the <form> tag in standard HTML pages. After typing the first few characters of the <h:form> tag into the page, and hitting Ctrl+Space, we can take advantage of NetBeans' excellent code completion. After adding the <h:form> tag and a number of additional JSF tags, our page now looks like this: <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <h:head> <title>Registration</title> <h:outputStylesheet library="css" name="styles.css"/> </h:head> <h:body> <h3>Registration Page</h3> <h:form> <h:panelGrid columns="3" columnClasses="rightalign,leftalign,leftalign"> <h:outputLabel value="Salutation: " for="salutation"/> <h:selectOneMenu id="salutation" label="Salutation" value="#{registrationBean.salutation}" > <f:selectItem itemLabel="" itemValue=""/> <f:selectItem itemLabel="Mr." itemValue="MR"/> <f:selectItem itemLabel="Mrs." itemValue="MRS"/> <f:selectItem itemLabel="Miss" itemValue="MISS"/> <f:selectItem itemLabel="Ms" itemValue="MS"/> <f:selectItem itemLabel="Dr." itemValue="DR"/> </h:selectOneMenu> <h:message for="salutation"/> <h:outputLabel value="First Name:" for="firstName"/> <h:inputText id="firstName" label="First Name" required="true" value="#{registrationBean.firstName}" /> <h:message for="firstName" /> <h:outputLabel value="Last Name:" for="lastName"/> <h:inputText id="lastName" label="Last Name" required="true" value="#{registrationBean.lastName}" /> <h:message for="lastName" /> <h:outputLabel for="age" value="Age:"/> <h:inputText id="age" label="Age" size="2" value="#{registrationBean.age}"/> <h:message for="age"/> <h:outputLabel value="Email Address:" for="email"/> <h:inputText id="email" label="Email Address" required="true" value="#{registrationBean.email}"> </h:inputText> <h:message for="email" /> <h:panelGroup/> <h:commandButton id="register" value="Register" action="confirmation" /> </h:panelGrid> </h:form> </h:body> </html> The following screenshot illustrates how our page will be rendered at runtime: All JSF input fields must be inside an <h:form> tag. The <h:panelGrid> helps us to easily lay out JSF tags on our page. It can be thought of as a grid where other JSF tags will be placed. The columns attribute of the <h:panelGrid> tag indicates how many columns the grid will have, each JSF component inside the <h:panelGrid> component will be placed in an individual cell of the grid. When the number of components matching the value of the columns attribute (three in our example) has been placed inside <h:panelGrid>, a new row is automatically started. The following table illustrates how tags will be laid out inside an <h:panelGrid> tag: Each row in our <h:panelGrid> consists of an <h:outputLabel> tag, an input field, and an <h:message> tag. The columnClasses attribute of <h:panelGrid> allows us to assign CSS styles to each column inside the panel grid, its value attribute must consist of a comma separated list of CSS styles (defined in a CSS stylesheet). The first style will be applied to the first column, the second style will be applied to the second column, the third style will be applied to the third column, so on and so forth. Had our panel grid had more than three columns, then the fourth column would have been styled using the first style in the columnClasses attribute, the fifth column would have been styled using the second style in the columnClasses attribute, so on and so forth. If we wish to style rows in an <h:panelGrid>, we can do so with its rowClasses attribute, which works the same way that the columnClasses works for columns. Notice the <h:outputStylesheet> tag inside <h:head> near the top of the page, this is a new tag that was introduced in JSF 2.0. One new feature that JSF 2.0 brings to the table is standard resource directories. Resources such as CSS stylesheets, JavaScript files, images, and so on, can be placed under a top level directory named resources, and JSF tags will have access to those resources automatically. In our NetBeans project, we need to place the resources directory under the Web Pages folder. We then need to create a subdirectory to hold our CSS stylesheet (by convention, this directory should be named css), then we place our CSS stylesheet(s) on this subdirectory. The value of the library attribute in <h:outputStylesheet> must match the directory where our CSS file is located, and the value of its name attribute must match the CSS file name. In addition to CSS files, we should place any JavaScript files in a subdirectory called javascript under the resources directory. The file can then be accessed by the <h:outputScript> tag using "javascript" as the value of its library attribute and the file name as the value of its name attribute. Similarly, images should be placed in a directory called images under the resources directory. These images can then be accessed by the JSF <h:graphicImage> tag, where the value of its library attribute would be "images" and the value of its name attribute would be the corresponding file name. Now that we have discussed how to lay out elements on the page and how to access resources, let's focus our attention on the input and output elements on the page. The <h:outputLabel> tag generates a label for an input field in the form, the value of its for attribute must match the value of the id attribute of the corresponding input field. <h:message> generates an error message for an input field, the value of its for field must match the value of the id attribute for the corresponding input field. The first row in our grid contains an <h:selectOneMenu>. This tag generates an HTML <select> tag on the rendered page. Every JSF tag has an id attribute, the value for this attribute must be a string containing a unique identifier for the tag. If we don't specify a value for this attribute, one will be generated automatically. It is a good idea to explicitly state the ID of every component, since this ID is used in runtime error messages. Affected components are a lot easier to identify if we explicitly set their IDs. When using <h:label> tags to generate labels for input fields, or when using <h:message> tags to generate validation errors, we need to explicitly set the value of the id tag, since we need to specify it as the value of the for attribute of the corresponding <h:label> and <h:message> tags. Every JSF input tag has a label attribute. This attribute is used to generate validation error messages on the rendered page. If we don't specify a value for the label attribute, then the field will be identified in the error message by its ID. Each JSF input field has a value attribute, in the case of <h:selectOneMenu>, this attribute indicates which of the options in the rendered <select> tag will be selected. The value of this attribute must match the value of the itemValue attribute of one of the nested <f:selectItem> tags. The value of this attribute is usually a value binding expression, that means that the value is read at runtime from a JSF managed bean. In our example, the value binding expression #{registrationBean.salutation} is used. What will happen is at runtime JSF will look for a managed bean named registrationBean, and look for an attribute named salutation on this bean, the getter method for this attribute will be invoked, and its return value will be used to determine the selected value of the rendered HTML <select> tag. Nested inside the <h:selectOneMenu> there are a number of <f:selectItem> tags. These tags generate HTML <option> tags inside the HTML <select> tag generated by <h:selectOneMenu>. The value of the itemLabel attribute is the value that the user will see while the value of the itemValue attribute will be the value that will be sent to the server when the form is submitted. All other rows in our grid contain <h:inputText> tags, this tag generates an HTML input field of type text, which accept a single line of typed text as input. We explicitly set the id attribute of all of our <h:inputText> fields, this allows us to refer to them from the corresponding <h:outputLabel> and <h:message> fields. We also set the label attribute for all of our <h:inputText> tags, this results in more user-friendly error messages. Some of our <h:inputText> fields require a value, these fields have their required attribute set to true, each JSF input field has a required attribute, if we need to require the user to enter a value for this attribute, then we need to set this attribute to true. This attribute is optional, if we don't explicitly set a value for it, then it defaults to false. In the last row of our grid, we added an empty <h:panelGroup> tag. The purpose of this tag is to allow adding several tags into a single cell of an <h:panelGrid>. Any tags placed inside this tag are placed inside the same cell of the grid where <h:panelGrid> is placed. In this particular case, all we want to do is to have an "empty" cell in the grid so that the next tag, <h:commandButton>, is aligned with the input fields in the rendered page. <h:commandButton> is used to submit a form to the server. The value of its value attribute is used to generate the text of the rendered button. The value of its action attribute is used to determine what page to display after the button is pressed. In our example, we are using static navigation. When using JSF static navigation, the value of the action attribute of a command button is hard-coded in the markup. When using static navigation, the value of the action attribute of <h:commandButton> corresponds to the name of the page we want to navigate to, minus its .xhtml extension. In our example, when the user clicks on the button, we want to navigate to a file named confirmation.xhtml, therefore we used a value of "confirmation" for its action attribute. An alternative to static navigation is dynamic navigation. When using dynamic navigation, the value of the action attribute of the command button is a value binding expression resolving to a method returning a String in a managed bean. The method may then return different values based on certain conditions. Navigation would then proceed to a different page depending on the value of the method. As long as it returns a String, the managed bean method executed when using dynamic navigation can contain any logic inside it, and is frequently used to save data in a managed bean into a database. When using dynamic navigation, the return value of the method executed when clicking the button must match the name of the page we want to navigate to (again, minus the file extension). In earlier versions of JSF, it was necessary to specify navigation rules in facesconfig.xml, with the introduction of the conventions introduced in the previous paragraphs, this is no longer necessary.  
Read more
  • 0
  • 0
  • 8816

article-image-facelets-templating-jsf-20
Packt
20 Jun 2011
7 min read
Save for later

Facelets Templating in JSF 2.0

Packt
20 Jun 2011
7 min read
One advantage that Facelets has over JSP is its templating mechanism. Templates allow us to specify page layout in one place, then we can have template clients that use the layout defined in the template. Since most web applications have consistent layout across pages, using templates makes our applications much more maintainable, since changes to the layout need to be made in a single place. If at one point we need to change the layout for our pages (add a footer, or move a column from the left side of the page to the right side of the page, for example), we only need to change the template, and the change is reflected in all template clients. NetBeans provides very good support for facelets templating. It provides several templates "out of the box", using common web page layouts. We can then select from one of several predefined templates to use as a base for our template or simply to use it "out of the box". NetBeans gives us the option of using HTML tables or CSS for layout. For most modern web applications, CSS is the preferred approach. For our example we will pick a layout containing a header area, a single left column, and a main area. After clicking on Finish, NetBeans automatically generates our template, along with the necessary CSS files. The automatically generated template looks like this: <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <h:head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="./resources/css/default.css" rel="stylesheet" type="text/css" /> <link href="./resources/css/cssLayout.css" rel="stylesheet" type="text/css" /> <title>Facelets Template</title> </h:head> <h:body> <div id="top" class="top"> <ui:insert name="top">Top</ui:insert> </div> <div> <div id="left"> <ui:insert name="left">Left</ui:insert> </div> <div id="content" class="left_content"> <ui:insert name="content">Content</ui:insert> </div> </div> </h:body> </html> As we can see, the template doesn't look much different from a regular Facelets file. Adding a Facelets template to our project We can add a Facelets template to our project simply by clicking on File | New File, then selecting the JavaServer Faces category and the Facelets Template file type. Notice that the template uses the following namespace: Java EE 6 Development with NetBeans 7" href="http://java.sun.com" target="_blank">http://java.sun.com/jsf/facelets. This namespace allows us to use the <ui:insert> tag, the contents of this tag will be replaced by the content in a corresponding <ui:define> tag in template clients. Using the template To use our template, we simply need to create a Facelets template client, which can be done by clicking on File | New File, selecting the JavaServer Faces category and the Facelets Template Client file type. After clicking on Next >, we need to enter a file name (or accept the default), and select the template that we will use for our template client. After clicking on Finish, our template client is created. <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <body> <ui:composition template="./template.xhtml"> <ui:define name="top"> top </ui:define> <ui:define name="left"> left </ui:define> <ui:define name="content"> content </ui:define> </ui:composition> </body> </html> As we can see, the template client also uses the Java EE 6 Development with NetBeans 7" href="http://java.sun.com" target="_blank">http://java.sun.com/jsf/facelets" namespace. In a template client, the <ui:composition> tag must be the parent tag of any other tag belonging to this namespace. Any markup outside this tag will not be rendered; the template markup will be rendered instead. The <ui:define> tag is used to insert markup into a corresponding <ui:insert> tag in the template. The value of the name attribute in <ui:define> must match the corresponding <ui:insert> tag in the template. After deploying our application, we can see templating in action by pointing the browser to our template client URL. Notice that NetBeans generated a template that allows us to create a fairly elegant page with very little effort on our part. Of course, we should replace the markup in the <ui:define> tags to suit our needs. Here is a modified version of our template, adding markup to be rendered in the corresponding places in the template: <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <body> <ui:composition template="./template.xhtml"> <ui:define name="top"> <h2>Welcome to our Site</h2> </ui:define> <ui:define name="left"> <h3>Links</h3> <ul> <li> <h:outputLink value="http://www.packtpub.com"> <h:outputText value="Packt Publishing"/> </h:outputLink> </li> <li> <h:outputLink value="http://www.ensode.net"> <h:outputText value="Ensode.net"/> </h:outputLink> </li> <li> <h:outputLink value="http://www.ensode.com"> <h:outputText value="Ensode Technology, LLC"/> </h:outputLink> </li> <li> <h:outputLink value="http://www.netbeans.org"> <h:outputText value="NetBeans.org"/> </h:outputLink> </li> <li> <h:outputLink value="http://www.glassfish. org"> <h:outputText value="GlassFish.org"/> </h:outputLink> </li> <li> <h:outputLink value="http://www.oracle.com/technetwork/ java/javaee/overview/index.html"> <h:outputText value="Java EE 6"/> </h:outputLink> </li> <li><h:outputLink value="http://www.oracle.com/ technetwork/java/index.html"> <h:outputText value="Java"/> </h:outputLink></li> </ul> </ui:define> <ui:define name="content"> <p> In this main area we would put our main text, images, forms, etc. In this example we will simply use the typical filler text that web designers love to use. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc venenatis, diam nec tempor dapibus, lacus erat vehicula mauris, id lacinia nisi arcu vitae purus. Nam vestibulum nisi non lacus luctus vel ornare nibh pharetra. Aenean non lorem lectus, eu tempus lectus. Cras mattis nibh a mi pharetra ultricies. In consectetur, tellus sit amet pretium facilisis, enim ipsum consectetur magna, a mattis ligula massa vel mi. Maecenas id arcu a erat pellentesque vestibulum at vitae nulla. Nullam eleifend sodales tincidunt. Donec viverra libero non erat porta sit amet convallis enim commodo. Cras eu libero elit, ac aliquam ligula. Quisque a elit nec ligula dapibus porta sit amet a nulla. Nulla vitae molestie ligula. Aliquam interdum, velit at tincidunt ultrices, sapien mauris sodales mi, vel rutrum turpis neque id ligula. Donec dictum condimentum arcu ut convallis. Maecenas blandit, ante eget tempor sollicitudin, ligula eros venenatis justo, sed ullamcorper dui leo id nunc. Suspendisse potenti. Ut vel mauris sem. Duis lacinia eros laoreet diam cursus nec hendrerit tellus pellentesque. </p> </ui:define> </ui:composition> </body> After making the above changes, our template client now renders as follows: As we can see, creating Facelets templates and template clients with NetBeans is a breeze.
Read more
  • 0
  • 0
  • 2265