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
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7019 Articles
article-image-understand-and-use-microsoft-silverlight-javascript
Packt
24 Oct 2009
10 min read
Save for later

Understand and Use Microsoft Silverlight with JavaScript

Packt
24 Oct 2009
10 min read
We have come a long way from the day the WEB was created in 1992 by T.B.LEE in Switzerland. From hyper linking which was the only thing at that time, to streaming videos, instant gratification with AJAX, and a host of other do-dads that has breathed new life to JavaScript and internet usability. Silverlight among several others, is a push in this direction to satisfy the ever increasing needs of the internet users. Even so, the web application displays fall short of the rich experience one can achieve with desktop applications, and this is where the tools are being created and honed for creating RIA, short for Rich Internet Applications. In order to create such applications, a great deal of development has taken place in the Microsoft ecosystem . These are all described in the .NET and Windows Presentation Foundation which supports developers to create easily deployable Rich Internet Applications. We have to wait and see how it percolates to the Semantic Web in the future. Silverlight is a cross-platform, cross-browser plug-in that renders XAML, the declarative tag-based files while exposing the JavaScript programming interface. It makes both developers and designers to collaborate and contribute to rich and interactive designs that are well integrated with Microsoft's Expression series of programs. Initial Steps to Take In this article we will be using Silverlight 1.0 with JavaScript. Initially you need to make your browser understand the XAML, and for this you need to install Silverlight available here. There is no need for a server to work with these Silverlight application files as they will be either HTML pages, XAML pages, or JavaScript pages. Of course these files may be hosted on the server as well. The next figure shows some details you need to know before installing the plug-in. Silverlight Project Details After having enabled the browser to recognize XAML - the Extensible Application Mark up Language, you need to consider the different components that will make Silverlight happen. In the present tutorial we will look at using Silverlight 1.0. Silverlight 2.0 is still in Beta stage. If you have Silverlight already installed you may be able to verify the version in the Control Panel / Add Remove Programs and display information as shown in the next figure. To make Silverlight happen you need the following files: An HTML page that you can browse to where the Silverlight plug-in is spawned A XAML page which is all the talk is about which provides the 'Richness' Supporting script files that will create the plug-in and embeds it in the HTML page The next figure shows how these interact with one another somewhat schematically. Basically you can start with your HTML page. You need to reference two .JS files as shown in the above figure. The script file Silverlight.js exposes the properties, methods, etc. of Silverlight. This file will be available in the SDK download. You can copy this file and move it around to any location. The second script createSilvelight.js creates a plug-in which you will embed in the HTML page using yet another short script. You will see how this is created later in the tutorial. The created plug-in then brings-in the XAML page which you will create as well. The first step is to create a blank HTML page, herein called, TestSilverLight.htm as shown in the following listing: Listing 1:TestSilverLight.htm Scaffold file <html><head><script type="text/javascript" src="Silverlight.js"></script><script type="text/javascript" src="createSilverlight.js"></script><title> </title> </head> <body> Next, you go ahead and create the createSilvelight.js file. The following listing shows how this is coded. This is slightly modified although taken from a web resource. Listing 2: createSilverlight.js function createSilverlight() { Silverlight.createObject( "TestSilver.xaml", // Source property value. parentElement, // DOM reference to hosting DIV tag. "SilverlightPlugInHost1", // Unique plug-in ID value. { // Plug-in properties. width:'1024', // Width of rectangular in pixels. height:'530', // Height of rectangular in pixels. inplaceInstallPrompt:false, // install prompt if invalid version is detected. background:'white', // Background color of plug-in. isWindowless:'false', // Determines whether to display in windowless mode. framerate:'24', // MaxFrameRate property value. version:'1.0' // Silverlight version. }, { onError:null, // OnError property value onLoad:null // OnLoad property value }, null, // initParams null); // Context value } This function, createSilverlight(), when called from within a place holder location will create a Silverlight object at that location with some defined properties. You may go and look up the various customizable items in this code on the web. The object that is going to be created will be the TestSilver.xaml at the "id" of the location which will be found using the ECMA script we will see later. The "id" is also named here, found by the "parentElement". To proceed further we need to create (a) the TestSilver.xaml file and (b) create a place holder in the HTML page. At first the changes made to Listing 1 are shown in bold. This is the place holder <div> </div> tags inside the 'body' tags as shown in the next listing with the "id" used in the createSilverlight.js file. You may also use <span> </span> tags, provided you associate a "id" with it. Listing 3: Place holder created in the HTML Page <head><script type="text/javascript" src="Silverlight.js"></script><script type="text/javascript" src="createSilverlight.js"></script><title> </title> </head> <body><div id="SilverlightPlugInHost1"> </div></body> </html> Creating the XAML File If you have neither used XAML, nor created a XAML page you should access the internet where you will find tons of this stuff. A good location is MSDN's Silvelight home page. You may also want to read up this article which will give some idea about XAML. Although this article is focusing on 'Windows' and not 'Web', the idea of what XAML is the same. The next listing describes the declarative syntax that will show a 'canvas', a defined space on your web page in which an image has been brought in. The 'Canvas' is the container and the image is the contained object. A XAML file should be well formed similar to an XML file. Listing 4: A Simple XAML file <Canvas Width="200" Height="200" Background="powderblue"><Image Canvas.Left="50" Canvas.Top="50" Width="200"Source="Fish.JPG"/></Canvas> Save the above file (text) with the extension XAML. If your Silverlight 1.0 is working correctly you should see this displayed on the browser when you browse to it. You also note the [.] notation to access the properties of the Canvas. For example, Canvas.Left is 50 pixels relative to the Canvas. The namespace is very important, more about it later. Without going into too much details, the pale blue area is the canvas whose width and height are 200 pixels each. The fish image is off set by the amounts shown relative to the canvas. Canvas is the portion of the browser window which functions as a place holder. While you use "Canvas" in web, you will have "Window" for desktop applications. The namespace of the canvas should be as shown otherwise you may get errors of various types depending on the typos. Inside the canvas you may place any type of object, buttons, textboxes, shapes, and even other canvases. If and when you design using the Visual Studio designer with intellisense guiding you along you will see a bewildering array of controls, styles, etc. The details of the various XAML tags are outside the scope of this tutorial. Although Notepad is used in this tutorial, you really should use a designer as you cannot possibly remember correctly the various Properties, Methods and Events supported. In some web references you may notice one more additional namespace . Remove this namespace reference as "Canvas" does not exist in this namespace. If you use it, you will get an XamlParseException. Also if you are of the cut and paste type make sure you save the XAML file as of type "All files" with XAML extension. With the above brief background review the TestSilver.xaml file whose listing is shown in the next paragraph. Listing 5: TestSilver.xaml file referenced in Plug-in script <Canvas Width="200" Height="150" Background="powderblue"> <Canvas Width="150" Height="250" Background="PaleGoldenRod"> <Ellipse Width="100" Height="100" Stroke="Black" StrokeThickness="2" Fill="Green" /> </Canvas><Image Canvas.Left="50" Canvas.Top="50" Width="200" Source="http://localhost/IMG_0086.JPG"/></Canvas> In the above code you see a second canvas embedded inside the first with its own independent window. The order they would appear will depend on where they are in the code unless the default order is changed. You also see that the image is now referenced to a graphic file on the local server. Later on you will see the Silverlight.htm hosted on the server. If you are using more recent versions of ASP.NET used on your site, or version of IE you may get to see the complete file and some times you may get to see only part of the XMAL content and additional error message such as this one. For example, while the image in the project folder is displayed, the image on the local server may be skipped. If the setting and versions are optimum, you will get to see this displayed on your browser when you browse to the above file. Script in HTML to Embed Silverlight Plug-in This really is the last piece left to be taken care of to complete this project. The code shown in the next listing shows how this is done. The code segment shown in bold is the script that is added to the place holder we created earlier. Listing 6: Script added to bring Plug-in <html><head><script type="text/javascript" src="Silverlight.js"></script><script type="text/javascript" src="createSilverlight.js"></script><title> </title> </head> <body><div id="SilverlightPlugInHost1"> <script type="text/javascript"> var parentElement = document.getElementById("SilverlightPluginHost1"); createSilverlight();</script></div></body> </html> Hosted Files on the IIS The various files used are then saved to a folder and can be set up as the target of a virtual directory on your IIS as shown. Now you can browse the Silverlight123.htm file on your browser to see the following displayed on your IE. Summary The present tutorial shows how to create a Silverlight project describing the various files used and how they interact with each other. The importance of using the correct namespace and some tips on creating the XAML files as well as hosting them on IIS are also described. A Windows XP with SP2 was used and the Silverlight.htm file tested on IIS 5.1; IE Ver 7.0.5370IC and web site enabled for ASP.NET Version 2.0.50727 with the registered MimeType application/xaml+xml.
Read more
  • 0
  • 0
  • 5305

article-image-creating-and-managing-user-groups-joomla-and-virtuemart
Packt
24 Oct 2009
9 min read
Save for later

Creating and Managing User Groups in Joomla! and VirtueMart

Packt
24 Oct 2009
9 min read
User manager In Joomla!, there is one User Manager component from where you can manage the users of that site. However, for the VirtueMart component, there is another  user manager which should be used for the VirtueMart shop. To be clear about  the differences of these two user managers, let us look into both. Joomla! user manager Let us first try Joomla!'s user manager. Go to the Joomla! control panel and click on the User Manager icon or click on Site | User Manager. This brings the User Manager screen of Joomla!: We see that the users registered to the Joomla! site are listed in this screen. This screen shows the username, full name, enabled status, group that the user is assigned to, email of the user, date and time when they last visited, and user ID. From this screen, you may guess that any user can be enabled or disabled by clicking on the icon in the Enabled column. Enabled user accounts show a green tick mark in the Enabled column. For viewing the details of any user, click on that user's name in the Name column. That brings up the User:[Edit] screen: As you see, the User Details section shows some important information about the user including Name, Username, E-mail, Group, and so on. You can edit and change these settings including the password. In the Group selection box, you must select one level. The deepest level gets the highest permission in the system. From this section, you can also block a user and decide whether they will receive system  emails or not. In the Parameters section, you can choose the Front-end Language and Time Zone for that user. If you have created contact items using Joomla!'s Contacts component, you may assign one contact to this user in the Contact Information section. VirtueMart user manager Let us now look into VirtueMart's user manager. From the Joomla! control panel, select Components | VirtueMart to reach the VirtueMart Administration Panel. To view the list of the user's registered to the VirtueMart store, click on Admin | Users. This brings the User List screen: As you can see, the User List screen shows the list of users registered to the shop. The screen shows their username, full name, group the user is assigned to, and their shopper group. In the Group column, note that there are two groups mentioned. One group is without brackets and another is inside brackets. The group name mentioned inside brackets is Joomla!'s standard user groups, whereas the one without brackets is VirtueMart's user group. We are going to learn about these user groups in the  next section. For viewing the details of a user, click on the user's name in Username column. That brings the Add/Update User Information screen: The screen has three tabs: General User Information, Shopper Information, and Order List. The General User Information tab contains the same information which was shown in Joomla!'s user manager's User: [Edit] screen. The Shopper Information tab contains shop related information for the user: The Shopper Information section contains: a vendor to which the user is registered the user group the user belongs to a customer number/ID the shopper group Other sections in this tab are: Shipping Addresses, Bill To Information, Bank Account, and any other section you have added to the user registration or account maintenance form. These sections contain fields which are either available on the registration or account maintenance form. If the user has placed some orders, the Order List tab will list the orders placed by that user. If no order has been placed,  the Order List tab will not be visible. Which user manager should we use? As we can see, there is a difference between Joomla!'s user manager and VirtueMart's user manager. VirtueMart's user manager shows some additional information fields, which are necessary for the operation of the shop. Therefore, whenever you are managing users for your shop, use the user manager in the VirtueMart component, not Joomla!'s user manager. Otherwise, all customer information will not be added or updated. This may create some problems in operating the VirtueMart store. User Groups Do you want to decide who can do what in your shop? There is a very good way for doing that in Joomla! and VirtueMart. Both Joomla! and VirtueMart have some predefined user groups. In both cases, you can create additional groups and assign permission levels to these groups. When users register to your site, you assign them to one of the user groups. Joomla! user groups Let us first look into Joomla! user groups. Predefined groups in Joomla! are  described below: User Group Permissions Public Frontend Registered Users in this group can login to the Joomla! site and view the contents, sections, categories, and the items which are marked only for registered users. This group has no access to content management. Author Users in this group get all the permissions the Registered group has. In addition to that, users in this group can submit articles for publishing, and can edit their own articles. Editor Users of this group have all the above permissions, and also can edit articles submitted by other users. However, they cannot publish the contents. Publisher Users in this group can login to the system and submit, edit, and publish their own content as well as contents submitted by other users. Public Backend Manager Users in this group can login to the administration panel and manage content items including articles, sections, categories, links, and so on. They cannot manage users, install modules or components, manage templates and languages, and access global configurations. Users in this group can access some of the components for which the administrator has given permission. Administrator In addition to content management, users in this group can add a user to Super Administrator group, edit a user, access the global configuration settings, access the mail function, and manage/install templates and language files. Super Administrator Users in this group can access all administration functions. For every site, at least one should be in this group to perform global configurations. You cannot delete a user in this group or move him/her to another group. As you can see, most of the users registering to your site should be assigned to the Registered group. By default, Joomla! assigns all newly registered users to the Registered group. You need to add some users to the Editor or Publisher group if they need to add or publish content to the site. The persons who are managing the shop should be assigned to other Public Backend groups such as Manager, Administrator or Super Administrator. VirtueMart user groups Let us now look into the user groups in VirtueMart. To see the user groups, go to VirtueMart's administration panel and click on Admin | User Groups. This shows the User Group List screen: By default, you will see four user groups: admin, storeadmin, shopper, and demo. These groups are used for assigning permissions to users. Also, note the values in the User Group Level column. The higher the value in this field, the lower the permissions assumed for the group. The admin group has a level value of 0, which means it has all of the permissions, and of course, more than the next group storeadmin. Similarly, storeadmin group has more permissions than the shopper group. These predefined groups are key groups in VirtueMart, and you cannot modify or delete these groups. These groups have the following permissions: Group Permissions admin This group has permissions to use all of the modules except checkout and shop. The admin group does not need these because admin users usually do not shop in their store. storeadmin This group has fewer permissions than admin group. Users in this group can access all the modules except the admin, vendor, shop, and checkout modules. They cannot set the global configurations for the store, but can add and edit payment methods, products, categories, and so on. shopper This group has the least permission among the three key groups. By default, users registered to the shop are assigned to this group. Users in this group can fully access the account module, and can use some functions of the shop, coupon, and checkout modules. demo This is a demo group created by default so that administrators can test and play with it. For most of the shops, these four predefined groups will be enough to implement appropriate permissions. However, in some cases you may need to create a new user group and assign separate permissions to that group. For example, you may want to employ some people as store managers who will add products to the catalog and manage the orders. They cannot add or edit payment methods, shipping methods, or other settings, except product and orders. If you add these people to the storeadmin group then they get more permissions than required. In such situations, a good solution is to create a new group, add selected user accounts to that group, and assign permissions to that group. Creating a new user group For creating a new user group, click on the New button in the toolbar on the User Group List screen. This brings Add/Edit a User Group screen: In the Add/Edit a User Group screen, enter the group's name and group level. You must type a higher value than existing groups (for example, 1000). Click on the Save icon to save the user group. You will now see the newly created user group in the User Group List screen.
Read more
  • 0
  • 0
  • 8734

article-image-making-world-wide-web-easier-place-talk-about
Packt
24 Oct 2009
4 min read
Save for later

Making the World Wide Web an Easier Place to Talk About

Packt
24 Oct 2009
4 min read
Why do we still use WWW? If you were tasked with finding the letter that, when spoken out loud repeatedly, was more awkward than any other, you would come up with W. Every other letter in the English alphabet is pronounced with a single syllable, yet the W is unique in requiring an impressive three syllables to utter. The irony is that ‘World Wide Web’ can be said in just three syllables, yet the abbreviation WWW encounters a tongue-twisting nine! How can any abbreviation take three times the effort to speak than the very words it is an abbreviation of!? ‘duh-bull-you duh-bull-you duh-bull-you’. WWW is such a prolific term these days and so hard to verbalize that this abbreviation has been abbreviated further with phrases such as “dub dub dub” or “all the Ws”. Almost every website we use starts with WWW and mankind is desperately seeking a way to make the oration of these website addresses an easier and less embarrassing task. The answer, you may be surprised to hear, is shockingly easy. Don’t uses Ws! Websites don’t need them, we don’t like to speak them, the internet will run equally well without them. Addressing the Internet A website address is made up of 3 key parts. Take for example www.google.co.uk The google part combined with the .co.uk part makes up the domain name. When Google purchased this address they purchased google.co.uk, NOT www.google.co.uk. The .co.uk part typically indicates the country, or type of domain (known as Top Level Domain or TLD). The www part is a sub-domain that can indicate anything at all, or can even be omitted. When a domain such as google.co.uk is purchased, it is the web developer who decides what sub-domains should be used, and by following convention and perceived wisdom they will normally opt for WWW. Why do they do this when they could use anything or even nothing at all? Why not w.google.co.uk, or web.google.co.uk or why not just google.co.uk? Many web developers have seen the light and make sure that their websites work even when a sub-domain is omitted. Try browsing to google.co.uk for example, or yahoo.com, or digg.com, they all work just as well as the same domain names with the Ws. Forward Slash is killing me So now that we have freed up the sub-domain, let’s make some good use of it. How many times have you heard an advert for a website followed by ‘forward slash deals’ or similar. Forward slash gives us another three syllable description of a single punctuation character. Easy to type, annoying to verbalize. It sounds either crude or demonic, and the alternative ‘stroke’ is equally cringe-worthy. We like dots. DotCom is easy to say – and with sub-domains we can ditch the slashes and strokes in favor of the smallest punctuation mark with the shortest name. Try these examples... www.google.co.uk/adwords contains 22 syllables yet adwords.google.co.uk just 10. That’s less than half the time to read, less than half to remember and 17% less to type. If your website sells cars and bikes, you might currently use www.123autos.com/cars and www.123autos.com/bikes. How much more succinct it would be to use 123autos.com for the main website, cars.123autos.com for the car pages, and bikes.123autos.com for the bike pages? Drop ‘em This campaign is to encourage people to forget that WWW ever existed. Don’t type it, don’t speak it, and complain to every website that still requires it. Drop the forward slashes, strokes and hyphens too. The only punctuation that should be used is the mighty yet humble dot and to achieve this, sub-domains are your loyal friends. Let’s make the World Wide Web an easier place to talk about.
Read more
  • 0
  • 0
  • 1358

article-image-installing-sbs-2008-and-connecting-internet
Packt
24 Oct 2009
5 min read
Save for later

Installing SBS 2008 and Connecting to the Internet

Packt
24 Oct 2009
5 min read
SBS 2008 installation The installation process is split into two sections: Installation of the operating system and other files to the disk Installation of everything that makes it SBS 2008 You cannot separate the two or stop the second half from happening; although, you will be required to provide input to the server at each stage. Operating system installation If you are performing a migration from SBS 2003 to SBS 2008, you must have your USB memory stick with the SBSAnswerFile.xml file loaded onto the root directory. You must also have a network cable plugged into the SBS server, connected to a hub or switch, for the installation to succeed. Migrating to SBS 2008 in a virtual environment If you are installing SBS 2008 into a virtual machine, such as under Hyper-V from Microsoft then you cannot simply plug in a USB memory stick as USB ports are not available within the virtual machine. For the install process to read it, either you must add it as a pass-through hard disk or you can create a Virtual Floppy Disk with the file on it. To add the USB Disk as a hard disk in Hyper-V, mark it as offline in the DISKPART tool and then add it as a drive before starting the virtual machine. For detailed instructions, take a look at http://davidoverton.com/r.ashx?12. If you have a DVD for the system, insert the DVD and boot the system and follow the instructions to boot from a DVD for your system. You will normally have to press a key to start the process. You will see the grey bar progressing across the screen as the DVD is read. If you have a system from a hardware manufacturer then the operating system may already be installed on the hard disk. If this is the case, simply turn on the machine. If your machine will not boot from the DVD and you have a DVD drive on the system, then check the BIOS settings to ensure that the DVD is the first boot drive. You will then be asked to set the Language to install, Time and currency format, and Keyboard or input method to match your needs. If you are migrating, you must ensure that you have installed the USB memory stick before you click on the Install Now button. However, if you are performing a clean installation, then simply press the button. If you wish to carry out a trial installation that gives you 30 days without activating your installation and fixing your hardware to your product key, do not enter a product key into the Product key box. If you are performing your final installation, then enter the key from the SBS 2008 package or the Certificate of Authenticity on the system case if SBS was pre-installed on the server. If you do not enter a product key, you will be prompted to enter the key within 30 days. You can extend the time without a key, but ultimately, you will need to activate SBS 2008 to continue using it. Next, accept the license and click on Next. Select the Custom (advanced) installation option. You should see one or more disks presented to you in a list. There are two schools of thought here on how to configure the first disk. One school has all the data on the first (or primary) partition and the other creates two partitions and splits the data and the operating system. The idea here is that the system partition can be correctly sized and backed up with a different strategy to the data partition. You can also easily move the second partition onto larger disks should there be a need to in the future. There are merits to both arguments, but if you only have a single disk, I would simply select this and install SBS 2008 to this disk without partitioning first. For SBS 2008, this should be absolutely fine as your data needs are not going to grow too rapidly. If you do have significant data requirements with multiple disks, then having the data and system separate does make sense. No hard disks showing If you do not see a hard disk shown in the screen, maybe because you need to load RAID disk drivers, click on the Load Driver button and insert the CD or floppy disk that came with your computer or motherboard. Provided your system supports Windows 2008, this will resolve this problem. Let's have a look at the following screenshot: Click on Next and the actual installation will finally start and take over an hour to complete. You will find yourself watching the progress on a screen similar to the one shown in the following screenshot. There is no interaction to this process, which means it can just be left on its own; however, it is best to check in ever so often to ensure that an error message has not interrupted the installation. The only error I've seen was when there was a read error from my DVD (I had scratched it!). I cleaned the disk and re-started the install again without any issue.
Read more
  • 0
  • 0
  • 2501

article-image-aspnet-repeater-control
Packt
23 Oct 2009
6 min read
Save for later

The ASP.NET Repeater Control

Packt
23 Oct 2009
6 min read
The Repeater control in ASP.NET is a data-bound container control that can be used to automate the display of a collection of repeated list items. These items can be bound to either of the following data sources: Database Table XML File In a Repeater control, the data is rendered as DataItems that are defined using one or more templates. You can even use HTML tags such as <li>, <ul>, or <div> if required. Similar to the DataGrid, DataList, or GridView controls, the Repeater control has a DataSource property that is used to set the DataSource of this control to any ICollection, IEnumerable, or IListSource instance. Once this is set, the data from one of these types of data sources can be easily bound to the Repeater control using itsDataBind() method. However, the Repeater control by itself does not support paging or editing of data. The Repeater control is light weight and does not contain so many features as the DataGrid contains. However, it enables you to place HTML code in its templates. It is great in situations where you need to display the data quickly and format the data to be displayed easily. Using the Repeater Control The Repeater control is a data-bound control that uses templates to display data. It does not have any built-in support for paging, editing, or sorting of the data that is rendered through one or more of its templates. The Repeater control works by looping through the records in your data source and then repeating the rendering of one of its templates called the ItemTemplate, one that contains the records that the control needs to render. To use this control, drag and drop the control in the design view of the web form onto a web form from the toolbox. Refer to the following screenshot: You can also drag and drop the Repeater control from the toolbox onto the source view directly. This is shown in the following screenshot: For customizing the behavior of this control, you have to use the built-in templates that this control comes with. These templates are actually blocks of HTML code. The Repeater control contains the following five templates: HeaderTemplate ItemTemplate AlternatingItemTemplate SeparatorTemplate FooterTemplate The following screenshot shows how a Repeater control looks when populated with data. Note that the templates (Header, Item, Footer, Alternate and Separator) have all been used. The following code snippet is an example of the order in which the templates of the Repeater control are used. <asp:Repeater id="repEmployee" runat="server"><HeaderTemplate>...</HeaderTemplate><ItemTemplate></ItemTemplate><FooterTemplate>...</FooterTemplate></asp:Repeater> When the Repeater control is bound to a data source, the data from the data source is displayed using the ItemTemplate element and any other optional elements, if used. Note that the contents of the HeaderTemplate and the FooterTemplate are rendered once for each Repeater control. The contents of the ItemTemplate are rendered for each record in the control. You can also use the additional AlternatingItemTemplate element after the ItemTemplate element for specifying the appearance of each alternate record. You can also use the SeparatorTemplate element between each record for specifying the separators for the records. Displaying Data Using the Repeater Control This section discusses how we can display data using the Repeater control. As discussed earlier, the Repeater control uses templates for formatting the data that it displays. The following code snippet displays the code in an .aspx file that contains a Repeater control. Note that we would be making use of templates and that the data would be bound to the control from the code-behind file using the DataManager class. The Repeater control is populated with data in the Page_Load event by reusing the DataManager(). Note how the SeparatorTemplate and the AlternatingItemTemplate have been used in the previous code example. Further, the DataBinder.Eval() method has been used to display the values of the corresponding fields from the data container, (in our case, the DataSet instance) in the Repeater control. The FooterTemplate uses the Total Records variable and substitutes its value to display the total number of records displayed by the control. The following is the output on execution. The Header and the Footer templates of the Repeater control are still rendered even if the data source does not contain any data. If you want to suppress their display, you can use the Visible property of the Repeater control and use it to suppress the display of these templates with a simple logic. Here is how you specify the Visible property of this control in your .aspx file to achieve this_Visible="<%# Repeater1.Items.Count > 0 %>"When you specify the Visible property as shown here, the Repeater is made visible only if there are records in your data source.   Displaying Checkboxes in a Repeater Control Let us now understand how we can display checkboxes in a Repeater Control and retrieve the number of checked items. We will use a Button control and a Label control in our page. When you click on the Button control, the number of checked items in the Repeater Control will be displayed in the Label control. The output on execution is similar to what is shown in the following screenshot: Here is the code that we will use in the .aspx file to display checkboxes in a Repeater control. The data is bound to the Repeater control in the Page_Load event as follows: Note that we have used the Page.IsPostBack to check whether the page has posted back in the Page_Load method. If you don't bind data by checking whether the page has posted back, the Repeater control will be rebound to data once again after a postback and all the checkboxes in your web page will be reset to the unchecked state. The source code for the click event of the Button control that we have used is as follows: When you execute the application, the Repeater control is displayed with records from the employee table. Now you check one or more of the checkboxes and then click on the Button control just beneath the Repeater control as follows: Note that the number of checked records is displayed in the Label Control. Summary This article discussed the Repeater control and how we can use it in ourASP.NET applications. Though this control does not support all the functionalities of other data controls, like DataGrid and GridView, it is still a good choice if you want faster rendering of data as it is light weight, and is very flexible.
Read more
  • 0
  • 0
  • 5278

article-image-service-oriented-java-business-integration-whats-whys
Packt
23 Oct 2009
4 min read
Save for later

Service Oriented Java Business Integration - What's & Why's

Packt
23 Oct 2009
4 min read
Many of you as (Java) programmers generate business purpose code, like "confirming an order" or "find available products". At times, you may also want to connect to external systems and services, since your application in isolation alone will not provide you the required functionality. When the number of such connections increases, you would be generating more and more of "integration code", mixed along with your business code. For single or simple systems and services this is fine, but what if your "Enterprise" has got many (say 100? or even more...) such systems and services to be integrated together? Here, integration becomes a prime concern, which is separate from fulfilling your business concerns. In the SOA context, we will have services fulfilling your business use cases. Existing Java tools help us to define services. But are they enough to support Service Oriented Integration (SOI)? Perhaps not, and this is where JSR-208 (Java Specification Request) introduces the Java Business Integration (JBI) specification. And in the world of integration, we have multiple Architectures to follow including the Point-to-Point, Hub-and-Spoke, Message-Bus and the Service-Bus. Each of them have their own advantages and disadvantages, and the Enterprise Service Bus (ESB) is an Architectural pattern best suited for doing SOI. This book provides a consistent style and visual representations to describe the message flows in sample scenarios, which helps the reader to understand the code samples fully. This book also presents practical advice on designing code that connects services together, based again on practical experiences gathered over the last one decade in java business integration. I believes in "Practice What You Preach" and hence equips you with enough tools to "Practice What You Read". What does the book have to offer? or What does it teach? This book introduces ESB - The book guarantees you understand ESB and can also code for ESB. This book introduces JBI - The book don't reproduce specification, but give you just enough highlights alone. Teaches you ServiceMix - ServiceMix is an Apache Open source Java ESB. The book teach you from step 1 of installation Teaches you to implement practical scenarios - Proxies, Web Services gateway, web services over JMS, service versioning, etc. Implementation for EIP - Gives you code on how to implement Enterprise Integration Patterns by Gregor Hohpe and Bobby Woolf For more, have a glance through the Table of Contents [PDF] Who would benefit from it? Any Java/J2EE enthusiast, who wants to know something more than daily POJO, Spring & Hibernate Developers & Architects who deals with integration Developers & Architects who don't consciously deal with integration - its high time for you to seperate out spaghetti integration aspects from your business purpose code - for that, you need to first understand and sense integration! Even people with Non-Java background - My .NET peers, don't envy on the lightweight approaches described in this book using java tools. The integration is done mostly in XML configurations with minimum java code, and you too can benefit from the literature. Anything special about the book First book published on JBI First book published on Apache ServiceMix First book which shows you how to integrate following ESB, using lightweight tools. A book with code, which makes you feel running and seeing the code in action, even without actually running the code (nothing prevents you from trying the samples). You can go though a Sample Chapter here: JBI-Bind-Web-Services-in-ESB-Gateway.pdf [1 MB] No heavy Workshops, IDEs, Studios, Plugins or 4GB RAM required - Use a text editor and Apache Ant, and you can run the samples. Based on existing knowledge on web services Authored and reviewed by practicing Architects, who are developers too in their everyday role. What this book is not about? Not a collection of white papers alone - The book provide you implementation samples. Not a repetition of ServiceMix online documentation - The book provide practical scenarios as samples Not about JBI Service Provider Interface (SPI) - Hence this book is not for tool vendors, but for developers Fine, if you think you need some starters before the real chill, you can go through the article titled Aggregate Services in ServiceMix JBI ESB
Read more
  • 0
  • 0
  • 1622
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 €18.99/month. Cancel anytime
article-image-microsoft-sql-server-2008-installation-made-easy
Packt
23 Oct 2009
3 min read
Save for later

Microsoft SQL Server 2008 - Installation Made Easy

Packt
23 Oct 2009
3 min read
(For more resources on Microsoft, see here.) Initial State of Computer Assuming you are working with the Windows XP OS, it will be advisable to create a restore point to which you can fall back should you fail to install and something goes wrong. You can set up a fall back position by going to Start | All Programs | Accessories | System Tools | System Restore. This allows you to comeback where you were before starting the install. The other thing that you should lookup is the suite of Microsoft software you already have on your computer that may interfere with the product you are installing. This can be reviewed following Start | Control Panel | Add and Remove Programs. SQL 2008 server requires IE 6.0 or higher version. It may be helpful to install this before embarking on installing the SQL 2008 Server. For the purpose of this article IE 7.0 was installed. It has appeared in some forum topics that SQL 2008 can exist side-by-side with SQL 2005 server. However in the present case SQL 2005 was completely removed. Sometimes even this removal is not quite an easy process if something is broken in the original install and requires you to reinstall and then uninstall. In the case of SQL Server 2008, there was an earlier version, "Katmai", installed but never used due to its inability to connect to the SQL Server Management Studio (Well, unless you remove the SQL 2005 client you cannot install SQL 2008 Client), a fact which came to light much later. 'Katmai' components were completely removed which required reinstalling the 'Katmai' followed by its complete removal. When you download the SQL 2008 and run the executable, it creates the folder, servers, containing a number of subfolders and files (dynamic link library files etc) that are used during the installation. Help can be accessed from servershelp1033s10ch_setup, an HTML file which provides a wealth of information regarding all aspects of installation including migration from an earlier version. From servesdefault.htm you can begin the installation which provides the required support using Prepare | Install | Other information navigational aid. After removing all the suggested components during this installation, the remaining Microsoft SQL Server related components on the computer are as shown in the Add and Remove Programs window in the next figure. The very first screen you will see when you click on the serverssetup.exe file is the SQL Server 2008 Setup where you need to agree with the licensing terms before proceeding. When you click on the Next button which displays the Installation Pre-requisites screen, you will be shown the pending items needed before you install SQL 2008 server. Click on the Install button after highlighting the pending item regarding setup support files in the right screen. SQL Server Installation Center This will take you to the SQL Server Installation Center screen as shown. It has a number of useful hyperlinks that you can come back to by repeating the above steps. Click on New Installation link. This Starts Install SQL Server 2008 Wizard for System Configuration Check. After a while when the checking is completed the following screen will be displayed. This timeall items have the status marked 'Passed'. In a previous attempt when the 'Katmai' items were still uninstalled,the Previous CTP Install Check did not succeed and it was corrected only after completely removing those items. Clicking on Next button takes you to screen where you need to select the features that you want to have installed as shown. The display shows Features Selection window after all items have been checked.
Read more
  • 0
  • 0
  • 4074

article-image-designing-and-creating-database-tables-ruby-rails
Packt
23 Oct 2009
9 min read
Save for later

Designing and Creating Database Tables in Ruby on Rails

Packt
23 Oct 2009
9 min read
Background Information The User Management Module is created for a website called 'TaleWiki'. TaleWiki is a website about user submitted tales and stories, which can be added, modified, deleted, and published by the user, depending on the Role or Privileges the user has. Taking into consideration this small piece of information, we will design and create tables that will become the back-end for the User Management functionality. Designing the Tables To Design and to create tables, we need to understand the entities and their relationship, the schema corresponding to the entities, and then the table creation queries. If we go step-by-step, we can say that following are the steps in designing the tables for the User Management module: Designing the E-R model Deriving the Schema from the E-R model Creating the Tables from the Schema So, let us follow the steps. Designing the E-R Model To design the E-R model, let us first look at what we have understood about the data required by the functionalities, which we just discussed. It tells us that 'only the Users with a particular Role can access TaleWiki'. Now we can consider this as our 'problem statement' for our E-R model design. If you observe closely, the statement is vague. It doesn't tell about the particular Roles. However, for the E-R design, this will suffice as it clearly mentions the two main entities, if we use the E-R terminology. They are: User Role Let us look at the User entity. Now this entity represents a real-world user. It is not difficult to describe its attributes. Keeping a real-world user in mind and the functionalities discussed for managing a user, we can say that the User entity should have the following attributes: Id: It will identify the different users, and it will be unique. User name: The name which will be displayed with the submitted story. Password: The pass key with which the user will be authenticated. First name: The first name of the user. Last name: The last name of the user. The combination of the first and last name will be the real name of the user. Age: The age of the user. This will help in deciding whether or not the user is of required age which is 15. E-mail id: The email id of the user in which he/she would like to get emails from the administrator regarding the submissions. Country: To keep track of the 'geographic distribution' of users. Role: To know what privileges are granted for the user. The Role is required because the problem statement mentions "User with a particular Role". The entity diagram will be as follows: Next, let us look at the Role entity. Role, as already discussed, will represent the privileges a user can have. And as these privileges are static, the Role entity won't need to have the attribute to store the privileges. The important point about the static privileges that you have to keep in mind is that they will have to be programmatically checked against a user. In other words, the privileges are not present in the database and there can only be a small number of Roles with predefined privileges. Keeping this in mind, we can say that the Role entity will have the following attributes: Id: The unique identification number for the Role. Name: The name with which the id will be known and that will be displayed along with the user name. The entity diagram for Role entity will be as follows: We have completed two out of three steps in designing the E-R model. Next, we have to define how the User entity is related with the Role entity. From the problem statement we can say that a user will definitely have a Role. And the functionality for assigning the Role tells us that a user can have only one Role. So if we combine these two, we can say that 'A user will have only one Role but different users can have the same Role'. In simple terms, a Role—let us say normal user—can be applied to different users such as John, or Jane. However, the users John or Jane cannot be both normal user as well as administrator. In technical terms, we can say that a Role has a one-to-many relationship with the User entity and a User has a many-to-one relationship with a Role. Diagrammatically, it will be as follows: One piece of the puzzle is still left. If you remember there is one more entity called Story. We had found that each story had a submitter. The submitter is a user. So that means there is a relationship between the User and the Story entity. Now, a user, let us say, John or Jane, can submit many stories. However, the same story cannot be submitted by more than one user. On the basis of this we can say that a User has a many-to-one relationship with a Story and a Story has a many-to-one relationship with a User. According to the E-R diagram it will be as follows: The final E-R design including all the entities and the attributes will be as follows: That completes our E-R design step. Next, we will derive the schema from theE-R model. Deriving the Schema We have all we need to derive the schema for our purpose. While deriving a schema from an E-R model, it is always a good choice to start with the entities at the 'one' end of a 'one-to-many' relationship. In our case, it is the Role entity. As we did in the previous chapter, let us start by providing the details for each attribute of the Role entity. The following is the schema for the Role entity: Attribute Data type of the attribute Length of the acceptable value Id Integer 10 Name Varchar 25 >Next, let us look at the schema of the User entity. As it is at the 'many' end of the 'one-to-many' relationship, the Role attribute will be replaced by the Id of Role. The schema will be as follows: Attribute Data type of the attribute Length of the acceptable value Id Integer 10 User name Varchar 50 First name Varchar 50 Last name Varchar 50 Password Varchar 15 Age Integer 3 e-mail id Varchar 25 Country Varchar 20 Id of the Role Integer 10 Now, let us visit the Story entity. The attributes of the entity were: Id: This is the Primary key attribute as it can uniquely identify a story. Heading: The title of the story. Body text: The body of the story. Date of Submission: The day the user submitted the story. Source: The source from where the story was found. If it is written by the user himself/herself, the source will be the user's id. Genre: The category of the story. User: The user who submitted the story. Name of the attribute Data type of the attribute Length of the acceptable value Id Integer 10 Title Varchar 100 Body Text Varchar 1000 Date of Submission Date   Source Varchar 50 Status Varchar 15 Id of Genre Integer 10 Id of the User Integer 10 The schema has been derived and now we can move to the last part of the database design—creation of the tables. Creating the Tables Looking at the schema  required for tables in Ruby on Rails, here is the table creation statement for the Role schema: CREATE TABLE `roles` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`name` VARCHAR( 25 ) NOT NULL ,`description` VARCHAR( 100 ) NOT NULL) ENGINE = innodb; Next comes the table creation statement for the User schema. Note that here also we are following the one-to-many path, that is, the table at the 'one' end is created first. Whenever there is a one-to-many relationship between entities, you will have to create the table for the entity at the 'one' end. Otherwise you will not be able to create a foreign key reference in the table for the entity at the 'many' end, and if you try to create one, you will get an error (obviously). So here is the create table statement for the User schema: CREATE TABLE `users` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`user_name` VARCHAR( 50 ) NOT NULL ,`password` VARCHAR( 15 ) NOT NULL ,`first_name` VARCHAR( 50 ) NOT NULL ,`last_name` VARCHAR( 50 ) NOT NULL ,`age` INT( 3 ) NOT NULL ,`email` VARCHAR( 25 ) NOT NULL ,`country` VARCHAR( 20 ) NOT NULL ,`role_id` INT NOT NULL,CONSTRAINT `fk_users_roles` FOREIGN KEY (`role_id`) REFERENCES `role`( `id`) ON DELETE CASCADE) ENGINE = innodb; Next, let us create the table for Story, we will call it the 'tales' table, we will also add a foreign key reference to the users table in it. Here is the query for creating the table CREATE TABLE `tales` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,`title` VARCHAR( 100 ) NOT NULL,`body_text` TEXT NOT NULL,`submission_date` DATE NOT NULL,`source` VARCHAR( 50 ) NOT NULL,`status` VARCHAR( 15 ) NOT NULL,`genre_id` INT NOT NULL,`user_id` INT NOT NULL,CONSTRAINT `fk_tales_genres` FOREIGN KEY (`genre_id`) REFERENCES genres( `id`)) ENGINE = innodb; Next, we will make a reference to the users table after executing the above query, with the following query: ALTER TABLE `tales` ADD FOREIGN KEY ( `user_id` ) REFERENCES `users` (`id`) ON DELETE CASCADE ; That completes our task of creating the required tables and making necessary changes to the tales table. The effect of this change will be visible to you when we implement session management in the next chapter. And incidentally, it completes the 'designing the tables' section. Let us move onto the development of the user management functionality. Summary In this article, we learned how to design and create tables for a User Management Module in Ruby on Rails. We looked at designing the E-R model, deriving the schema from the E-R model and creating the tables from the schema.
Read more
  • 0
  • 0
  • 5065

article-image-minilang-and-ofbiz
Packt
23 Oct 2009
11 min read
Save for later

Minilang and OFBiz

Packt
23 Oct 2009
11 min read
What is Minilang? The syntax of Minilang is simply well formed XML. Developers write XML that obeys a defined schema, this XML is then parsed by the framework and commands are executed accordingly. It is similar in concept to the Gang of Four Interpreter Pattern. We can therefore consider Minilang's XML elements to be "commands". Minilang is usually written in a simple method's XML file, which is specified at the top of the document like this: xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/ simple-methods.xsd"> Although Minilang's primary use is to code services and events, concepts from Minilang are also used to prepare data for screen widgets. Much of the simplicity of Minilang arises from the fact that variables are magically there for us to use. They do not have to be explicitly obtained, they are placed in the environment and we can take them as we wish. Should we wish to create a Map, we just use it, the framework will take care of its creation. For example: <set field="tempMap.fieldOne" from-field="parameters.fieldOne"/> will set the value of the fieldOne parameter to tempMap. If tempMap has already been used and is available, this will be added. If not, the Map will be created and the value added to the key fieldOne. Tools to Code XML Minilang is coded in XML and before it can be successfully parsed by the framework's XML parser, this XML must be well formed. Trying to code Minilang in a plain text editor like Notepad is not a wise move. Precious time can be wasted trying to discover a simple mistake such as a missing closing tag or a misspelled element. For this reason, before attempting to code Minilang services, make sure that you have installed some kind of XML editor and preferably one with an auto-complete feature. The latest versions of Eclipse come packaged with one and XML files are automatically associated to use this editor. Alternatively there are many editors available to download of varying functionality and price. For example XML Buddy (http://www.xmlbuddy.com), oXygen XML Editor (http://www.oxygenxml.com), or the heavyweight Altova XMLSpy (http://www.altova.com) Defining a Simple Service Minilang services are referred to as "simple" services. They are defined and invoked in the same way as a Java service. They can be invoked by the control servlet from the controller.xml file or from code in the same way as a Java service. In the following example we will write a simple service that removes Planet Reviews from the database by deleting the records. First open the file ${component:learning}widgetLearningForms.xml and find the PlanetReviews Form Widget. This widget displays a list of all reviews that are in the database. Inside this Form Widget, immediately under the update field element add: <field name="delete"><hyperlink target="RemovePlanetReview?reviewId=${reviewId}" description="Delete"/></field> Our list will now also include another column showing us a hyperlink we can click, although clicking it now will cause an error. We have not added the request-map to handle this request in the controller.xml. It will be added a little later. Defining the Simple Service In the file ${component:learning}servicedefservices.xml add a new service definition: <service name="learningRemovePlanetReview" engine="simple" location="org/ofbiz/learning/learning/LearningServices.xml" invoke="removePlanetReview"> <description>Service to remove a planet review</description> <attribute name="reviewId" type="String" mode="IN" optional="false"/> </service> Note that the engine type is simple. It is a common practice to group service definitions into their own XML file according to behavior. For instance, we may see that all services to do with Order Returns are in a file called services_returns.xml. So long as we add the <service-resource> element to the parent component's ofbiz-component.xml file and let the system know that this service definition file needs to be loaded, we can structure our service definitions sensibly and avoid huge definition files. It is not a common practice, however, to group service definitions by type. The type is abstracted from the rest of the system. When the service is invoked, the invoker doesn't care what type of service it is. It could be Java, it could be a simple service, it doesn't matter. All that matters is that the correct parameters are passed into the service and the correct parameters are passed out. For this reason, simple service definitions are found in the same XML files as Java service definitions. Writing the Simple Method Simple Method XML files belong in the component's script folder. In the root of ${component:learning} create the nested directory structure scriptorgofbizlearninglearning and in the final directory create a new file called LearningServices.xml. Before we add anything to this file we must make sure that the script directory is on the classpath. Open the file ${component:learning}ofbiz-component.xml and if it is not already there add <classpath type="dir" location="script"/> immediately underneath the other classpath elements. The location specified in the service definition can now be resolved. In our newly created file LearningServices.xml add the following code: <simple-methods xsi:noNamespaceSchemaLocation="http://www.ofbiz.org/dtds/ simple-methods.xsd"> <simple-method method-name="removePlantetReview" short-description="Delete a Planet Review"> <entity-one entity-name="PlanetReview" value-name="lookedUpValue"/> <remove-value value-name="lookedUpValue"/> </simple-method> </simple-methods> Finally all that is left is to add the request-map to the controller.xml: <request-map uri="RemovePlanetReview"> <security auth="true" https="true"/> <event type="service" invoke="learningRemovePlanetReview"/> <response name="success" type="view" value="ListPlanetReviews"/> <response name="error" type="view" value="ListPlanetReviews"/> </request-map> Since we have added a new service definition OFBiz must be restarted. A compilation is not needed. Restart and fire an http request ListPlanetReviews to webapp learning: Selecting Delete will delete this PlanetReview record from the database. Let's take a closer look at the line of code in the simple service that performs the lookup of the record that is to be deleted. <entity-one entity-name="PlanetReview" value-name="lookedUpValue"/> This command will perform a lookup on the PlanetReview entity. Since the command is <entity-one> the lookup criteria must be the primary key. This code is equivalent in Java to: GenericValue lookedUpValue = delegator.findByPrimaryKey ("PlanetReview", UtilMisc.toMap("reviewId", reviewId)); Already we can see that Minilang is less complicated. And this is before we take into account that the Java code above is greatly simplified, ignoring the fact that the delegator had to be taken from the DispatchContext, the reviewId had to be explicitly taken from the context Map and the method call had to be wrapped in a try/catch block. In Minilang, when there is a look up like this, the context is checked for a parameter with the same name as the primary key for this field, as specified in the entity definition for PlanetReview. If there is one, and we know there is since we have declared a compulsory parameter reviewId in the service definition, then the framework will automatically take it from the context. We do not need to do anything else. Simple Events We can call Minilang events, in the same way that we called Java events from the controller.xml. Just as Minilang services are referred to as simple services, the event handler for Minilang events is called "simple". Tell the control servlet how to handle simple events by adding a new <handler> element to the learning component's controller.xml file, immediately under the other <handler> elements: <handler name="simple" type="request" class="org.ofbiz.webapp.event.SimpleEventHandler"/> A common reason for calling simple events would be to perform the preparation and validation on a set of parameters that are passed in from an XHTML form. Don't forget that when an event is called in this way, the HttpServletRequest object is passed in! In the case of the Java events, it is passed in as a parameter. For simple events, it is added to the context, but is nonetheless still available for us to take things from, or add things onto. In the same location as our LearningServices.xml file (${component:learning} scriptorgofbizlearninglearning) create a new file called LearningEvents.xml. To this file add one <simple-method> element inside a <simple-methods> tag: <simple-methods xsi:noNamespaceSchemaLocation="http://www.ofbiz.org/dtds/ simple-methods.xsd"> <simple-method method-name="simpleEventTest" short-description="Testing a simple Event"> <log level="info" message="Called the Event: simpleEventTest"/> </simple-method> </simple-methods> Finally, we need to add a request-map to the controller from where this event will be invoked: <request-map uri="SimpleEventTest"> <security auth=true»https=true/> <event type=»simple»path=»org/ofbiz/learning/learning/ LearningEvents.xml»invoke=»simpleEventTest»/> <response name=»success»type=»view»value=»SimplestScreen»/> <response name=»error»type=»view»value=»SimplestScreen»/> </request-map> Notice our simple method doesn't actually do anything other than leave a message in the logs. It is with these messages that we can debug through Minilang. Validating and Converting Fields We have now met the Simple Methods Mini-Language, which is responsible for general processing to perform simple and repetitive tasks as services or events. Validation and conversion of parameters are dealt with by another type of Minilang—the Simple Map Processor. The Simple Map Processor takes values from the context Map and moves them into another Map converting them and performing validation checks en-route. Generally, Simple Map Processors will prepare the parameters passed into a simple event from an HTML form or query string. As such, the input parameters will usually be of type String. Other object types can be validated or converted using the Simple Map Processor including: BigDecimals, Doubles, Floats, Longs, Integers, Dates, Times, java.sql.Timestamps, and Booleans. The Simple Map Processors are, like simple methods, coded in XML and they adhere to the same schema (simple-methods.xsd). Open this file up again and search for The Simple Map Processor Section. The naming convention for XML files containing Simple Map Processors is to end the name of the file with MapProcs.xml (For example, LearningMapProcs.xml) and they reside in the same directory as the Simple Services and Events. One of the best examples of validation and conversion already existing in the code is to be found in the PaymentMapProcs.xml file in ${component:accounting}scriptorgofbizaccountingpayment. Open this file and find the simple-map-processor named createCreditCard. Here we can see that immediately, the field expireDate is created from the two parameters expMonth and expYear with a "/" placed in between (example, 09/2012): <make-in-string field="expireDate"> <in-field field="expMonth"/> <constant>/</constant> <in-field field="expYear"/> </make-in-string> Towards the end of the <simple-map-processor> this expireDate field is then copied into the returning Map and validated using isDateAfterToday. If the expiration date is not after today, then the card has expired and instead, a fail-message is returned. <process field="expireDate"> <copy/> <validate-method method="isDateAfterToday"> <fail-message message="The expiration date is before today"/> </validate-method> </process> The <validate-method> element uses a method called isDateAfterToday. This method is in fact a Java static method found in the class org.ofbiz.base.util.UtilValidate. We have already been using one of the OFBiz utility classes, UtilMisc, namely the toMap function, to create for us Maps from key-value pairs passed in as parameters. OFBiz provides a huge number of incredibly useful utility methods, ranging from validation, date preparation, and caching tools to String encryption and more. The framework will automatically allow Minilang access to this class. By adding a bespoke validation method into this class and recompiling, you will be able to call it from the <validate-method> in Minilang, from anywhere in your application.
Read more
  • 0
  • 0
  • 2371

article-image-catalyst-web-framework-building-your-own-model
Packt
23 Oct 2009
12 min read
Save for later

Catalyst Web Framework: Building Your Own Model

Packt
23 Oct 2009
12 min read
Extending a DBIx::Class Model A common occurrence is a situation in which your application has free reign over most of the database, but needs to use a few stored procedure calls to get at certain pieces of data. In that case, you'll want to create a normal DBIC schema and then add methods for accessing the unusual data. As an example, let's look back to the AddressBook application and imagine that for some reason we couldn't use DBIx::Class to access the user table, and instead need to write the raw SQL to return an array containing everyone's username. In AddressBook::Model::AddressDB, we just need to write a subroutine to do our work as follows:     package AddressBook::Model::AddressDB;    // other code in the package    sub get_users {        my $self = shift;        my $storage = $self->storage;        return $storage->dbh_do(            sub {                my $self = shift;                my $dbh = shift;                my $sth = $dbh->prepare('SELECT username FROM user');                $sth->execute();                my @rows = @{$sth->fetchall_arrayref()};                return map { $_->[0] } @rows;                });    } Here's how the code works. On the first line, we get our DBIC::Schema object and then obtain the schema's storage object. The storage object is what DBIC uses to execute its generated SQL on the database, and is usually an instance of DBIx:: Class::Storage::DBI. This class contains a method called dbh_do which will execute a piece of code, passed to dbh_do as a coderef (or "anonymous subroutine"), and provide the code with a standard DBI database handle (usually called $dbh). dbh_do will make sure that the database handle is valid before it calls your code, so you don't need to worry about things like the database connection timing out. DBIC will reconnect if necessary and then call your code. dbh_do will also handle exceptions raised within your code in a standard way, so that errors can be caught normally. The rest of the code deals with actually executing our query. When the database handle is ready, it's passed as the second argument to our coderef (the first is the storage object itself, in case you happen to need that). Once we have the database handle, the rest of the code is exactly the same as if we were using plain DBI instead of DBIx::Class. We first prepare our query (which need not be a SELECT; it could be EXEC or anything else), execute it and, finally, process the result. The map statement converts the returned data to the form we expect it in, a list of names (instead of a list of rows each containing a single name). Note that the return statement in the coderef returns to dbh_do, not to the caller of get_users. This means that you can execute dbh_do as many times as required and then further process the results before returning from the get_users subroutine. Once you've written this subroutine, you can easily call it from elsewhere in your application:     my @users = $c->model('AddressDB')->get_users;    $c->response->body('All Users' join ', ', @users); Custom Methods Without Raw SQL As the above example doesn't use any features of the database that DBIC doesn't explicitly expose in its resultset interface, let us see how we can implement the get_users function without using dbh_do. Although the preconditions of the example indicated that we couldn't use DBIC, it's good to compare the two approaches so you can decide which way to do things in your application. Here's another way to implement the above example:     sub get_users { # version 2        my $self = shift;        my $users = $self->resultset('User');        my @result;        while(my $user = $users->next){                push @result, $user->username;        }        return @result;    } This looks like the usual DBIC manipulation that we're used to. (Usually we call $c->model('AddressDB::User') to get the "User" resultset, but under the hood this is the same as $c->model('AddressDB')->resultset('User'). In this example, $self is the same as $c->model('AddressDB').) The above code is cleaner and more portable (across database systems) than the dbh_do method, so it's best to prefer resultsets over dbh_do unless there's absolutely no other way to achieve the functionality you desire. Calling Database Functions Another common problem is the need to call database functions on tables that you're accessing with DBIC. Fortunately, DBIC provides syntax for this case, so we won't need to write any SQL manually and run it with dbh_do. All that's required is a second argument to search. For example, if we want to get the count of all users in the user table, we could write (in a controller) the following:     $users = $c->model('AddressDB::User');    $users->search({}, { select => [ { COUNT => 'id' } ],                                                    as => [ 'count' ],});    $count = $users->first->get_column('count'); This is the same as executing SELECT COUNT(id) FROM user, fetching the first row and then setting $count to the first column of that row. Note that we didn't specify a WHERE clause, but if we wanted to, we could replace the first {} with the WHERE expression, and then get the count of matching rows. Here's a function that we can place in the User ResultSetClass to get easy access to the user count:     sub count_users_where {        my $self = shift;        my $condition = shift;        $self->search($condition,                { select => [ { COUNT => 'id' } ],                        as => [ 'count' ], });        my $first = $users->first;        return $first->get_column('count') if $first;        return 0; # if there is no "first" row, return 0    } Now, we can write something like the following:     $jons = $c->model('AddressDB::User')->        count_users_where([ username => {-like => '%jon%'}]); to get the number of jons in the database, without having to fetch every record and count them. If you only need to work with a single column, you can also use the DBIx::Class:: ResultSetColumn interface. Creating a Database Model from Scratch In some cases, you'll have no use for any of DBIC's functionality. DBIC might not work with your database, or perhaps you're migrating a legacy application that has well-tested database queries that you don't want to rewrite. In this sort of situation, you can write the entire database model manually. In the next example, we'll use Catalyst::Model::DBI to set up the basic DBI layer and the write methods (like we did above) to access the data in the model. As we have the AddressBook application working, we'll add a DBI model and write some queries against the AddressBook database. First, we need to create the model. We'll call it AddressDBI: $ perl script/addressbook_create.pl model AddressDBI DBI DBI:SQLite: database When you open the generated AddressBook::Model::AddressDBI file, you should see something like this:     package AddressBook::Model::AddressDBI;    use strict;    use base 'Catalyst::Model::DBI';    __PACKAGE__->config(            dsn => 'DBI:SQLite:database',            user => '',            password => '',            options => {},    );    1; # magic true value required Once you have this file, you can just start adding methods. The database handle will be available via $self->dbh, and the rest is up to you. Let's add a count_users function:     sub count_users {        my $self = shift;        my $dbh = $self->dbh;        my $rows = $dbh->            selectall_arrayref('SELECT COUNT(id) FROM user');        return $rows->[0]->[0]; # first row, then the first column    } Let's also add a test Controller so that we can see if this method works. First, create the Test controller by running the following command line: $ perl script/addressbook_create.pl controller Test And then add a quick test action as follows:     sub count_users : Local {        my ($self, $c) = @_;        my $count = $c->model('AddressDBI')->count_users();        $c->response->body("There are $count users."); } You can quickly see the output of this action by running the following command line:   $ perl script/addressbook_test.pl /test/count_users  There are 2 users. The myapp_test.pl script will work for any action, but it works best for test actions like this because the output is plain-text and will fit on the screen. When you're testing actual actions in your application, it's usually easier to read the page when you view it in the browser. That's all there is to it—just add methods to AddressDBI until you have everything you need. The only other thing you might want to do is to add the database configuration to your config file. It works almost the same way for DBI as it does for DBIC::Schema:     ---    name: AddressBook    Model::AddressDBI:        dsn: "DBI:SQLite:database"        username: ~        password: ~            options:                option1: something                # and so on    # the rest of your config file goes here Implementing a Filesystem Model In this final example, we'll build an entire model from scratch without even the help of a model base class like Catalyst::Model::DBI. Before you do this for your own application, you should check the CPAN to see if anyone's done anything similar already. There are currently about fifty ready-to-use model base classes that abstract data sources like LDAP servers, RSS readers, shopping carts, search engines, Subversion, email folders, web services and even YouTube. Expanding upon one of these classes will usually be easier than writing everything yourself. For this example, we'll create a very simple blog application. To post the blog, you just write some text and put it in a file whose name is the title you want on the post. We'll write a filesystem model from scratch to provide the application with the blog posts. Let's start by creating the app's skeleton:   $ catalyst.pl Blog After that, we'll create our Filesystem model:   $ cd Blog  $ perl script/blog_create.pl model Filesystem We'll also use plain TT for the View:   $ perl script/blog_create.pl view TT TT
Read more
  • 0
  • 0
  • 2456
article-image-interacting-databases-through-java-persistence-api
Packt
23 Oct 2009
17 min read
Save for later

Interacting with Databases through the Java Persistence API

Packt
23 Oct 2009
17 min read
We will look into: Creating our first JPA entity Interacting with JPA entities with entity manager Generating forms in JSF pages from JPA entities Generating JPA entities from an existing database schema JPA named queries and JPQL Entity relationships Generating complete JSF applications from JPA entities Creating Our First JPA Entity JPA entities are Java classes whose fields are persisted to a database by the JPA API. JPA entities are Plain Old Java Objects (POJOs), as such, they don't need to extend any specific parent class or implement any specific interface. A Java class is designated as a JPA entity by decorating it with the @Entity annotation. In order to create and test our first JPA entity, we will be creating a new web application using the JavaServer Faces framework. In this example we will name our application jpaweb. As with all of our examples, we will be using the bundled GlassFish application server. To create a new JPA Entity, we need to right-click on the project and select New | Entity Class. After doing so, NetBeans presents the New Entity Class wizard. At this point, we should specify the values for the Class Name and Package fields (Customer and com.ensode.jpaweb in our example), then click on the Create Persistence Unit... button. The Persistence Unit Name field is used to identify the persistence unit that will be generated by the wizard, it will be defined in a JPA configuration file named persistence.xml that NetBeans will automatically generate from the Create Persistence Unit wizard. The Create Persistence Unit wizard will suggest a name for our persistence unit, in most cases the default can be safely accepted. JPA is a specification for which several implementations exist. NetBeans supports several JPA implementations including Toplink, Hibernate, KODO, and OpenJPA. Since the bundled GlassFish application server includes Toplink as its default JPA implementation, it makes sense to take this default value for the Persistence Provider field when deploying our application to GlassFish. Before we can interact with a database from any Java EE 5 application, a database connection pool and data source need to be created in the application server. A database connection pool contains connection information that allow us to connect to our database, such as the server name, port, and credentials. The advantage of using a connection pool instead of directly opening a JDBC connection to a database is that database connections in a connection pool are never closed, they are simply allocated to applications as they need them. This results in performance improvements, since the operations of opening and closing database connections are expensive in terms of performance. Data sources allow us to obtain a connection from a connection pool by obtaining an instance of javax.sql.DataSource via JNDI, then invoking its getConnection() method to obtain a database connection from a connection pool. When dealing with JPA, we don't need to directly obtain a reference to a data source, it is all done automatically by the JPA API, but we still need to indicate the data source to use in the application's Persistence Unit. NetBeans comes with a few data sources and connection pools pre-configured. We could use one of these pre-configured resources for our application, however, NetBeans also allows creating these resources "on the fly", which is what we will be doing in our example. To create a new data source we need to select the New Data Source... item from the Data Source combo box. A data source needs to interact with a database connection pool. NetBeans comes pre-configured with a few connection pools out of the box, but just like with data sources, it allows us to create a new connection pool "on demand". In order to do this, we need to select the New Database Connection... item from the Database Connection combo box. NetBeans includes JDBC drivers for a few Relational Database Management Systems (RDBMS) such as JavaDB, MySQL, and PostgreSQL "out of the box". JavaDB is bundled with both GlassFish and NetBeans, therefore we picked JavaDB for our example. This way we avoid having to install an external RDBMS. For RDBMS systems that are not supported out of the box, we need to obtain a JDBC driver and let NetBeans know of it's location by selecting New Driver from the Name combo box. We then need to navigate to the location of a JAR file containing the JDBC driver. Consult your RDBMS documentation for details. JavaDB is installed in our workstation, therefore the server name to use is localhost. By default, JavaDB listens to port 1527, therefore that is the port we specify in the URL. We wish to connect to a database called jpaintro, therefore we specify it as the database name. Since the jpaintro database does not exist yet, we pass the attribute create=true to JavaDB, this attribute is used to create the database if it doesn't exist yet. Every JavaDB database contains a schema named APP, since each user by default uses a schema named after his/her own login name. The easiest way to get going is to create a user named "APP" and select a password for this user. Clicking on the Show JDBC URL checkbox reveals the JDBC URL for the connection we are setting up. The New Database Connection wizard warns us of potential security risks when choosing to let NetBeans remember the password for the database connection. Database passwords are scrambled (but not encrypted) and stored in an XML file under the .netbeans/[netbeans version]/config/Databases/Connections directory. If we follow common security practices such as locking our workstation when we walk away from it, the risks of having NetBeans remember database passwords will be minimal. Once we have created our new data source and connection pool, we can continue configuring our persistence unit. It is a good idea to leave the Use Java Transaction APIs checkbox checked. This will instruct our JPA implementation to use the Java Transaction API (JTA) to allow the application server to manage transactions. If we uncheck this box, we will need to manually write code to manage transactions. Most JPA implementations allow us to define a table generation strategy. We can instruct our JPA implementation to create tables for our entities when we deploy our application, to drop the tables then regenerate them when our application is deployed, or not create any tables at all. NetBeans allows us to specify the table generation strategy for our application by clicking the appropriate value in the Table Generation Strategy radio button group. When working with a new application, it is a good idea to select the Drop and Create table generation strategy. This will allow us to add, remove, and rename fields in our JPA entity at will without having to make the same changes in the database schema. When selecting this table generation strategy, tables in the database schema will be dropped and recreated, therefore any data previously persisted will be lost. Once we have created our new data source, database connection and persistence unit, we are ready to create our new JPA entity. We can do so by simply clicking on the Finish button. At this point NetBeans generates the source for our JPA entity. JPA allows the primary field of a JPA entity to map to any column type (VARCHAR, NUMBER). It is best practice to have a numeric surrogate primary key, that is, a primary key that serves only as an identifier and has no business meaning in the application. Selecting the default Primary Key type of long will allow for a wide range of values to be available for the primary keys of our entities. package com.ensode.jpaweb;import java.io.Serializable;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic class Customer implements Serializable { private static final long serialVersionUID = 1L; private Long id; public void setId(Long id) { this.id = id; } @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } //Other generated methods (hashCode(), equals() and //toString() omitted for brevity.} As we can see, a JPA entity is a standard Java object. There is no need to extend any special class or implement any special interface. What differentiates a JPA entity from other Java objects are a few JPA-specific annotations. The @Entity annotation is used to indicate that our class is a JPA entity. Any object we want to persist to a database via JPA must be annotated with this annotation. The @Id annotation is used to indicate what field in our JPA entity is its primary key. The primary key is a unique identifier for our entity. No two entities may have the same value for their primary key field. This annotation can be placed just above the getter method for the primary key class. This is the strategy that the NetBeans wizard follows. It is also correct to specify the annotation right above the field declaration. The @Entity and the @Id annotations are the bare minimum two annotations that a class needs in order to be considered a JPA entity. JPA allows primary keys to be automatically generated. In order to take advantage of this functionality, the @GeneratedValue annotation can be used. As we can see, the NetBeans generated JPA entity uses this annotation. This annotation is used to indicate the strategy to use to generate primary keys. All possible primary key generation strategies are listed in the following table:   Primary Key Generation Strategy   Description   GenerationType.AUTO   Indicates that the persistence provider will automatically select a primary key generation strategy. Used by default if no primary key generation strategy is specified.   GenerationType.IDENTITY   Indicates that an identity column in the database table the JPA entity maps to must be used to generate the primary key value.   GenerationType.SEQUENCE   Indicates that a database sequence should be used to generate the entity's primary key value.   GenerationType.TABLE   Indicates that a database table should be used to generate the entity's primary key value.       In most cases, the GenerationType.AUTO strategy works properly, therefore it is almost always used. For this reason the New Entity Class wizard uses this strategy. When using the sequence or table generation strategies, we might have to indicate the sequence or table used to generate the primary keys. These can be specified by using the @SequenceGenerator and @TableGenerator annotations, respectively. Consult the Java EE 5 JavaDoc at http://java.sun.com/javaee/5/docs/api/ for details. For further knowledge on primary key generation strategies you can refer EJB 3 Developer Guide by Michael Sikora, which is another book by Packt Publishing (http://www.packtpub.com/developer-guide-for-ejb3/book). Adding Persistent Fields to Our Entity At this point, our JPA entity contains a single field, its primary key. Admittedly not very useful, we need to add a few fields to be persisted to the database. package com.ensode.jpaweb;import java.io.Serializable;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic class Customer implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String firstName; private String lastName; public void setId(Long id) { this.id = id; } @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } //Additional methods omitted for brevity} In this modified version of our JPA entity, we added two fields to be persisted to the database; firstName will be used to store the user's first name, lastName will be used to store the user's last name. JPA entities need to follow standard JavaBean coding conventions. This means that they must have a public constructor that takes no arguments (one is automatically generated by the Java compiler if we don't specify any other constuctors), and all fields must be private, and accessed through getter and setter methods. Automatically Generating Getters and Setters In NetBeans, getter and setter methods can be generated automatically. Simply declare new fields as usual then use the "insert code" keyboard shortcut (default is Alt+Insert), then select Getter and Setter from the resulting pop-up window, then click on the check box next to the class name to select all fields, then click on the Generate button. Before we can use JPA persist our entity's fields into our database, we need to write some additional code. Creating a Data Access Object (DAO) It is a good idea to follow the DAO design pattern whenever we write code that interacts with a database. The DAO design pattern keeps all database access functionality in DAO classes. This has the benefit of creating a clear separation of concerns, leaving other layers in our application, such as the user interface logic and the business logic, free of any persistence logic. There is no special procedure in NetBeans to create a DAO. We simply follow the standard procedure to create a new class by selecting File | New, then selecting Java as the category and the Java Class as the file type, then entering a name and a package for the class. In our example, we will name our class CustomerDAO and place it in the com.ensode.jpaweb package. At this point, NetBeans create a very simple class containing only the package and class declarations. To take complete advantage of Java EE features such as dependency injection, we need to make our DAO a JSF managed bean. This can be accomplished by simply opening faces-config.xml, clicking its XML tab, then right-clicking on it and selecting JavaServer Faces | Add Managed Bean. We get the Add Manged Bean dialog as seen here: We need to enter a name, fully qualified name, and scope for our managed bean (which, in our case, is our DAO), then click on the Add button. This action results in our DAO being declared as a managed bean in our application's faces-config.xml configuration file. <managed-bean> <managed-bean-name>CustomerDAO</managed-bean-name> <managed-bean-class> com.ensode.jpaweb.CustomerDAO </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> We could at this point start writing our JPA code manually, but with NetBeans there is no need to do so, we can simply right-click on our code and select Persistence | Use Entity Manager, and most of the work is automatically done for us. Here is how our code looks like after doing this trivial procedure: package com.ensode.jpaweb;import javax.annotation.Resource;import javax.naming.Context;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;@PersistenceContext(name = "persistence/LogicalName", unitName = "jpawebPU")public class CustomerDAO { @Resource private javax.transaction.UserTransaction utx; protected void persist(Object object) { try { Context ctx = (Context) new javax.naming.InitialContext(). lookup("java:comp/env"); utx.begin(); EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName"); em.persist(object); utx.commit(); } catch (Exception e) { java.util.logging.Logger.getLogger( getClass().getName()).log( java.util.logging.Level.SEVERE, "exception caught", e); throw new RuntimeException(e); } }} All highlighted code is automatically generated by NetBeans. The main thing NetBeans does here is add a method that will automatically insert a new row in the database, effectively persisting our entity's properties. As we can see, NetBeans automatically generates all necessary import statements. Additionally, our new class is automatically decorated with the @PersistenceContext annotation. This annotation allows us to declare that our class depends on an EntityManager (we'll discuss EntityManager in more detail shortly). The value of its name attribute is a logical name we can use when doing a JNDI lookup for our EntityManager. NetBeans by default uses persistence/LogicalName as the value for this property. The Java Naming and Directory Interface (JNDI) is an API we can use to obtain resources, such as database connections and JMS queues, from a directory service. The value of the unitName attribute of the @PersistenceContext annotation refers to the name we gave our application's Persistence Unit. NetBeans also creates a new instance variable of type javax.transaction.UserTransaction. This variable is needed since all JPA code must be executed in a transaction. UserTransaction is part of the Java Transaction API (JTA). This API allows us to write code that is transactional in nature. Notice that the UserTransaction instance variable is decorated with the @Resource annotation. This annotation is used for dependency injection. in this case an instance of a class of type javax.transaction.UserTransaction will be instantiated automatically at run-time, without having to do a JNDI lookup or explicitly instantiating the class. Dependency injection is a new feature of Java EE 5 not present in previous versions of J2EE, but that was available and made popular in the Spring framework. With standard J2EE code, it was necessary to write boilerplate JNDI lookup code very frequently in order to obtain resources. To alleviate this situation, Java EE 5 made dependency injection part of the standard. The next thing we see is that NetBeans added a persist method that will persist a JPA entity, automatically inserting a new row containing our entity's fields into the database. As we can see, this method takes an instance of java.lang.Object as its single parameter. The reason for this is that the method can be used to persist any JPA entity (although in our example, we will use it to persist only instances of our Customer entity). The first thing the generated method does is obtain an instance of javax.naming.InitialContext by doing a JNDI lookup on java:comp/env. This JNDI name is the root context for all Java EE 5 components. The next thing the method does is initiate a transaction by invoking uxt.begin(). Notice that since the value of the utx instance variable was injected via dependency injection (by simply decorating its declaration with the @Resource annotation), there is no need to initialize this variable. Next, the method does a JNDI lookup to obtain an instance of javax.persistence.EntityManager. This class contains a number of methods to interact with the database. Notice that the JNDI name used to obtain an EntityManager matches the value of the name attribute of the @PersistenceContext annotation. Once an instance of EntityManager is obtained from the JNDI lookup, we persist our entity's properties by simply invoking the persist() method on it, passing the entity as a parameter to this method. At this point, the data in our JPA entity is inserted into the database. In order for our database insert to take effect, we must commit our transaction, which is done by invoking utx.commit(). It is always a good idea to look for exceptions when dealing with JPA code. The generated method does this, and if an exception is caught, it is logged and a RuntimeException is thrown. Throwing a RuntimeException has the effect of rolling back our transaction automatically, while letting the invoking code know that something went wrong in our method. The UserTransaction class has a rollback() method that we can use to roll back our transaction without having to throw a RunTimeException. At this point we have all the code we need to persist our entity's properties in the database. Now we need to write some additional code for the user interface part of our application. NetBeans can generate a rudimentary JSF page that will help us with this task.
Read more
  • 0
  • 0
  • 6087

article-image-python-ldap-applications-part-4-ldap-schema
Packt
23 Oct 2009
8 min read
Save for later

Python LDAP Applications: Part 4 - LDAP Schema

Packt
23 Oct 2009
8 min read
Using Schema Information As with most LDAP servers, OpenLDAP provides schema access to LDAP clients. An LDAP schema defines object classes, attributes, matching rules, and other LDAP structures. In this article, we will take a brief look at what might be the most complex module in the Python-LDAP API, the ldap.schema module. This module provides programmatic access to the schema, using the LDAP subschema record, and the subschema's subentries obtained from the LDAP server. The module has two major components. The first is the SubSchema object, which contains the schema definition, and provides numerous functions for navigating through the definitions stored in the schema. The second component is the model, which contains classes that describe structural components (Schema Elements) of the schema. For example, the model contains classes like ObjectClass, AttributeType, MatchingRule, and DITContentRule. Getting the Schema from the LDAP Server The ldap.schema module does not automatically retrieve the schema information. It must be fetched from the server with an LDAP search operation. The schema is always stored in a specific entry, almost always accessible with the DN cn=subschema. (If it is elsewhere, and is accessible, the Root DSE will note the location.) We can retrieve the record by doing a search with a base scope: >>> res = l.search_s('cn=subschema',... ldap.SCOPE_BASE,... '(objectclass=*)',... ['*','+']... )>>> subschema_entry = ldaphelper.get_search_results(res)[0]>>> subschema_subentry = subschema_entry.get_attributes()>>> The search configuration above should return only one record – the record for cn=subschema. Because most of the schema attributes are operational attributes, we need to specify, in the list of attributes, both * for all regular attributes and + for all operational attributes. The ldaphelper.get_search_results() function we created early in this series returns a list of LDAPSearchResult objects. Since we know that we want the first one (in a list of one), we can use the [0] notation at the end to return just the first item in the resulting list. Now, schema_entry contains the LDAPSearchResult object for the cn=subschema record. We need the list of attributes – namely, the schema-defining attributes, usually called the subschema subentry. We can use the get_attributes() method to retrieve the dict of attributes. Now we have the information necessary for creating a new SubSchema object. The SubSchema Object The SubSchema object provides access to the details of the schema definitions. The SubSchema() constructor takes one parameter: a dictionary of attributes that contains the subschema subentry information. This is the information we retrieved and stored in the subschema_subentry variable above. Creating a new SubSchema object is done like this: >>> subschema = ldap.schema.SubSchema( subschema_subentry )>>> Now we can access the schema information. We can, for instance, get the schema information for the cn attribute: >>> cn_attr = subschema.get_obj( ldap.schema.AttributeType, 'cn' )>>> cn_attr.names('cn', 'commonName')>>> cn_attr.desc'RFC2256: common name(s) for which the entity is known by'>>> cn_attr.oid'2.5.4.3'>>> The first line employs the get_obj() method to retrieve an AttributeType object. The call to get_obj() above uses two parameters. The first is the class (a subclass of SchemaElement) that represents an attribute. This is ldap.schema.AttributeType. If we were getting an object class instead of an attribute, we would use the same method, but pass an ldap.schema.ObjectClass as the first parameter. The second parameter is a string name (or OID) of the attribute. We could have used 'commonName' or '2.5.4.3' and attained the same result. The cn_attr object (an instance of an AttributeType class) has a number of properties representing schema statements. For example, in the example above, the names property contains a tuple of the attribute names for that attribute, and the desc property contains the value of the description, as specified in the schema. The oid attribute contains the Object Identifier (OID) for the CN attribute. Let's look at one more method of the SubSchema class before moving on to the final script in this article. Using the attribute_types() method of the SubSchema class, we can find out what attributes are required for an record, and what attributes are allowed. For example, consider a record that has the object classes account and simpleSecurityObject. The uid=authenticate,ou=system,dc=example,dc=com entry in our directory information tree is an example of such a user. We can use the attribute_types() method to get information about what attributes this record can or must have: >>> oc_list = ['account', 'simpleSecurityObject']>>> oc_attrs = subschema.attribute_types( oc_list )>>> must_attrs = oc_attrs[0]>>> may_attrs = oc_attrs[1]>>> >>> for ( oid, attr_obj ) in must_attrs.iteritems():... print "Must have %s" % attr_obj.names[0]... Must have userPasswordMust have objectClassMust have uid>>> for ( oid, attr_obj ) in may_attrs.iteritems():... print "May have %s" % attr_obj.names[0]... May have oMay have ouMay have seeAlsoMay have descriptionMay have lMay have host>>> The oc_list list has the names of the two object classes in which we are interested: account and simpleSecurityObject. Passing this list to the attribute_types() method, we get a two-item tuple. The first item in the tuple is a dictionary of required attributes. The key in the dictionary is the OID: >>> must_attrs.keys()['2.5.4.35', '2.5.4.0', '0.9.2342.19200300.100.1.1']>>> The value in the dictionary is an AttributeType object corresponding to the attribute defined for the OID key: >>> must_attrs['2.5.4.35'].oid'2.5.4.35'>>> In the code snippet above, we assigned each value in the two-item tuple to a different variable: must_attrs contains the first item in the tuple – the dictionary of must-have attributes. The may_attrs contains a dictionary of the attributes that are allowed, but not required. Iterating through the dictionaries and printing the output, we can see that the required attributes for a record that used both the account and the simpleSecurityObject object classes would be userPassword, objectclass, and uid. Several other attributes are allowed, but not required: o, ou, seeAlso, description, l, and host. We could find out which object class definitions required or allowed which of these attributes using the get_obj() method we looked at above: >>> oc_obj = subschema.get_obj( ldap.schema.ObjectClass, 'account' )>>> oc_obj.may('description', 'seeAlso', 'localityName', 'organizationName', 'organizationalUnitName', 'host')>>> oc_obj.must('userid',)>>>>>> oc_obj = subschema.get_obj( ldap.schema.ObjectClass,... 'simpleSecurityObject' )>>> oc_obj.must('userPassword',)>>> oc_obj.may()>>> From the above, we can see that most of the required and optional attributes come from the account definition, while only userPassword comes from the simpleSecurityObject definition. The requirement of the objectClass attribute comes from the top object class, the ultimate ancestor of all structural object classes. The schema support offered by the Python-LDAP API makes it possible to program schema-aware clients that can, for instance, perform client-side schema checking, dynamically build forms for creating records, or compare definitions between different LDAP servers on a network. Unfortunately, the ldap.schema module is poorly documented. With most of the module, the best source of information is the __doc__ strings embedded in the code: >>> print ldap.schema.SubSchema.attribute_types.__doc__ Returns a 2-tuple of all must and may attributes including all inherited attributes of superior object classes by walking up classes along the SUP attribute. The attributes are stored in a ldap.cidict.cidict dictionary. object_class_list list of strings specifying object class names or OIDs attr_type_filter list of 2-tuples containing lists of class attributes which has to be matched raise_keyerror All KeyError exceptions for non-existent schema elements are ignored ignore_dit_content_rule A DIT content rule governing the structural object class is ignored >>> In some cases, though, the best source of documentation is the code itself. The last script in this article will provide an example of how the schema information can be used. An Example Script: suggest_attributes.py This example script compares the attributes in a user-specified record with the possible attributes, and prints out an annotated list of “suggested” available attributes. This script is longer than the other scripts in this article, but it makes use of similar techniques, and we will be able to move through it quickly.
Read more
  • 0
  • 0
  • 13109

article-image-adonet-entity-framework
Packt
23 Oct 2009
6 min read
Save for later

ADO.NET Entity Framework

Packt
23 Oct 2009
6 min read
Creating an Entity Data Model You can create the ADO.NET Entity Data Model in one of the two ways: Use the ADO.NET Entity Data Model Designer Use the command line Entity Data Model Designer called EdmGen.exe We will first take a look at how we can design an Entity Data Model using the ADO.NET Entity Data Model Designer which is a Visual Studio wizard that is enabled after you install ADO.NET Entity Framework and its tools. It provides a graphical interface that you can use to generate an Entity Data Model. Creating the Payroll Entity Data Model using the ADO.NET Entity Data Model Designer Here are the tables of the 'Payroll' database that we will use to generate the data model: Employee Designation Department Salary ProvidentFund To create an entity data model using the ADO.NET Entity Data Model Designer, follow these simple steps: Open Visual Studio.NET and create a solution for a new web application project as seen below and save with a name. Switch to the Solution Explorer, right click and click on Add New Item as seen in the following screenshot: Next, select ADO.NET Entity Data Model from the list of the templates displayed as shown in the following screenshot:   Name the Entity Data Model PayrollModel and click on Add. Select Generate from database from the Entity Data Model Wizard as shown in the following screenshot: Note that you can also use the Empty model template to create the Entity Data Model yourself. If you select the Empty Data Model template and click on next, the following screen appears: As you can see from the above figure, you can use this template to create the Entity Data Model yourself. You can create the Entity Types and their relationships manually by dragging items from the toolbox. We will not use this template in our discussion here. So, let's get to the next step. Click on Next in the Entity Data Model Wizard window shown earlier. The modal dialog box will now appear and prompts you to choose your connection as shown in the following figure: Click on New Connection Now you will need to specify the connection properties and parameters as shown in the following figure: We will use a dot to specify the database server name. This implies that we will be using the database server of the localhost, which is the current system in use. After you specify the necessary user name, password, and the server name, you can test your connection using the Test Connection button. When you do so, the message Test connection succeeded gets displayed in the message box as shown in the previous figure. When you click on OK on the Test connection dialog box, the following screen appears: <connectionStrings> <add name="PayrollEntities" connectionString="metadata=res:// *; provider=System.Data.SqlClient;provider connection string=&quot; Data Source=.;Initial Catalog=Payroll;User ID=sa;Password=joydip1@3; MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> Note the Entity Connection String generated automatically. This connection string will be saved in the ConnectionStrings section of your application's web.config file. This is how it will look like: When you click on Next in the previous figure, the following screen appears: Expand the Tables node and specify the database objects that you require in the Entity Data Model to be generated as shown in the following figure: Click on Finish to generate the Entity Data Model. Here is the output displayed in the Output Window while the Entity Data Model is being generated: Your Entity Data Model has been generated and saved in a file named PayrollModel.edmx. We are done creating our first Entity Data Model using the ADO.NET Entity Data Model Designer tool. When you open the Payroll Entity Data Model that we just created in the designer view, it will appear as shown in the following figure: Note how the Entity Types in the above model are related to one another. These relationships have been generated automatically by the Entity Data Model Designer based on the relationships between the tables of the Payroll database. In the next section, we will learn how we can create an Entity Data Model using the EdmGen.exe command line tool. Creating the Payroll Data Model Using the EdmGen Tool We will now take a look at how to create a data model using the Entity Data Model generation tool called EdmGen. The EdmGen.exe command line tool can be used to do one or more of the following: Generate the .cdsl, .msl, and .ssdl files as part of the Entity Data Model Generate object classes from a .csdl file Validate an Entity Data Model The EdmGen.exe command line tool generates the Entity Data Model as a set of three files: .csdl, .msl, and .ssdl. If you have used the ADO.NET Entity Data Model Designer to generate your Entity Data Model, the .edmx file generated will contain the CSDL, MSL, and the SSDL sections. You will have a single .edmx file that bundles all of these sections into it. On the other hand, if you use the EdmGen.exe tool to generate the Entity Data Model, you would find three distinctly separate files with .csdl, .msl or .ssdl extensions. Here is a list of the major options of the EdmGen.exe command line tool: Option Description /help Use this option to display help on all the possible options of this tool. The short form is /? /language:CSharp Use this option to generate code using C# language /language:VB Use this option to generate code using VB language /provider:<string> Use this option to specify the name of the ADO.NET data provider that you would like to use. /connectionstring: <connection string> Use this option to specify the connection string to be used to connect to the database /namespace:<string> Use this option to specify the name of the namespace /mode:FullGeneration Use this option to generate your CSDL, MSL, and SSDL objects from the database schema /mode:EntityClassGeneration Use this option to generate your entity classes from a given CSDL file /mode:FromSsdlGeneration Use this option to generate MSL, CSDL, and Entity Classes from a given SSDL file /mode:ValidateArtifacts Use this option to validate the CSDL, SSDL, and MSL files /mode:ViewGeneration Use this option to generate mapping views from the CSDL, SSDL, and MSL files  
Read more
  • 0
  • 0
  • 3771
article-image-using-data-pager-control-visual-studio-2008
Packt
23 Oct 2009
5 min read
Save for later

Using the Data Pager Control in Visual Studio 2008

Packt
23 Oct 2009
5 min read
A direct connection to SQL Server 2008 is not possible with this version of SQL Server and Visual Studio 2008. One way to get around this is to use an ODBC connection to the SQL Server and then using the ODBC connection to retrieve the data. Another way described is to use the OLEDB connectivity option shown in this article. Article Overview We first create an ASP.NET Web Application project. To the default.aspx page we add a ListView control. Then we configure the ListView Control by configuring its data source and its displayed features. At this point a DataPager can be included as part of the ListView, but adding a DataPager manually is also shown. Controlling the number of displayed items in a page can be carried out using page load event code or declaratively. Creating an ASP.NET Web Application From the File menu item create a new project that opens up the window shown in the next figure. Make sure you are creating a .NET Framework 3.5 ASP.NET Web application project (use drop-down at top right of this window). The default name of the application has been changed to DataPager as shown. Click on the OK button to create the project. The project is created with all the necessary files and the template for the Default.aspx page as shown. The Solution Explorer and the Class View of the project has all the information on this project. The Split tab at the bottom of the 'Default.aspx' shows both the Design page as well as the HTML code for the page. Adding a ListView Control and connecting to a Data Source Drag and drop a ListView Control from the Toolbox on to the design page between the <div/> tags as shown. The Code is automatically generated as shown in the next figure. The ListView instance has a Id property "ListView1". Now you can configure the ListView using the Smart Tasks handle - the small arrow head [>] attached to the list view at the top right. Click the Smart Task handle to open the list of tasks to be performed as shown. The only task you find here is the "Choosing the data source". Configuring the Data Source Now click on <New data source...>. This opens the Data Source Configuration Wizard. Click on Database icon which sets the stage for bringing data from SQL Server with an Id property "SQLDataSource1". This supports connecting to any ADO.NET datasource. Click on the OK button in the above window. This opens the window where you need to choose the "Connection String", a very important item for connecting to a source of data.     Click on the <New Connection...> button. This opens the Add Connection window with the default options displayed. Click on the Change... button since we are interested in connecting to SQL Server 2008. Click on the <other> drop-down menu item and choose the .NET Framework Data Provider for OLEDB as shown. Click on the OK button. This brings you back to the Add Connection window and you need to indicate the DataLinks. Click on the OLEDB Providers drop-down and choose Microsoft OLEDB Provider for SQL server as shown. Click on the Data Links... button. This brings up the Data Link Properties window as shown. Choose the Windows authentication. If you click on the drop-down handle for Selecting the databases on the server a list of databases will be displayed. Choose the pubsx database. Click on the OK on the Data Link properties page which will take you back to the Add Connection window updating all the information. You may test and verify the connection on this page as well. Click on the OK button on the Add Connection window. This will take you back to the Configure Data Source window seen earlier after updating the connection string as shown. Click on the Next button. The window that shows up is about saving the connection information to the web.config file. Make sure you read the notes on this window. Click on the Next button. In the window that gets displayed you can choose either a table from the database, or provide a SQL statement, or the name of a stored procedure. Here to keep it simple, the authors table is chosen from the drop-down list. You can make use of other buttons on this window to refine your select statement. Here just the table name is chosen. From the columns that are displayed a few columns are chosen. Click on the Next button. This displays the window where you can test your query. It comes up blank, but when you hit the button Test Query, the blank area gets populated by the result returned by the query as shown. Now click on the Finish button. This closes this window and the details of the just finished data source gets into the designer interface as shown.  
Read more
  • 0
  • 0
  • 2590

article-image-front-page-customization-moodle
Packt
23 Oct 2009
11 min read
Save for later

Front Page Customization in Moodle

Packt
23 Oct 2009
11 min read
Look and Feel: An Overview Moodle can be fully customized in terms of layout and branding. It has to be stressed that certain aspects of changing the look and feel require some design skills. While you as an administrator will be able to make most of the relevant adjustments, it might be necessary to get a professional designer involved, especially when it comes to styling. The two relevant components for customization are the Moodle front page and Moodle themes, though this article will focus only on Moodle front page. Before going into further details, let's try to understand which part is responsible for which element of the look and feel of your site. Have a look at the screenshot that would follow. It shows the front page of Moodle site after you are logged in as an administrator. It is not obvious which parts are driven by the Moodle theme and by the front page settings. The next table sheds some light on this: Element Settings Theme Other Logos - x - Logged-in information (location and font) - x - Language Drop Down - - x Site Administration block (position) x - - Available Courses block (position) x - - Available Courses block (content) - - x Course categories and Calendar block (position) x - - Course categories and Calendar block (icons, fonts, colors) - x - Footer text - x - Footer logo - x - Copyright statement - x -   While this list is by no means complete, it hopefully gives you an idea that the look and feel of your Moodle site is driven by a number of different elemen In short, the settings (mostly front page settings as well as a few related parameters) dictate what content users will see before and after they log on. The theme is responsible for the design scheme or branding, that is, the header and footer as well as colors, fonts, icons, and so on used throughout the site. Now let's move towards the core part of this article. Customizing Your Front Page The appearance of Moodle's front page changes after a user has logged in. The content and layout of the page before and after login can be customized to represent the identity of your organization. Look at the following screenshot. It is the same site that the preceding screenshot was taken from, but before a user has logged in. In this particular example, a Login block is shown on the left and the Course categories are displayed in the center, as opposed to the list of available courses. Front Page Settings To customize the front page, you either have to be logged in as Moodle administrator, or have front-page-related permissions in the Front Page context. From the Site Administration block, select Front Page | Front Page Settings. The screen showing all available parameters will be loaded displaying your current settings that are changeable. ts. Setting Description Full site name This is the name that appears in the browser's title bar. It is usually the full name of your organization, or the name of the dedicated course, or qualification the site is used for. Short name for site This is the name that appears as the first item in the breadcrumb trail. Front Page Description This description of the site will be displayed on the front page via the Site Description block. It can, therefore, only be displayed in the left or right column, never in the center of the front page. The description text is also picked up by the Google search engine spider, if allowed. Front Page Moodle can display up to four elements in the center column of the front page when not logged in. List of courses List of categories News items Combo list(categories and courses) The order of the elements is the same as the one chosen in the pull-down menus. Front page items when logged in Same as "Front Page", but used when logged in. Include a topic section If ticked, an additional topic section (just like the topic blocks in the center column of a topics-format course) appears on top of the front page's center column. It can contain any mix of resources or activities available in Moodle. It is very often used to provide information about the site. News items to show Number of news items that are displayed. Courses per page This is a threshold setting that is used when displaying courses within categories. If there are more courses in a category than specified, page navigation will be displayed at the top of the page. Also, when a combo list is used, course names are only displayed if the number is less than the specified threshold. For all other categories, only the number of courses is shown after the category name. Allow visible courses within hidden categories By default, courses in hidden categories are not shown unless the said setting is applied. Default frontpage role If logged-in users should be allowed to participate in front page activities, a default front page role should be set. The default is None.   Arranging Front Page Blocks To configure the left and right column areas with blocks, you have to turn on editing (using the Blocks editing on button). The menu includes blocks that are not available in courses such as Course/Site description and Main menu. Blocks are added to the front page in exactly the same way as in courses. To change their position, use the standard arrows. The Main Menu block allows you to add any installed Moodle resource or activity inside the block. For example, using labels and links to (internal or external) websites, you are able to create a menu-like structure on your front page. If the Include a topic section parameter has been selected in the Front Page settings, you have to edit the part and add any installed Moodle activity or resource. This topic section is usually used by organizations to add a welcome message to visitors, often accompanied by a picture or other multimedia content. Login From a Different Website The purpose of the Login block is for users to authenticate themselves by entering their username and password. It is possible to log into Moodle from a different website, maybe your organization's homepage, effectively avoiding the Login block. To implement this, you will have to add some HTML code on that page as shown: <form class="loginform" name="login" method="post" action="http://www.mysite.com/login/index.php">   <p>Username :     <input size="10" name="username" />   </p>   <p>Password :     <input size="10" name="password" type="password" />   </p>   <p>     <input name="Submit" value="Login" type="submit" />   </p></form> The form will pass the username and password to your Moodle system. You will have to replace www.mysite.com with your URL. This address has to be entered in the Alternate Login URL field at Users | Authentication | Manage authentication in the Site Administration block. Other Front Page Items The Moodle front page is treated as a standalone component in Moodle, and therefore has a top-level menu with a number of features that can all be accessed via the Front Page item in the Site Administration menu. Having now looked in detail at the front page settings, let's turn to examining the other available options. Front Page Roles The front page has its own context in which roles can be assigned to users. This allows a separate user to develop and maintain the front page without having access to any other elements in Moodle. Since the front page is treated as a course, a Teacher role is usually sufficient for this. Front Page Backup and Restore The front page has its own backup and restore facilities to back up and restore all elements of the front page including any content. The mechanism of performing backup and restore is the same as for course backups.   Front page backups are stored in the backupdata folder in the Site Files area, and can be accessed by anybody who is aware of the URL. It is therefore best to move the created ZIP files to a more secure location. Front Page Questions Since the Moodle front page is treated in the same way as a course, it also has its own question bank, which is used to store any questions used on front-page quizzes. For more information on quizzes and the question bank, go to the MoodleDocs at http://docs.moodle.org/en/Quiz . Site Files The files areas of all courses are separate from each other, that is, files in Moodle belong to a course and can only be accessed by users who have been granted appropriate rights. The difference between Site files and the files area of any other course is that files in Site files can be accessed without logging in. Files placed in this location are meant for the front page, but can be accessed from anywhere in the system. In fact, if the location is known, files can be even be accessed from outside Moodle. Make sure that in the Site files area, you only place files that are acceptable to be seen by users who are not authenticated on your Moodle system. Typical files to be placed in this area are any images you want to show on the front page (such as the logo of your organization) or any document that you want to be accessed (for example, the curriculum). However, it is also used for other files that are required to be accessible without access to a course, such as the Site Policy Agreement, which has to be accepted before starting Moodle. To access these publicly available Site files elsewhere (for example, as a resource within other courses), you have to copy the link location that has the format: http://mysite.com/file.php/1/file.doc. Allow Personalization via My Moodle By default, the same front page is displayed for all users on your Moodle system. To relax this restriction and to allow users to personalize their own front page, you have to activate the My Moodle feature via the Force users to use My Moodle setting in Appearance | My Moodle in the Site Administration block. Once enabled, Moodle creates a /my directory for each user (except administrators) at their first login, which is displayed instead of the main Moodle front page. It is a very flexible feature that is similar to a customizable dashboard, but requires some more disk space on your server. Once logged in, users will have the ability to edit their page by adding blocks to their My Moodle area. The center of the page will be populated by the main front page, for instance displaying a list of courses, that users cannot modify. Making Blocks Sticky There might be some blocks that you wish to "stick", that is, display on each My Moodle page, making them effectively compulsory blocks. For example, you might want to pin the Calendar block on the top right corner of each user's My Moodle page. To do this, go to Modules | Blocks | Sticky blocks in the Site Administration block and select My Moodle from the pull-down menu. You can now add any item from the pull-down menu in the Blocks block. If the block is single instance (that is, only one occurrence is allowed per page), the block will not be available for the user to choose from. If the user has already selected a particular block, a duplicate will appear on their site, which can be edited and deleted. To prevent users from editing their My Moodle pages, change the moodle/my: manageblocks capability in the Authenticated user role from Allow to Not set. The sticky block feature is also available for course pages. A course creator has the ability to add and position blocks inside a course unless they have been made sticky. Select the Course page item from the same menu to configure the sticky blocks for courses, as shown in the preceding screenshot. Summary After providing a general overview of look and feel elements in Moodle, the article covered front page customization. As mentioned earlier, the front page in Moodle is a course. This has advantages (you can do everything you can do in a course and a little bit more), but it also has certain limitations (you can only do what you can do in a course and might feel limited by this). However, some organizations are now using the Moodle front page as their homepage.
Read more
  • 0
  • 0
  • 17368
Modal Close icon
Modal Close icon