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-developing-web-applications-using-javaserver-faces-part-1
Packt
27 Oct 2009
6 min read
Save for later

Developing Web Applications using JavaServer Faces: Part 1

Packt
27 Oct 2009
6 min read
Although a lot of applications have been written using these APIs, most modern Java applications are written using some kind of web application framework. As of Java EE 5, the standard framework for building web applications is Java Server Faces (JSF). Introduction to JavaServer Faces Before JSF was developed, Java web applications were typically developed using non-standard web application frameworks such as Apache Struts, Tapestry, Spring Web MVC, or many others. These frameworks are built on top of the Servlet and JSP standards, and automate a lot of functionality that needs to be manually coded when using these APIs directly. Having a wide variety of web application frameworks available (at the time of writing, Wikipedia lists 35 Java web application frameworks, and this list is far from extensive!), often resulted in "analysis paralysis", that is, developers often spend an inordinate amount of time evaluating frameworks for their applications. The introduction of JSF to the Java EE 5 specification resulted in having a standard web application framework available in any Java EE 5 compliant application server. We don't mean to imply that other web application frameworks are obsolete or that they shouldn't be used at all, however, a lot of organizations consider JSF the "safe" choice since it is part of the standard and should be well supported for the foreseeable future. Additionally, NetBeans offers excellent JSF support, making JSF a very attractive choice. Strictly speaking, JSF is not a web application framework as such, but a component framework. In theory, JSF can be used to write applications that are not web-based, however, in practice JSF is almost always used for this purpose. In addition to being the standard Java EE 5 component framework, one benefit of JSF is that it was designed with graphical tools in mind, making it easy for tools and IDEs such as NetBeans to take advantage of the JSF component model with drag-and-drop support for components. NetBeans provides a Visual Web JSF Designer that allow us to visually create JSF applications. Developing Our first JSF Application From an application developer's point of view, a JSF application consists of a series of JSP pages containing custom JSF tags, one or more JSF managed beans, and a configuration file named faces-config.xml. The faces-config.xml file declares the managed beans in the application, as well as the navigation rules to follow when navigating from one JSF page to another. Creating a New JSF Project To create a new JSF project, we need to go to File | New Project, select the Java Web project category, and Web Application as the project type. After clicking Next, we need to enter a Project Name, and optionally change other information for our project, although NetBeans provides sensible defaults. On the next page in the wizard, we can select the Server, Java EE Version, and Context Path of our application. In our example, we will simply pick the default values. On the next page of the new project wizard, we can select what frameworks our web application will use. Unsurprisingly, for JSF applications we need to select the JavaServer Faces framework. The Visual Web JavaServer Faces framework allows us to quickly build web pages by dragging-and-dropping components from the NetBeans palette into our pages. Although it certainly allows us to develop applications a lot quicker than manually coding, it hides a lot of the "ins" and "outs" of JSF. Having a background in standard JSF development will help us understand what the NetBeans Visual Web functionality does behind the scenes. When clicking Finish, the wizard generates a skeleton JSF project for us, consisting of a single JSP file called welcomeJSF.jsp, and a few configuration files: web.xml, faces-config.xml and, if we are using the default bundled GlassFish server, the GlassFish specific sun-web.xml file is generated as well. web.xml is the standard configuration file needed for all Java web applications. faces-config.xml is a JSF-specific configuration file used to declare JSF-managed beans and navigation rules. sun-web.xml is a GlassFish-specific configuration file that allows us to override the application's default context root, add security role mappings, and perform several other configuration tasks. The generated JSP looks like this: <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <f:view> <h1> <h:outputText value="JavaServer Faces"/> </h1> </f:view> </body> </html> As we can see, a JSF enabled JSP file is a standard JSP file using a couple of JSF-specific tag libraries. The first tag library, declared in our JSP by the following line: <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> is the core JSF tag library, this library includes a number of tags that are independent of the rendering mechanism of the JSF application (recall that JSF can be used for applications other than web applications). By convention, the prefix f (for faces) is used for this tag library. The second tag library in the generated JSP, declared by the following line: <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> is the JSF HTML tag library. This tag library includes a number of tags that are used to implement HTML specific functionality, such as creating HTML forms and input fields. By convention, the prefix h (for HTML) is used for this tag library. The first JSF tag we see in the generated JSP file is the <f:view> tag. When writing a Java web application using JSF, all JSF custom tags must be enclosed inside an <f:view> tag. In addition to JSF-specific tags, this tag can contain standard HTML tags, as well as tags from other tag libraries, such as the JSTL tags. The next JSF-specific tag we see in the above JSP is <h:outputText>. This tag simply displays the value of its value attribute in the rendered page. The application generated by the new project wizard is a simple, but complete, JSF web application. We can see it in action by right-clicking on our project in the project window and selecting Run. At this point the application server is started (if it wasn't already running), the application is deployed and the default system browser opens, displaying our application's welcome page.
Read more
  • 0
  • 0
  • 2614

article-image-creating-vbnet-application-enterprisedb
Packt
27 Oct 2009
5 min read
Save for later

Creating a VB.NET application with EnterpriseDB

Packt
27 Oct 2009
5 min read
Overview of the tutorial You will begin by creating an ODBC datasource for accessing data on the Postgres server. Using the User DSN created you will be connecting to the Postgres server data. You will derive a dataset from the table which you will be using to display in a datagrid view on a form in a windows application. We start with the Categories table that was migrated from MS SQL Server 2008. This table with all of its columns is shown in the Postgres studio in the next figure. Creating the ODBC DSN Navigate to Start | Control Panel | Administrative Tools | Data Sources (ODBC) to bring up the ODBC Database Manager window. Click on Add.... In the Create New Data Source scroll down to EnterpriseDB 8.2 under the list heading Name as shown. Click Finish. The EnterpriseDB ODBC Driver page gets displayed as shown. Accept the default name for the Data Source(DSN) or, if you prefer, change the name. Here the default is accepted. The Database, Server, User Name, Port and the Password should all be available to you [Read article 1]. If you click on the option button Datasource you display a window with two pages as shown. Make no changes to the pages and accept defaults but make sure you review the pages. Click OK and you will be back in the EnterpriseDB Driver window. If you click on the button Global the Global Settings window gets displayed (not shown). These are logging options as the page describes. Click Cancel to the Global Settings window. Click on the Test button and verify that the connection was successful. Click on the Save button and save the DSN under the list heading User DSN. The DSN EnterpriseDB enters the list of DSN's created as shown here. Create a Windows Forms application and Establish a connection to Postgres Open Visual Studio 2008 from its shortcut. Click File | New | Project... and open the New Project window. Choose a windows forms project for Framework 2.0. Besides Framework 2.0 you can also create projects in other versions in Visual Studio 2008. In Server Explorer window double click the Connection icon as shown. This brings up the Add Connection window as shown. Click on Change... button to display the Change Data Source window. Scroll up and select Microsoft ODBC Data Source as shown. Click OK. Click on the drop-down handle for the option Use user or system data source name and choose EnterpriseDB you created earlier as shown. Insert User Name and Password and click on the Test Connection button. You should get a connection succeeded message as shown. Click OK on the message screen as well as to the add connection window. The connection appears in the Visual Studio 2008 in the Server Explorer as shown.     Displaying data from the table Drag and drop a DataGridView under Data in the Toolbox onto the form as shown (shown with SmartTasks handle clicked) Click on Choose Data Source handle to display a drop-down menu as shown below. Click on Add Project Data Source at the bottom. This displays the Choose a Data Source Type page of the Data Source Configuration Wizard. Accept the default datasource type and click Next. In the Choose Your Data Connection page of the wizard choose the ODBC.localhost.PGNorthwind as shown in the drop-down list. Click Next in the page that gets displayed and accept the default to save the connection string to the application configuration file as shown. Click Next. In the Choose Your Database Objects page, expand Tables and choose the categories table as shown. The default Dataset name can be changed. Herein the default is accepted. Click Finish. The DatagridView on Form1 gets displayed with two columns and a row but can be extended to the right by using drag handles to reveal all the four columns as shown. Three other objects PGNorthwindDataSet, CategoriesBindingSource, and CategoriesTableAdapter are also added to the control tray as shown. The PGNorthwindDataset.xsd file gets added to the project. Now build the project and run. The Form 1 gets displayed with the data from the PGNorthwind database as shown. In the design view of the form few more tasks have been added as shown. Here you can Add Query... to filter the data displayed; Edit the details of the columns and you can choose to add a column if you had chosen fewer columns from the original table. For example, Edit Column brings up its editor as shown where you can make changes to the styles if you desire to do so. The next figure shows slightly modified form by editing the columns and resizing the cell heights as shown. Summary A step-by-step procedure was described to display the data stored in a table in the Postgres database in a Windows Forms application. Procedure to create an ODBC DSN was also described. Using this ODBC DSN a connection was established to the Postgres server in Visual Studio 2008.
Read more
  • 0
  • 0
  • 10434

article-image-new-soa-capabilities-biztalk-server-2009-uddi-services
Packt
27 Oct 2009
6 min read
Save for later

New SOA Capabilities in BizTalk Server 2009: UDDI Services

Packt
27 Oct 2009
6 min read
All truths are easy to understand once they are discovered; the point is to discover them.-Galileo Galilei What is UDDI? Universal Description and Discovery Information (UDDI) is a type of registry whose primary purpose is to represent information about web services. It describes the service providers, the services that provider offers, and in some cases, the specific technical specifications for interacting with those services. While UDDI was originally envisioned as a public, platform independent registry that companies could exploit for listing and consuming services, it seems that many have chosen instead to use UDDI as an internal resource for categorizing and describing their available enterprise services. Besides simply listing available services for others to search and peruse, UDDI is arguably most beneficial for those who wish to perform runtime binding to service endpoints. Instead of hard-coding a service path in a client application, one may query UDDI for a particular service's endpoint and apply it to their active service call. While UDDI is typically used for web services, nothing prevents someone from storing information about any particular transport and allowing service consumers to discover and do runtime resolution to these endpoints. As an example, this is useful if you have an environment with primary, backup, and disaster access points and want your application be able to gracefully look up and failover to the next available service environment. In addition, UDDI can be of assistance if an application is deployed globally but you wish for regional consumers to look up and resolve against the closest geographical endpoint. UDDI has a few core hierarchy concepts that you must grasp to fully comprehend how the registry is organized. The most important ones are included here. Name Purpose Name in Microsoft UDDI services BusinessEntity These are the service providers. May be an organization, business unit or functional area. Provider BusinessService General reference to a business service offered by a provider. May be a logical grouping of actual services. Service BindingTemplate Technical details of an individual service including endpoint Binding tModel (Technical Model) Represents metadata for categorization or description such as transport or protocol tModel As far as relationships between these entities go, a Business Entity may contain many Business Services, which in turn can have multiple Binding Templates. A binding may reference multiple tModels and tModels may be reused across many Binding Templates. What's new in UDDI version three? The latest UDDI specification calls out multiple-registry environments, support for digital signatures applied to UDDI entries, more complex categorization, wildcard searching, and a subscription API. We'll spend a bit of time on that last one in a few moments. Let's take a brief lap around at the Microsoft UDDI Services offering. For practical purposes, consider the UDDI Services to be made up of two parts: an Administration Console and a web site. The website is actually broken up into both a public facing and administrative interface, but we'll talk about them as one unit. The UDDI Configuration Console is the place to set service-wide settings ranging from the extent of logging to permissions and site security. The site node (named UDDI) has settings for permission account groups, security settings (see below), and subscription notification thresholds among others. The web node, which resides immediately beneath the parent, controls web site setting such as logging level and target database. Finally, the notification node manages settings related to the new subscription notification feature and identically matches the categories of the web node. The UDDI Services web site, found at http://localhost/uddi/, is the destination or physically listing, managing, and configuring services. The Search page enables querying by a wide variety of criteria including category, services, service providers, bindings, and tModels. The Publish page is where you go to add new services to the registry or edit the settings of existing ones. Finally, the Subscription page is where the new UDDI version three capability of registry notification is configured. We will demonstrate this feature later in this article. How to add services to the UDDI registry? Now we're ready to add new services to our UDDI registry. First, let's go to the Publish page and define our Service Provider and a pair of categorical tModels. To add a new Provider, we right-click the Provider node in the tree and choose Add Provider. Once a provider is created and named, we have the choice of adding all types of context characteristics such as a contact name(s), categories, relationships, and more. I'd like to add two tModel categories to my environment : one to identify which type of environment the service references (development, test, staging, production) and another to flag which type of transport it uses (Basic HTTP, WS HTTP, and so on). To add atModel, simply right-click the tModels node and choose Add tModel. This first one is named biztalksoa:runtimeresolution:environment. After adding one more tModel for biztalksoa:runtimeresolution:transporttype, we're ready to add a service to the registry. Right-click the BizTalkSOA provider and choose Add Service. Set the name of this service toBatchMasterService. Next, we want to add a binding (or access point) for this service, which describes where the service endpoint is physically located. Switch to the Bindings tab of the service definition and choose New Binding. We need a new access point, so I pointed to our proxy service created earlier and identified it as an endPoint. Finally, let's associate the two new tModel categories with our service. Switch to the Categories tab, and choose to Add Custom Category. We're asked to search for atModel, which represents our category, so a wildcard entry such as %biztalksoa%  is a valid search criterion. After selecting the environment category, we're asked for the key name and value. The key "name" is purely a human-friendly representation of the data whereas the tModel identifier and the key value comprise the actual name-value pair. I've entered production as the value on the environment category, and WS-Http as the key value on thetransporttype category. At this point, we have a service sufficiently configured in the UDDI directory so that others can discover and dynamically resolve against it.
Read more
  • 0
  • 0
  • 2855

article-image-overview-cherrypy-web-application-server-part1
Packt
27 Oct 2009
6 min read
Save for later

Overview of CherryPy - A Web Application Server (Part1)

Packt
27 Oct 2009
6 min read
Vocabulary In order to avoid misunderstandings, we need to define a few key words that will be used. Keyword Definition Web server A web server is the interface dealing with the HTTP protocol. Its goal is to transform incoming HTTP requests into entities that are then passed to the application server and also transform information from the application server back into HTTP responses. Application An application is a piece of software that takes a unit of information, applies business logic to it, and returns a processed unit of information. Application server An application server is the component hosting one or more applications. Web application server A web application server is simply the aggregation of a web server and an application server into a single component. CherryPy is a web application server. Basic Example To illustrate the CherryPy library we will go through a very basic web application allowing a user to leave a note on the main page through an HTML form. The notes will be stacked and be rendered in a reverse order of their creation date. We will use a session object to store the name of the author of the note. Each note will have a URI attached to itself, of the form /note/id. Create a blank file named note.py and copy the following source code. #!/usr/bin/python# -*- coding: utf-8 -*# Python standard library importsimport os.pathimport time################################################################The unique module to be imported to use cherrypy###############################################################import cherrypy# CherryPy needs an absolute path when dealing with static data_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))################################################################ We will keep our notes into a global list# Please not that it is hazardous to use a simple list here# since we will run the application in a multi-threaded environment# which will not protect the access to this list# In a more realistic application we would need either to use a# thread safe object or to manually protect from concurrent access# to this list###############################################################_notes = []################################################################ A few HTML templates###############################################################_header = """<html><head><title>Random notes</<title><link rel="stylesheet" type="text/css" href="/style.css"></link></head><body><div class="container">"""_footer = """</div></body></html>"""_note_form = """<div class="form"><form method="post" action="post" class="form"><input type="text" value="Your note here..." name="text"size="60"></input><input type="submit" value="Add"></input></form></div>"""_author_form = """<div class="form"><form method="post" action="set"><input type="text" name="name"></input><input type="submit" value="Switch"></input></form></div>"""_note_view = """<br /><div>%s<div class="info">%s - %s <a href="/note/%d">(%d)</a></div></div>"""################################################################ Our only domain object (sometimes referred as to a Model)###############################################################class Note(object):def __init__(self, author, note):self.id = Noneself.author = authorself.note = noteself.timestamp = time.gmtime(time.time())def __str__(self):return self.note################################################################ The main entry point of the Note application###############################################################class NoteApp:"""The base application which will be hosted by CherryPy"""# Here we tell CherryPy we will enable the session# from this level of the tree of published objects# as well as its sub-levels_cp_config = { 'tools.sessions.on': True }def _render_note(self, note):"""Helper to render a note into HTML"""return _note_view % (note, note.author,time.strftime("%a, %d %b %Y %H:%M:%S",note.timestamp),note.id, note.id)@cherrypy.exposedef index(self):# Retrieve the author stored in the current session# None if not definedauthor = cherrypy.session.get('author', None)page = [_header]if author:page.append("""<div><span>Hello %s, please leave us a note.<a href="author">Switch identity</a>.</span></div>"""%(author,))page.append(_note_form)else:page.append("""<div><a href="author">Set youridentity</a></span></div>""")notes = _notes[:]notes.reverse()for note in notes:page.append(self._render_note(note))page.append(_footer)# Returns to the CherryPy server the page to renderreturn page@cherrypy.exposedef note(self, id):# Retrieve the note attached to the given idtry:note = _notes[int(id)]except:# If the ID was not valid, let's tell the# client we did not find itraise cherrypy.NotFoundreturn [_header, self._render_note(note), _footer]@cherrypy.exposedef post(self, text):author = cherrypy.session.get('author', None)# Here if the author was not in the session# we redirect the client to the author formif not author:raise cherrypy.HTTPRedirect('/author')note = Note(author, text)_notes.append(note)note.id = _notes.index(note)raise cherrypy.HTTPRedirect('/')class Author(object):@cherrypy.exposedef index(self):return [_header, _author_form, _footer]@cherrypy.exposedef set(self, name):cherrypy.session['author'] = namereturn [_header, """Hi %s. You can now leave <a href="/" title="Home">notes</a>.""" % (name,), _footer]if __name__ == '__main__':# Define the global configuration settings of CherryPyglobal_conf = {'global': { 'engine.autoreload.on': False,'server.socket_host': 'localhost','server.socket_port': 8080,}}application_conf = {'/style.css': {'tools.staticfile.on': True,'tools.staticfile.filename': os.path.join(_curdir,'style.css'),}}# Update the global CherryPy configurationcherrypy.config.update(global_conf)# Create an instance of the applicationnote_app = NoteApp()# attach an instance of the Author class to the main applicationnote_app.author = Author()# mount the application on the '/' base pathcherrypy.tree.mount(note_app, '/', config = application_conf)# Start the CherryPy HTTP servercherrypy.server.quickstart()# Start the CherryPy enginecherrypy.engine.start() Following is the CSS which should be saved in a file named style.css and stored in the same directory as note.py. html, body {background-color: #DEDEDE;padding: 0px;marging: 0px;height: 100%;}.container {border-color: #A1A1A1;border-style: solid;border-width: 1px;background-color: #FFF;margin: 10px 150px 10px 150px;height: 100%;}a:link {text-decoration: none;color: #A1A1A1;}a:visited {text-decoration: none;color: #A1A1A1;}a:hover {text-decoration: underline;}input {border: 1px solid #A1A1A1;}.form {margin: 5px 5px 5px 5px;}.info {font-size: 70%;color: #A1A1A1;} In the rest of this article we will refer to the application to explain CherryPy's design.
Read more
  • 0
  • 0
  • 3751

article-image-building-user-portal-sermyadmin-openser
Packt
27 Oct 2009
8 min read
Save for later

Building the User Portal with SerMyAdmin for OpenSER

Packt
27 Oct 2009
8 min read
SerMyAdmin Originally, this material was written for SerWeb. SerWeb was originally developed for the SER project. Unfortunately, SerWeb became incompatible with newer versions of OpenSER. Another important aspect of SerWeb to be considered is its vulnerabilities. There are very few options for web interfaces to OpenSER. One of the tools we have found is OpenSER administrator. This tool is being developed using Ruby on Rails. While it seems to be a very good tool to administer an OpenSER server, it does not permit to provisioning users in the same way that SerWeb did and it lacks multi-domain support. OpenSER administrator can be found at http://sourceforge.net/projects/openseradmin. Since a tool to build an OpenSER portal was not available , we decided to build our own tool named SerMyAdmin using Java. After a slow start, it is now ready and we are using it to build a book. It is licensed according to GPLv2 and developed in Grails (Groovy on rails). It can be downloaded at http://sourceforge.net/projects/sermyadmin. What you are seeing here is the standalone tool. In our roadmap, we intend to integrate SerMyAdmin into the Liferay portal. Using a content management system such as Liferay (www.liferay.com) will make your task of building a portal much easier than it is today. The SerMyAdmin project can be found at sermyadmin.sourceforge.net. The idea is to facilitate the administration of the OpenSER database. SerMyAdmin is licensed under the GPLv2. Lab—Installing SerMyAdmin SerMyAdmin uses the Grails framework, so it needs an application server. You can choose from many application servers, such as IBM WebSphere, JBoss, Jetty, Tomcat, and so on. In this article we will use Apache Tomcat, because it's free and easy to install. Because we use some Java 1.5 features, we'll need Sun's Java JDK, not the free alternative GCJ. Step 1: Create an administrator for SerMyAdmin: mysql –u rootuse openserINSERT INTO 'subscriber' ( 'id' , 'username' , 'domain' , 'password' , 'first_name' , 'last_name' , 'email_address' , 'datetime_created' , 'ha1' , 'ha1b' , 'timezone' , 'rpid' , 'version' , 'password_hash' , 'auth_username' , 'class' , 'domain_id' , 'role_id' )VALUES (NULL , 'admin', 'openser.org', 'senha', 'Admin', 'Admin', 'admin@openser.org', '0000-00-00 00:00:00', '1', '1', '1', '1', '1', NULL , 'admin@openser.org', NULL , '1', '3'); Step 2: The next step we will take is to update our source's list to use the contrib repository and non-free packages. Our /etc/apt/sources.list, should look like below: # /etc/apt/souces.listdeb http://ftp.br.debian.org/debian/ etch main contrib non-freedeb-src http://ftp.br.debian.org/debian/ etch main contrib non-freedeb http://security.debian.org/ etch/updates main contrib non-freedeb-src http://security.debian.org/ etch/updates main contrib non-free/etc/apt/sources.list Notice that we have added only the keywords contrib and non-free after our repository definitions. Step 3: Update the package listing using the following command: openser:~# apt-get update Step 4: Install Sun's Java 1.5, running the command below: openser:~# apt-get install sun-java5-jdk Step 5: Make sure you are using Sun's Java. Please, run the command below to tell Debian that you want to use Sun's Java as your default Java implementation. openser:~# update-java-alternatives -s java-1.5.0-sun Step 6: If everything has gone well so far, you should run the following command and get a similar output. openser:~# java -version java version "1.5.0_14" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_14-b03) Java HotSpot(TM) Client VM (build 1.5.0_14-b03, mixed mode, sharing) Step 7: Install Tomcat. You can obtain Tomcat at: http://tomcat.apache.org/download-60.cgi. To install Tomcat, just run the commands below: openser:/usr/local/etc/openser# cd /usr/localopenser:/usr/local# wget http://mirrors.uol.com.br/pub/apache/tomcat/tomcat-6/v6.0.16/bin/apache-tomcat-6.0.16.tar.gzopenser:/usr/local# tar zxvf apache-tomcat-6.0.16.tar.gzopenser:/usr/local# ln -s apache-tomcat-6.0.16 tomcat6 Step 8: To start Tomcat on your server initialization, please copy the following script to /etc/init.d/tomcat6. #! /bin/bash –e#### BEGIN INIT INFO# Provides: Apache’s Tomcat 6.0# Required-Start: $local_fs $remote_fs $network# Required-Stop: $local_fs $remote_fs $network# Default-Start: 2 3 4 5# Default-Stop: S 0 1 6# Short-Description: Tomcat 6.0 Servlet engine# Description: Apache’s Tomcat Servlet Engine### END INIT INFO## Author: Guilherme Loch Góes <glwgoes@gmail.com>#set -ePATH=/bin:/usr/bin:/sbin:/usr/sbin:CATALINA_HOME=/usr/local/tomcat6CATALINA_BIN=$CATALINA_HOME/bintest -x $DAEMON || exit 0. /lib/lsb/init-functionscase "$1" in start) echo "Starting Tomcat 6" "Tomcat6" $CATALINA_BIN/startup.sh log_end_msg $? ;; stop) echo "Stopping Tomcat6" "Tomcat6" $CATALINA_BIN/shutdown.sh log_end_msg $? ;; force-reload|restart) $0 stop $0 start ;; *) echo "Usage: /etc/init.d/tomcat6 {start|stop|restart}" exit 1 ;;esacexit 0 Step 9: Instruct Debian to run your script on startup; we do this with the command below. openser: chmod 755 /etc/init.d/tomcat6 openser:/etc/init.d# update-rc.d tomcat6 defaults 99 Step 10: To make sure everything is running correctly, reboot the server and try to open in your browser the URL http://localhost:8080; if everything is OK you'll be greeted with Tomcat's start page. Step 11: Install the MySQL driver for Tomcat, so that SerMyAdmin can access your database. This driver can be found at http://dev.mysql.com/downloads/connector/j/5.1.html. You should download the driver and unpack it, then copy the connector to Tomcat's shared library directory, as follows. openser:/usr/src# tar zxf mysql-connector-java-5.1.5.tar.gz openser:/usr/src# cp mysql-connector-java-5.1.5/mysql-connector-java-5.1.5-bin.jar /usr/local/tomcat6/lib Step 12: Declare the data source for SerMyAdmin to connect to OpenSER's database. You can do this in an XML file found at /usr/local/tomcat6/conf/context.xml. The file should look as below: <?xml version="1.0" encoding="UTF-8"?><Context path="/serMyAdmin"> <Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" maxActive="20" maxIdle="10" maxWait="-1" name="jdbc/openser_MySQL" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/openser" username="sermyadmin" password="secret"/></Context> In the file above, please change the highlighted parameters according to your scenario. SerMyAdmin can be installed in a different server than the one that holds the database. Do this for better scalability when possible. The default MySQL installation on Debian only accepts requests from localhost, so you should edit the file /etc/mysql/my.cnf, for MySQL to accept requests from external hosts. Step 13: Create a user to be referenced in the file context.xml. This user will have the required access to the database. Please, run the commands below: openser:/var/lib/tomcat5.5/conf# mysql -u root –p Enter password: Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 14 Server version: 5.0.32-Debian_7etch5-log Debian etch distribution Type 'help;' or 'h' for help. Type 'c' to clear the buffer. mysql> grant all privileges on openser.* to sermyadmin@'%' identified by 'secret'; Query OK, 0 rows affected (0.00 sec) Step 14: We're almost there. The next step is to deploy the SerMyAdmin WAR file. Please, download and copy the file serMyAdmin.war to Tomcat's webapps directory. Restart it, to activate the changes. openser:/usr/src# cp serMyAdmin-0.4.war /usr/local/tomcat6/webapps/serMyAdmin.war openser:/usr/src# invoke-rc.d tomcat6 restart Don't worry about database modifications; SerMyAdmin will automatically handle that for you. Step 15: Configure Debian's MTA (Message Transfer Agent) to allow SerMyAdmin to send a confirmation email to new users. Run the command below to configure Exim4 (default MTA for Debian). Ask your company's email administrator. openser:/# apt-get install exim4 openser:/# dpkg-reconfigure exim4-config You will be greeted with a dialog-based configuration menu; on this menu it's import to pay attention to two options: General type of mail configuration, which should be set to Internet Site so that we can send and receive mails directly using SMTP, and Domains to relay mail for, which should be set to the domain from which you want the emails from SerMyAdmin to appear to come. Step 16: Customize the file /usr/local/apache-tomcat-6.0.16/webapps/serMyAdmin-0.3/WEB-INF/spring/resource.xml, which contains the parameters that specify which email server is used to send mails and from whom these emails should appear to come from. The following is an example of this file: <?xml version="1.0" encoding="UTF-8"?><beans xsi_schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host"><value>localhost</value></property> </bean> <!-- You can set default email bean properties here, eg: from/to/subject --> <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="from"><value>admin@sermyadmin.org</value></property> </bean></beans> The first parameter to change is the server that we will use to send emails. The second is the parameter specifying from whom those emails will appear to come. Restart Tomcat again and we're ready to go. When you point your browser to http://<server address>:8080/serMyAdmin you should be greeted with the login page, the same as we have shown at the start on this article.
Read more
  • 0
  • 0
  • 1851

article-image-creating-joomla-15-templates
Packt
27 Oct 2009
16 min read
Save for later

Creating Joomla 1.5 Templates

Packt
27 Oct 2009
16 min read
Corporate Identity Corporate Identity (CI) refers to the self-image and the appearance of an enterprise. This appearance, the identity, either arises from the enterprise's tradition or it is completely invented in a newly created establishment. This identity is important to give the customer a feel for the enterprise and to enable recognition. Corporate Identity includes: Corporate Image (price, product, and advertising strategy) Corporate Design (visual appearance) Corporate Communication Corporate Behavior (behavior of employees towards each other and the outside world) All of the above areas have to be considered when developing a website. In this article, we will examine Corporate Design. At a minimum, it consists of a logo, a character font, and the house colors that the enterprise uses. The visitors to your website should recognize your enterprise on the first visit. HTML/XHTML, CSS, and XML The abbreviations HTML/XHTML, CSS, and XML stand for Internet technologies that Joomla! works with. The World Wide Web Consortium standardizes these technologies. HTML/XHTML The World Wide Web is based on HTML. HTML is not a programming language, but a text-description language. Each piece of text consists of structures like headings, lists, bold and italic areas, tables, and much more. HTML works with so-called tags. A tag has an opening portion and a closing portion. For example, a first-level heading looks as follows: <h1>This is a heading</h1> The tags are interpreted in the browser and the text is displayed according to their significance. HTML is very easy to learn and many online tutorials can be found. HTML is not being developed any further; the successor to HTML is XHTML version 1.0. CSS Cascading Style Sheets (CSS) are an extension to HTML. CSS is not a programming language either, but a vocabulary for defining the format properties of individual HTML elements. With the help of CSS commands, you can, for example, specify that the first-level headings should have a character size of 18 points in the character font Arial, are not bold, and have a spacing of 1.9 cm to the next paragraph. Such options are not possible with pure HTML and were not necessary when HTML was first developed. With the progressive commercialization of the Internet, additional formatting possibilities do, however, become more and more important. CSS data can be integrated into HTML in the following three ways: In the Central HTML File The CSS commands are defined in the head section of the HTML file like this: <head><title>title of the file</title><style type="text/css"><!--/* ... this is where the CSS commands are defined ... */--></style></head> In a Separate CSS File If the CSS commands apply to several HTML files, they can be stored in a separate file and the path to this file can be specified in the HTML header. This is the version that Joomla! uses. <head><title>title of the file</title><link rel="stylesheet" type="text/css" href="formats.css"></head> Within an HTML Tag CSS commands can also be inserted within an HTML tag: <body><h1 style="… CSS commands ...">...</h1></body> Combinations These three methods can be combined without any problem in an HTML file. It is, for instance, possible to subsequently overwrite CSS commands that were defined in a central file in the additional source code of an HTML page. This practice, however, quickly leads to confusing structures; it is better to customize the central file. XML The Extended Markup Language (XML) is a universe in itself. It represents a meta‑language and is derived from the much more complex SGML (Standardized Generalized Markup Language) that was developed in the sixties. XML is often used for configuration files and as an interchange format. For our purposes, you need XML as the description language for the metadata of the templates that you want to create. These metadata are primarily relevant for the Template Installer and the display in the Template Manager. In principle, these data also consist of opening and closing tags. For example: <name>Joomla! Book</name> The difference between HTML and XML is that no tags are predefined in XML. Because of that, you are completely unrestricted in the organization of the structures and the naming of the tags. Creating Your Own Templates Now we want to create our own template. There are several things to consider before we have a finished template packages. Let's take it one step at a time. Concept Before you start working, you have to create a concept. The work starts with a sketch or a diagram, especially when producing templates. It is up to you whether you want to create this sketch with an image editing program like Adobe Photoshop, Microsoft Paint that comes with Windows, the open-source program GIMP, or even with a piece of paper and crayons. Fixed Size or Variable (Fluid) or Both You can create two kinds of templates. Templates that adapt their structure to the size of the browser window and templates that have a fixed size. An example for the flexible layout: if you have 2048 pixels across your screen and the browser window is maximized, then your page is stretched accordingly. That can look strange if you use graphical, non-scalable elements like logos and signatures in your template. You have no control of what it is going to look like. Your other choice is to decide on a certain resolution and to position all the elements exactly on the pixels in the template. This has the advantage that your web page always looks the way you want. Unfortunately, you do not know the resolution of the monitor that is viewing your page. If that monitor has a resolution of 800 x 600 pixels, then your page fills the screen. On a large screen with a resolution of 1400 x 1050 pixels, it occupies about a quarter of the screen surface and looks a little lost. You will have to weigh the pros and cons and make a decision on one or the other, or you can consider barrier freedom and offer both versions. You must have seen websites where you can even change the font size. In addition to the font size buttons there is also often a button to select different layouts. If you prefer the fixed size, you should select a size that looks presentable on most screens, in other words 800 x 600 pixels. Since the browser has a scroll bar on the right side and the browser window is framed, the available width is even smaller, meaning that you have a maximum of 780 pixels to work with. Structure You are dealing with structured data and first have to determine a general allocation. Joomla! normally uses a structure as shown in the following figure: Section 1: Part 1: This is where your logo or a picture and the name of the website goes. Part 2: This is where the search field is. Part 3: This is where the linked navigation path goes (Breadcrumbs). Section 2: Part 4: The most important menus are shown in the left column. Part 5: The actual page content goes here. Part 6: The right column is a place for additional menus. Section 3: Part 7: The footer.     HTML Conversion Now you have to convert the concept into HTML and CSS. Depending on the graphics editing program that you have used to create it, there is a possibility that the picture can be automatically exported to HTML code. You can also do the conversion manually in a text editor, in an HTML editor like Dreamweaver (http://www.adobe.com/products/dreamweaver), or in one of the numerous free HTML editors (http://www.thefreecountry.com/webmaster/htmleditors.shtml). <table> or <div>? The <div> tag is a replacement and a supplement for the <table> tag in HTML. You can enclose several HTML elements, such as text and graphics in one common area with it. This general area does nothing for the time being but start in a new line of the continuing text. The <div> tag does not have any other properties. There are big benefits, however, in using a combination of <div> tags with CSS commands. <div> was specifically developed for the purpose of being formatted with CSS commands. Until 2004, it was common practice to define website structures with generous employment of HTML tables. With CSS and the <div> HTML element becoming more and more popular and with browsers being able to interpret these, more and more templates are being structured without HTML tables. However, rarely do we see websites that contain only semantically correct HTML and that have layouts that are built 100% without tables. The first step in structuring your website in that direction is the use of the <div> tags. Joomla! 1.5 is also gradually straying from the 'table path' and is starting to deliver semantically correct HTML. Nonetheless, it continues to be possible to structure your site layout with HTML tables. There are no table tags in the included rhuk_milkyway template; the entire table-like structure is created with <div> tags. Take a look at the original source code of this template to familiarize yourself with this technology. You can get more information about <div> tags at selfhtml (in German). Dreamweaver also supports this technology. The source code of the HTML conversion looks somewhat like the following listing. The code is kept simple on purpose and is not consistent with the XHTML standard in the header. The file name of this layout file has to be index.php since Joomla! searches it for embedded commands per PHP. HTML file /index.php: <html> <head> <link href="/joomla150/templates/joomla150buch/css/template.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="part11">header / header<br /><br /> <div id="section1">section1</div> <div id="section2">section2</div> </div> <div id="part2">main display area / main<br /><br /> <div id="section3">breadcrumbs</div> <div id="section6">right side</div> <div id="section4">left side</div> <div id="section5">content</div> </div> <div id="part3">footer /footer<br /><br /> <div id="section7">section7</div> </div> </body></html> The subsequent CSS file from the individual template is integrated into the header area of the code. At the moment this CSS file contains only one command that defines the typeface. CSS file /css/template.css: body{font-size: 12px;font-family: Helvetica,Arial,sans-serif; }#Part1{ /*header*/float: left;border: 2px dotted green; }#Part2{ /*main*/float: left;border: 2px dotted yellow; }#Part3{ /*footer*/clear:all;border: 2px dotted red; }#Section1{ /*top right*/float: left; width: 18em;margin: 0 0 1.2em;border: 1px dashed silver; background-color: #eee; }#Section2{ /*top left*/float: right; width: 12em;margin: 0 0 1.1em;background-color: #eee; border: 1px dashed silver; }#Section3{ /*breadcrumbs*/border: 1px dashed silver;background-color: #eee; }#Section4{ /*left side*/float: left; width: 15em;margin: 0 0 1.2em;border: 1px dashed silver; }#Section5{ /*content*/margin: 0 12em 1em 16em;padding: 0 1em;border: 1px dashed silver; }#Section6{ /*right side*/float: right; width: 12em;margin: 0 0 1.1em;background-color: #eee; border: 1px dashed silver; }#Section7{ /*footer*/margin: 0 0 1.1em;background-color: #eee; border: 1px dashed silver; } You will create this first template manually in the Joomla! directory. When the template is ready, you can turn it into a compressed installation package that it can then be installed by a third party (or by you yourself) using the Joomla! installer. Save the HTML layout file by the name of index.php in the also newly created [PathtoJoomla]/templates/joomla150book/ directory. Save the template.css file in the [PathtoJoomla]/templates/joomla150book/css/ directory. The basic structure of your template is done. Now you have to define the template more exactly for Joomla! with the help of an XML file so that it will be displayed in the template administration section. Directory Structures of the Template Now it's time to take care of certain conventions. As previously discussed, the template has to be stored in a specific directory structure. [PathtoJoomla]/templates/[name of the template]/[PathtoJoomla]/templates/[name of the template]/CSS/[PathtoJoomla]/templates/[name of the template]/images/ The name of the template cannot contain blanks and other special characters. When this template is later installed as a package, the Template Installer has to create a directory from this name. Depending on the operating system, exotic combinations of characters can cause problems. In addition, the name should be meaningful. Here we will use joomla150book as the name of the template. Various files with predefined names have to be present in the template directories. Layout File: This is the HTML file that we created earlier:/templates/joomla150book/index.php. It should have the .php ending, since the dynamic Joomla! module elements that we will insert later have to be interpreted by PHP. Preview Picture: The /templates/joomla150book/template_thumbnail.png file contains a preview image of your template for preview selection in Joomla! administration in the Extensions | Template Manager menu. Preview pictures have a format of 200 by approximately 150 pixels. You can create this file later when you can see your template. Metadata of the Template: The /templates/joomla150_book/templateDetails.xml file represents the construction manual for the template installer and contains the installations for the template selection in the template manager. Here you specify the location where the files are to be copied, who the author is, and additional metadata about the template. During subsequent installation of this file by the Joomla! installer, PHP reads this file and copies the files to the place specified by the XML file. For the example template, you can use the file from the following listing (templateDetails.xml) and populate it with your own data. For every file that you use in the template, a respective XML container has to be populated with the file name and the correct path. <files> <filename> ... enter the filename of a file in the TemplateRoot directory ... </filename> <filename> ... for every file a filename-Container </filename></files> The other containers of the XML file are there for the description of the template. Here is the complete functional listing of the XML file: templateDetails.xml: <install version="1.5" type="template"><name>joomla150book</name><version>1.0</version><creationDate>11.11.2007</creationDate><author>Hagen Graf</author><copyright>GNU/GPL</copyright><authorEmail>hagen@cocoate.com</authorEmail><authorUrl>http://www.cocoate.com</authorUrl><version>0.1</version><description>... description</description><files><filename>index.php</filename><filename>templateDetails.xml</filename><filename>template_thumbnail.png</filename><filename>css/template.css</filename></files></install> Create the templateDetails.xml file in the [PathtoJoomla]/templates/joomla150book/ directory as well. CSS File: You can use several CSS files for your template. What name you give the CSS file and how you create it is up to you. There are, however, standard descriptions for various CSS elements. For your first attempt, you need a CSS file with the name /templates/joomla150_book/css/template.css. Graphics, Images: Here you can enter user-defined image files that you need in your template. The installer then copies the files into the images folder. The file name appears as /templates/joomla150_book/images/[user-defined image files]. First Trial Run Once you have reproduced all the structures in the [pathtoJoomla!]/templates/ subdirectory, you can already see your new template in the Extensions | Template Manager menu of your Joomla! administration and you can make it default: When you call up your website, you will see your new template. Unfortunately, there is no content shown yet. Since this content is produced dynamically, you have to integrate it piece by piece into your new template. Integration of the Joomla! Module The integration of the Joomla! module takes place by means of commands embedded into the HTML code. Joomla! uses the namespace jdoc to integrate various elements into the template. If you insert the following highlighted line into the header of the layout file: <head><jdoc:include type="head" /> </head> the title of the site and the news feed symbol are already correctly displayed. If you call up the source code of this site, you will notice that Joomla! has copied the entire metadata that you had entered in administration into the HTML code. In addition, the RSS feeds have been integrated by means of link tags and these will be displayed as feed symbols in browsers like Firefox that support this technology. Joomla! Metadata: <head> <base href="http://localhost/joomla150/" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="index, follow" /> <meta name="keywords" content="joomla, joomla!, Joomla, Joomla!, J!" /> <meta name="description" content="Joomla! - dynamic portal-engine and Content-Management-System" /> <meta name="generator" content="Joomla! 1.5 - Open Source Content Management" /> <title>Welcome to the Frontpage</title> <link href="/joomla150/index.php?format=feed&amp;type=rss" rel="alternate" type="application/rss+xml" title="RSS 2.0" /> <link href="/joomla150/index.php?format=feed&amp;type=atom" rel="alternate" type="application/atom+xml" title="Atom 1.0" /> <script type="text/javascript" src="/joomla150/media/system/js/mootools.js"></script> <script type="text/javascript" src="/joomla150/media/system/js/caption.js"></script>...  
Read more
  • 0
  • 0
  • 2039
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-aspnet-35-cms-adding-security-and-membership-part-1
Packt
27 Oct 2009
10 min read
Save for later

ASP.NET 3.5 CMS: Adding Security and Membership (Part 1)

Packt
27 Oct 2009
10 min read
Security is a concern in any web application, but the security this article deals with is that of user accounts, membership, and roles. We'll be using the ASP.NET membership and roles functions to allow certain users such as administrators to perform specific tasks. These tasks may include managing the application, while other users such as content editors, may be restricted to the specific tasks we want them to manage such as adding or changing content. User account management can be handled either by the application (in our case, our Content Management System) or by Windows itself, using standard Windows authentication functions, as well as file and folder permissions. The advantage of an application-based user authentication system is primarily in cost. To use Windows authentication, we need to purchase Client Access Licenses (CALs) for each user that will access our application. This is practical in an intranet, where users would have these licenses to perform other functions in the network. However, for an Internet application, with potentially thousands of users, licensing could be extremely expensive. The drawback to an application-based system is that there is a lot more work to do in designing and using it. The Windows authentication process has been around for years, continually improved by Microsoft with each Windows release. It scales extremely well, and with Active Directory, can be extended to manage just about anything you can think of. ASP.NET membership Fortunately, Microsoft has provided relief for application-based authentication drawbacks in the 2.0 version of the ASP.NET framework, with the ASP.NET membership functions, and in our case, the SqlMembershipProvider. The membership API makes it simple for us to use forms authentication in our application, retrieving authentication and membership information from a membership provider. The membership provider abstracts the membership details from the membership storage source. Microsoft provides two providers—the ActiveDirectoryMembershipProvider that uses Active Directory and the SqlMembershipProvider that uses an SQL server database for the user data store. By default, ASP.NET authentication uses cookies—small text files stored on the user's system—to maintain authentication status throughout the application. These cookies normally have an expiration time and date, which requires users to log in again after the cookie has expired. It is possible to use cookies to allow the client system to authenticate the application without a user login, commonly seen as a "Remember Me" checkbox in many web site login pages. There is naturally a downside to cookies in that a client system may not accept cookies. ASP.NET can encode the authentication information into the URL to bypass this restriction on cookies. Although in the case of our application, we will stick with the cookie method. Forms authentication secures only ASP.NET pages. Unless you are using IIS7, and the integrated pipeline, where ASP.NET processes all file requests, the ASP.NET DLL won't be called for non-ASP.NET pages. This means that you cannot easily secure HTML pages, PDF files, or anything other than ASP.NET through forms authentication. Configuring and using forms authentication Let's start learning ASP.NET forms authentication by walking through a brand new application. We'll then add it to our Content Management System application. Forms authentication is actually quite simple, both in concept and execution, and a simple application can explain it better than adopting our current CMS application. Of course, we eventually need to integrate authentication into our CMS application, but this is also easier once you understand the principles and techniques we'll be using. Creating a new application Start by opening Visual Web Developer 2008 Express and creating a new web site by clicking on File | New Web Site. Use the ASP.NET Website template, choose File System, and name the folder FormsDemo. When the site is created, you are presented with a Default.aspx page created with generic code. We will use this as our home page for the new site, although we need to modify it for our needs. Creating the home page Visual Web Developer 2008 Express creates a generic Default.aspx file whenever you create a new site. Unfortunately, the generic file is not what we want and will need modification. The first thing we want to do is make sure our site uses a Master Page, just as our Content Management System application will. To do this, we could delete the page, create our Master Page, and then add a new Default.aspx page that uses our Master Page. In the case of a brand new site, it's pretty easy, but what if you have developed an extensive site that you want to convert to Master Pages? You would want to add a Master Page to an existing site, so let's go ahead and do that. Create the Master Page To create a Master Page, leave the Default.aspx file open and press Ctrl+Shift+A to add a new item to the solution. Choose the Master Page template and leave the name as MasterPage.Master. Place the code in a separate file and click Add to create the Master Page. You will notice that this creates the same generic code as in the previous chapter. Unfortunately, our Default.aspx file is not a content page and won't use the MasterPage.Master we just created, unless we tell it to. To tell our Default.aspx page to use the MasterPage.Master, we need to add the MasterPageFile declaration, in the @ Page declaration, at the top of the file. Add the following code between the Language and AutoEventWireup declarations: MasterPageFile="~/MasterPage.master" This adds the Master Page to our Default.aspx page. However, content pages include only those Content controls that match the Master Page, not the full page code as our Default.aspx page currently does. To fix this, replace the remaining code outside the @ Page declaration with the following two Content controls: <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <h1>This is where the content goes.</h1></asp:Content> We've left the Content1 control empty for the moment, and we've added a simple text statement to the Content2 control so that it can be tested. If you view the Default.aspx page in a browser, you should see the relatively uninteresting web page below: Enabling forms authentication Okay, we have a boring home page for our new site. Let's leave it for a moment and enable forms authentication for the site, so we can restrict who can access our home page. The process of enabling forms authentication is simply adding a few lines to our web.config file. Or in the case of the generic web.config file, which we created while creating our new site, we simply need to alter a single line. Open the web.config file in the new site and look for the line that says: <authentication mode="Windows" /> Edit it to read: <authentication mode="Forms" /> Save the web.config file and you have now enabled forms authentication for this site. The default authentication mode for ASP.NET applications is Windows, which is fine if you're working in an intranet environment where every user probably has a Windows login for use in the corporate network anyway. Using Windows authentication, Windows itself handles all the security and authentication, and you can use the myriad of Windows utilities and functions such as Active Directory, to manage your users. On the other hand, with forms authentication, ASP.NET is expected to handle all the details of authentication and security. While ASP.NET 2.0 and later have sophisticated membership and profile capabilities, there is no ASP.NET mechanism for protecting files and folders from direct access, outside of the application. You will still need to secure the physical server and operating system from outside of your application. Creating the membership database To use forms authentication and the SqlMembershipProvider, we need to create a database to authenticate against. This database will hold our user information, as well as membership information, so we can both authenticate the user and provide access based on membership in specific roles. For our demonstration, we will create a new database for this function. We'll create a database with SQL Server ManagementExpress, so open it and right-click Databases in the Object Explorer pane. Choose New Database and name it FormsDemo. Change the location of the database path to the App_Data folder of your FormsDemo web application—the default is C:InetpubFormsDemoApp_Data as shown below. Click OK and the new database will be created. If you look at this database, you will see that it is empty. We haven't added any tables to it, and we haven't set up any fields in those non-existent tables. The database is pretty much useless at this stage. We need to create the database layout, or schema, to hold all the authentication and membership details. Fortunately, Microsoft provides a simple utility to accomplish this task for the 2.0 version of the ASP.NET framework – aspnet_regsql.exe. We'll use this too, in order to create the schema for us, and make our database ready for authentication and membership in our application. To use aspnet_regsql.exe, we need to provide the SQL Server name and login information. This is the same information as shown in the login dialog when we open the database in SQL Server Management Studio Express, as shown below: Note the server name, it will usually be {SystemName}/SQLEXPRESS, but it may be different depending on how you set it up. We use SQL Server Authentication with the sa account and a password of SimpleCMS when we set up SQL Server Express 2005, and that's what we'll use when we run the aspnet_regsql.exe tool. To run aspnet_regsql.exe, you may browse to it in Windows Explorer, or enter the path into the Run dialog when you click on Start and then Run. The default path is C:WINDOWSMicrosoft.NETFrameworkv2.0.50727aspnet_regsql.exe. The utility may be run with command-line arguments, useful when scripting the tool or using it in a batch file, but simply running it with no parameters brings it up in a GUI mode. When the ASP.NET SQL Server Setup Wizard launches, click Next. Make sure that the Configure SQL Server for application services is selected and click on Next. The ASP.NET SQL Server Setup Wizard will ask for the server, authentication, and database. You should enter these according to the information from above. Click Next to confirm the settings. Click Next again to configure the database with the ASP.NET users and membership schema. Continue and exit the wizard, and the database is ready for us to use for authentication. If you were to open the FormsDemo database in SQL Server Management Studio Express, you would find that new tables, views, and stored procedures have been added to the database during this configuration process.
Read more
  • 0
  • 0
  • 2832

article-image-reporting-planning-data-ibm-cognos-8-publish-and-bi-integration
Packt
27 Oct 2009
11 min read
Save for later

Reporting Planning Data in IBM Cognos 8: Publish and BI Integration

Packt
27 Oct 2009
11 min read
When your users save and submit plans on the Contributor Web Client, Contributor saves and stores this data in XML format in a relational database. The stored data needs to be translated into a format that is easily readable and accessible to other IBM Cognos tools and databases. The publishing feature in Contributor works like a translator and converts the XML format data into a readable format. Accessing planning data There are two elementary methods in which planning data can be accessed for reporting. The first method allows you to access real-time data either by creating a planning package during a GTP or through the Planning Data Service (PDS). The data is revealed by opening up a slice of the application. This process is slow and is better suited to ad hoc reporting rather than for full-scale reporting purposes. The second method involves moving the planning data to a separate star schema datastore by using the publish process and reporting off of this database. This option is far more suited to reporting and ETL purposes. Publish When your users save and submit plans on the Contributor Web Client, Contributor saves and stores this data in XML format in a relational database. The stored data needs to be translated into a format that is easily readable and accessible to other IBM Cognos tools and databases. The publishing feature in Contributor works like a translator and converts the XML format data into a readable format. Publishing is an administrative task, and it is executed by the Contributor job system. You, as an administrator, can either manually publish data or automate the publishing task by using a Contributor macro. The frequency of data publishing is dictated by the needs of the consumers' tools, such as IBM Cognos Report Studio, or as an enterprise data warehouse. Although Contributor-published data can be used for various purposes, the following are the most common business uses of published data: Reporting plan data using IBM Cognos reporting tools, such as Report Studio, Analysis Studio, and Query Studio Performing additional analysis on submitted plan data by using IBM Cognos Planning Analyst Loading plan data back into a general ledger or ERP system Storing published data Contributor stores published data in a separate datastore, which IBM Cognos documentation refers to as the 'publish container'. Unlike the Contributor application datastore, which is a transactional database, the publish container has a different life cycle and contains a significantly different storage and performance profile. There are two different types of publish containers available, and we will examine both types of containers in the next section. The two types of containers are: The Table-only Layout Publish Container The View Layout Publish Container The following are the steps required to create a publish container. Note that the steps to create a publish container apply to both types of publish layouts. Select the application and click on the Production branch. Select either the Table-only Layout or the View Layout from the Publish branch. Click on the Configure button on the Option tab. You may or may not have the required rights to create the publish container. See the following section. Click on the Create New button on the Select Publish Datastore Container screen. Click on the Star icon on the Configure Datastore Server Connection screen. This opens the Create a New Publish Container screen. Type the name of the publish container and the location of the database files on the Create a New Publish Container screen. Click on the Create button. Click on the Test Connection button on the Configure Datastore Server Connection screen to test the configuration. Click on OK twice on the next two messages. Add this new publish container to the Job system by opening the Job Server Cluster branch and selecting a cluster or job server. You are ready to publish data. Who can publish You need the following rights to successfully complete the administrative duties related to creating the publish container and publishing data. Access Rights: This gives you rights to perform publishing tasks. You can configure these rights on the following Access Rights screen. Note that the default Access Rights should work in most cases. Database Rights: Published data is stored in a database (called Container). The account that creates the publish container needs database creation rights (DDL) to create and modify a publish container. If this account does not have DDL rights, you can ask the database administrator to create and modify a publish container. In the Contributor Administration Console, you can generate a script for the database administrators, so that they can create and modify a publish container. Publishing using the Table-only layout The recommended Table-only layout is an optimized publish layout for IBM Cognos BI reporting tools. As discussed later in this chapter, the Framework Manager (FM) model, which uses the Framework Manager Extension, requires this layout. You can also transmit data from the Table-only layout published tables to external databases, such as data mart or data warehouse. Several tables are created when you run the Table-only publish layout. Three important types of tables are D-List items tables, hierarchy tables, and D-Cube export tables. The following is a description of these tables. You can create reporting models from these key tables to report on planning data. D-List items tables (it_table): One table is created for each D-List in the planning model. Each item table describes the contents of a D-List. For example, you may find a month item table storing month details, such as Jan, Feb, Mar, and so on. Hierarchy tables (sy_ and cy_table): The two most commonly used hierarchy tables are cy_ (Calculated hierarchy) and sy_ (Simple hierarchy). In most of the cases, the contents of these two tables will be very similar. Derived hierarchy lists found in sy_ table allow reporting tools to automatically generate summaries for each level of the hierarchy. The complete hierarchy lists found in cy_table are intended to be used when a D-List contains complex calculations between D-List items. You can use complete hierarchy lists, which are already in the Planning application, to avoid having to recreate calculations in your IBM Cognos 8 report. Export tables (et_table): One table is created for each D-Cube in the planning model. For example, you may find the Sales cube export table when we publish the Sales cube of the ABC Company's model. The following are the steps to publish the Table-only Layout: Select Production|Publish|Table-only Layout. Select the cube that is to be published, and then select a dimension to be published. The dimension for publish reduces the data volume to be published. It provides the measure dimension for the reporting environment. The measure dimension is typically referred to as a calculation D-List in the planning model, for example, the PL D-List in the ABC Company model. The following illustration identifies the differences in the table structures when you choose or do not choose a dimension for publish: Select the e.List items to be published. As a minimum, you must have reconciled all e.List items in an application before you execute the publish job. Select the options to be used when publishing. Click on the Publish button. The program will create a publish job. You can monitor the publish job by using the Monitor Console branch. Publishing data changes (incremental publish) When you publish data using the Table-only Layout structure, the program takes a snapshot of the data entered in the Contributor Web Client, and then publishes and stores this in the published tables. Practically, you select all nodes to publish, even though you can choose to publish selected nodes. Depending on the number of e.List items being published, and the availability of job servers, a publish job can take anywhere from a few minutes to many hours. Because of the batch nature of the publish mechanism, a latency period exists between the time that users input plan numbers in the Web Client, and the time when the program populates the plan numbers in the publish container by using the publish feature. Because of this latency, it was impractical to produce a real time reporting solution in versions prior to 8.2, especially when IBM Cognos reporting studios relied on planning published containers. The incremental publishing feature, also called trickled publishing, solves this real-time data publish and reporting problem. Instead of publishing all nodes, the incremental publish scans data changes and publishes only the changes. For example, assume there are five e.List nodes in an application. When you publish the application using the Table-only Layout option, the program publishes all nodes. (We assume that you have selected all nodes to be published.) Now, assume that a user enters revised plan numbers in e.List node 4. Without the incremental publish feature turnedon, you must publish all nodes, as you, as an administrator, cannot tell who has entered or revised planning numbers on the Contributor Web Client, or when they did this. However, when you have incremental publish turnedon, the program would publish only e.List node 4. It is important to note that a stabilized application will get the most benefit from the incremental publishing feature. If your application requires significant changes, such as e.List updates or model structural changes, you have to republish all nodes before you go back to using the incremental publish feature. To accomplish real-time publishing and reporting, you have to configure the following items: Configure the Table-only Layout publish container Publish all nodes by using the Table-only Layout publish Configure incremental publish Configure macro incremental publish Schedule the macro by using the Scheduling feature in the IBM Cognos Connection Publishing using the View Layout The View Layout was the only type of publishing available in IBM Cognos Planning version 7.2 and earlier. IBM Cognos kept this layout for its backward compatibility, as many applications and models are dependent on this feature. You can also transmit data from the View Layout published tables to external databases, such as data mart or data warehouse. Some differences between both layouts are noted in the following table: Table Layout View Layout Greater flexibility in reporting on planning data Intended for backward compatibility Source to other data mart and source systems Source to other data mart and source systems Required by Generate Framework Manager Model Admin Extension Slower publish performance and inefficient data storage Employs better naming conventions     The following are the steps to publish the View Layout: Select Your Application | Development | Application Maintenance | Dimensions for Publish. The selection of dimension for publish is optional in the View Layout publish. Execute the GTP. Select Your Application | Production | Publish | View Layout. Create a new container, if one has not yet been created. Add this new publish container to the Job system by opening the Job Server Cluster branch and selecting a cluster or job server. Note that you cannot use the Table-only Layout publish container for the View Layout publishing. Read the section on Storing Published Data earlier in this article. Select the cubes to be published. Select the e.List items to be published. Select the options to be used when publishing. Click on the Publish button. The program will create a publish job. You can monitor the publish job by using the Monitor Console branch. Automating publishing jobs You can automate publishing jobs by using the following macros: Publish—View Layout Publish—Table Only Layout Publish—Incremental Publish Understanding the impact of changes Changes to e.List, model, and dimension for publish may range from having no impact, to having a significant impact, on the publishing process, tables, and BI reports. Some of these changes, and their impacts, are noted below. e.List changes When you add e.List items, you have to reselect these added e.List items on the Publish screen. The Publish screen tries to select e.List items that were most recently used in situations where e.List items have been removed. When you modify an e.List or D-List hierarchy, for example, adding/removing a hierarchical level, you have to adjust the BI (Framework Manager) models so that the reports do not break. Model changes Changes in the model structure, for example by changing D-List items, adding or removing a D-List from a cube, or reordering the dimensions in a cube, can range from having no impact, to having a significant impact. For example, when you delete dimensions in a cube, a reconfiguration or restructuring of publishing parameters and published tables is required. The Framework Manager model, if attached to the publish table, needs to be reconfigured so that the reports do not break. Dimension for publish changes When you change the dimension for publish, the program needs to restructure the published tables. The Framework Manager model, if attached to the publish table, needs to be reconfigured so that the reports do not break.    
Read more
  • 0
  • 0
  • 2401

article-image-creating-shopping-cart-using-zend-framework-part-1
Packt
27 Oct 2009
13 min read
Save for later

Creating a Shopping Cart using Zend Framework: Part 1

Packt
27 Oct 2009
13 min read
Our next task in creating the storefront is to create the shopping cart. This will allow users to select the products they wish to purchase. Users will be able to select, edit, and delete items from their shopping cart. Lets get started. Creating the Cart Model and Resources We will start by creating our model and model resources. The Cart Model differs from our previous model in the fact that it will use the session to store its data instead of the database. Cart Model The Cart Model will store the products that they wish to purchase. Therefore, the Cart Model will contain Cart Items that will be stored in the session. Let's create this class now. application/modules/storefront/models/Cart.php class Storefront_Model_Cart extends SF_Model_Abstract implements SeekableIterator, Countable, ArrayAccess { protected $_items = array(); protected $_subTotal = 0; protected $_total = 0; protected $_shipping = 0; protected $_sessionNamespace; public function init() { $this->loadSession(); } public function addItem( Storefront_Resource_Product_Item_Interface $product,$qty) { if (0 > $qty) { return false; } if (0 == $qty) { $this->removeItem($product); return false; } $item = new Storefront_Resource_Cart_Item( $product, $qty ); $this->_items[$item->productId] = $item; $this->persist(); return $item; } public function removeItem($product) { if (is_int($product)) { unset($this->_items[$product]); } if ($product instanceof Storefront_Resource_Product_Item_Interface) { unset($this->_items[$product->productId]); } $this->persist(); } public function setSessionNs(Zend_Session_Namespace $ns) { $this->_sessionNamespace = $ns; } public function getSessionNs() { if (null === $this->_sessionNamespace) { $this->setSessionNs(new Zend_Session_Namespace(__CLASS__)); } return $this->_sessionNamespace; } public function persist() { $this->getSessionNs()->items = $this->_items; $this->getSessionNs()->shipping = $this->getShippingCost(); } public function loadSession() { if (isset($this->getSessionNs()->items)) { $this->_items = $this->getSessionNs()->items; } if (isset($this->getSessionNs()->shipping)) { $this->setShippingCost($this->getSessionNs()->shipping); } } public function CalculateTotals() { $sub = 0; foreach ($this as $item) { $sub = $sub + $item->getLineCost(); } $this->_subTotal = $sub; $this->_total = $this->_subTotal + (float) $this->_shipping; } public function setShippingCost($cost) { $this->_shipping = $cost; $this->CalculateTotals(); $this->persist(); } public function getShippingCost() { $this->CalculateTotals(); return $this->_shipping; } public function getSubTotal() { $this->CalculateTotals(); return $this->_subTotal; } public function getTotal() { $this->CalculateTotals(); return $this->_total; } /*...*/ } We can see that the Cart Model class is fairly weighty and in fact, we have not included the full class here. The reason we have slightly truncated the class is that we are implementing the SeekableIterator, Countable, and ArrayAccess interfaces. These interfaces are defined by PHP's SPL Library and we use them to provide a better way to interact with the cart data. For the complete code, copy the methods below getTotal() from the example files for this article. We will look at what each method does shortly in the Cart Model implementation section, but first, let's look at what functionality the SPL interfaces allow us to add. Cart Model interfaces The SeekableIterator interface allows us to access our cart data in these ways: // iterate over the cartforeach($cart as $item) {}// seek an item at a position$cart->seek(1);// standard iterator access$cart->rewind();$cart->next();$cart->current(); The Countable interface allows us to count the items in our cart: count($cart); The ArrayAccess interface allows us to access our cart like an array: $cart[0]; Obviously, the interfaces provide no concrete implementation for the functionality, so we have to provide it on our own. The methods not listed in the previous code listing are: offsetExists($key) offsetGet($key) offsetSet($key, $value) offsetUnset($key) current() key() next() rewind() valid() seek($index) count() We will not cover the actual implementation of these interfaces, as they are standard to PHP. However, you will need to copy all these methods from the example files to get the Cart Model working. Documentation for the SPL library can be found athttp://www.php.net/~helly/php/ext/spl/     Cart Model implementation Going back to our code listing, let's now look at how the Cart Model is implemented. Let's start by looking at the properties and methods of the class. The Cart Model has the following class properties: $_items:An array of cart items $_subTotal: Monetary total of cart items $_total: Monetary total of cart items plus shipping $_shipping: The shipping cost $_sessionNamespace: The session store The Cart Model has the following methods: init(): Called during construct and loads the session data addItem(Storefront_Resource_Product_Item_Interface $product, $qty): Adds or updates items in the cart removeItem($product): Removes a cart item setSessionNs(Zend_Session_Namespace $ns): Sets the session instance to use for storage getSessionNs(): Gets the current session instance persist(): Saves the cart data to the session loadSession(): Loads the stored session values calculateTotals(): Calculates the cart totals setShippingCost($cost): Sets the shipping cost getShippingCost(): Gets the shipping cost getSubTotal(): Gets the total cost for items in the cart (not including the shipping) getTotal(): Gets the subtotal plus the shipping cost When we instantiate a new Cart Model instance, the init() method is called. This is defined in the SF_Model_Abstract class and is called by the __construct() method. This enables us to easily extend the class's instantiation process without having to override the constructor. The init() method simply calls the loadSession() method. This method populates the model with the cart items and shipping information stored in the session. The Cart Model uses Zend_Session_Namespace to store this data, which provides an easy-to-use interface to the $_SESSION variable. If we look at the loadSession() method, we see that it tests whether the items and shipping properties are set in the session namespace. If they are, then we set these values on the Cart Model. To get the session namespace, we use the getSessionNs() method. This method checks if the $_sessionNs property is set and returns it. Otherwise it will lazy load a new Zend_Session_Namespace instance for us. When using Zend_Session_ Namespace, we must provide a string to its constructor that defines the name of the namespace to store our data in. This will then create a clean place to add variables to, without worrying about variable name clashes. For the Cart Model, the default namespace will be Storefront_Model_Cart. The Zend_Session_Namespace component provides a range of functionality that we can use to control the session. For example, we can set the expiration time as follows: $ns = new Zend_Session_Namespace('test');$ns->setExpirationSeconds(60, 'items');$ns->setExpirationHops(10);$ns->setExpirationSeconds(120); This code would set the item's property expiration to 60 seconds and the namespaces expiration to 10 hops (requests) or 120 seconds, whichever is reached first. The useful thing about this is that the expiration is not global. Therefore, we can have specialized expiration per session namespace. There is a full list of Zend_Session_Namespace functionalities in the reference manual. Testing with Zend_Session and Zend_Session_NamespaceTesting with the session components can be fairly diffi cult. For the Cart Model, we use the setSessionNs() method to allow us to inject a mock object for testing, which you can see in the Cart Model unit tests. There are plans to rewrite the session components to make testing easier in the future, so keep an eye out for those updates. To add an item to the cart, we use the addItem() method. This method accepts two parameters,$product and $qty. The $product parameter must be an instance of the Storefront_Resource_Product_Item class, and the $qty parameter must be an integer that defines the quantity that the customer wants to order. If the addItem() method receives a valid $qty, then it will create a new Storefront_Resource_Cart_Item and add it to the $_items array using the productId as the array key. We then call the persist() method. This method simply stores all the relevant cart data in the session namespace for us. You will notice that we are not using a Model Resource in the Cart Model and instead we are directly instantiating a Model Resource Item. This is because the Model Resources represent store items and the Cart Model is already doing this for us so it is not needed. To remove an item, we use the removeItem() method. This accepts a single parameter $product which can be either an integer or a Storefront_Resource_Product_Item instance. The matching cart item will be removed from the $_items array and the data will be saved to the session. Also, addItem() will call removeItem() if the quantity is set to zero. The other methods in the Cart Model are used to calculate the monetary totals for the cart and to set the shipping. We will not cover these in detail here as they are fairly simple mathematical calculations. Cart Model Resources Now that we have our Model created, let's create the Resource Interface and concrete Resource class for our Model to use. application/modules/storefront/models/resources/Cart/Item/Interface.php interface Storefront_Resource_Cart_Item_Interface { public function getLineCost(); } The Cart Resource Item has a very simple interface that has one method, getLineCost(). This method is used when calculating the cart totals in the Cart Model. application/modules/storefront/models/resources/Cart/Item.php class Storefront_Resource_Cart_Item implements Storefront_Resource_Cart_Item_Interface { public $productId; public $name; public $price; public $taxable; public $discountPercent; public $qty; public function __construct(Storefront_Resource_Product_Item_ Interface $product, $qty) { $this->productId = (int) $product->productId; $this->name = $product->name; $this->price = (float) $product->getPrice(false,false); $this->taxable = $product->taxable; $this->discountPercent = (int) $product->discountPercent; $this->qty = (int) $qty; } public function getLineCost() { $price = $this->price; if (0 !== $this->discountPercent) { $discounted = ($price*$this->discountPercent)/100; $price = round($price - $discounted, 2); } if ('Yes' === $this->taxable) { $taxService = new Storefront_Service_Taxation(); $price = $taxService->addTax($price); } return $price * $this->qty; } } The concrete Cart Resource Item has two methods __construct() and getLineCost(). The constructor accepts two parameters $product and $qty that must be a Storefront_Resource_Product_Item_Interface instance and integer respectively. This method will then simply copy the values from the product instance and store them in the matching public properties. We do this because we do not want to simply store the product instance because it has all the database connection data contained within. This object will be serialized and stored in the session. The getLineCost() method simply calculates the cost of the product adding tax and discounts and then multiplies it by the given quantity. Shipping Model We also need to create a Shipping Model so that the user can select what type of shipping they would like. This Model will simply act as a data store for some predefined shipping values. application/modules/storefront/models/Shipping.php class Storefront_Model_Shipping extends SF_Model_Abstract { protected $_shippingData = array( 'Standard' => 1.99, 'Special' => 5.99, ); public function getShippingOptions() { return $this->_shippingData; } } The shipping Model is very simple and only contains the shipping options and a single method to retrieve them. In a normal application, shipping would usually be stored in the database and most likely have its own set of business rules. For the Storefront, we are not creating a complete ordering process so we do not need these complications. Creating the Cart Controller With our Model and Model Resources created, we can now start wiring the application layer together. The Cart will have a single Controller, CartController that will be used to add, view, and update cart items stored in the Cart Model. application/modules/storefront/controllers/CartController.php class Storefront_CartController extends Zend_Controller_Action { protected $_cartModel; protected $_catalogModel; public function init() { $this->_cartModel = new Storefront_Model_Cart(); $this->_catalogModel = new Storefront_Model_Catalog(); } public function addAction() { $product = $this->_catalogModel->getProductById( $this->_getParam('productId') ); if(null === $product) { throw new SF_Exception('Product could not be added to cart as it does not exist' ); } $this->_cartModel->addItem( $product, $this->_getParam('qty') ); $return = rtrim( $this->getRequest()->getBaseUrl(), '/' ) . $this->_getParam('returnto'); $redirector = $this->getHelper('redirector'); return $redirector->gotoUrl($return); } public function viewAction() { $this->view->cartModel = $this->_cartModel; } public function updateAction() { foreach($this->_getParam('quantity') as $id => $value) { $product = $this->_catalogModel->getProductById($id); if (null !== $product) { $this->_cartModel->addItem($product, $value); } } $this->_cartModel->setShippingCost( $this->_getParam('shipping') ); return $this->_helper->redirector('view'); } } The Cart Controller has three actions that provide a way to: add: add cart items view: view the cart contents update: update cart items The addAction() first tries to find the product to be added to the cart. This is done by searching for the product by its productId field, which is passed either in the URL or by post using the Catalog Model. If the product is not found, then we throw an SF_Exception stating so. Next, we add the product to the cart using the addItem() method. When adding the product, we also pass in the qty. The qty can again be either in the URL or post. Once the product has been successfully added to the cart, we then need to redirect back to the page where the product was added. As we can have multiple locations, we send a returnto variable with the add request. This will contain the URL to redirect back to, once the item has been added to the cart. To stop people from being able to redirect away from the storefront, we prepend the baseurl to the redirect string. To perform the actual redirect, we use the redirector Action Helper's gotoUrl() method. This will create an HTTP redirect for us. The viewAction() simply assigns the Cart Model to the cartModel View property. Most of the cart viewing functionality has been pushed to the Cart View Helper and Forms, which we will create shortly. The updateAction() is used to update the Cart Items already stored in the cart. The first part of this updates the quantities. The quantities will be posted to the Action as an array in the quantity parameter. The array will contain the productId as the array key, and the quantity as the value. Therefore, we iterate over the array fi nding the product by its ID and adding it to the cart. The addItem() method will then update the quantity for us if the item exists and remove any with a zero quantity. Once we have updated the cart quantities, we set the shipping and redirect back to the viewAction. >> Continue Reading Creating a Shopping Cart using Zend Framework: Part 2
Read more
  • 0
  • 0
  • 5671

article-image-managing-student-work-using-moodle-part-2
Packt
27 Oct 2009
5 min read
Save for later

Managing Student Work using Moodle: Part 2

Packt
27 Oct 2009
5 min read
How Assignments Look to a Student I've logged out and then logged back in as student John Smith. As far as offline assignments are concerned, they are carried out in the real world. In that instance, Moodle is used to manage grades and notes. If I click on my Offline assignment, I just see a description of the assignment: My second assignment requires students to upload a file. In the next section, we experience a little of what life is like as a Moodle student when we try uploading a project submission to Moodle. Taking the Student's Point of View—Uploading a Project File It is a very good idea to see what we are expecting our students to do when we ask them to upload their project work to us online. At the very least, when we ask students to upload their project work to Moodle, we need to know what we are talking about in case they have any questions. If you don't have a student login or you are still logged in as yourself and have asked a colleague to check that your assignment is working correctly, it's a good idea to take a good look over their shoulder while they are running through the following steps. Together, let's run though what a student must do to upload a file to us... Time for Action – Uploading a File to an Assignment I only have one computer to work from, so the first thing to do is for me to log out and log back in as my pretend student "John Smith". If you have the luxury of having two computers next to each other then you can log in as yourself on one and your pretend student on the other at the same time. You might have two different browsers (e.g. Firefox and Internet Explorer) installed on the same computer. If so you can log into one as a teacher and the other as a student. Don't try to log in as two different people on the same computer using the same browser—it doesn't work. Now that you are logged in as a student... Return to the course main page and click on the Advanced uploading of files assignment you added earlier. You will be presented with the following page: The top half of the page is our description of the assignment. The second half allows us to upload a file and, because I configured the activity such that students could include comments with their submission, has an area allowing us to add a note. Students can browse for files and upload them in exactly the same way as we upload our teaching materials to the course files area. If they want to add a note, then they need to press on the Edit button (at the bottom of the previous screenshot). Click on the Browse... button now. The File upload dialog is displayed. This allows us to select a file to upload. You can choose any for now, just to prove the point. I've quickly created a text file using Notepad called example_submission.txt. Select the file you want to upload and press the Open button. The name of the file is now displayed in the box: Press the Upload this file button. You will now see the file listed in the Submission draft box: Repeat this process for your other project files. To add a note to go along with the submission, I can press the Edit button at the bottom of the page. Try leaving a note now. (If your assignment has been configured so that students are prevented from leaving a note, you won't have this option.) If I am happy that this is the final version of the project and I want to send it for marking, then I can press the Send for marking button at the bottom of the page. Pressing this stops me from uploading any more files: That's it. We're done: What Just Happened? It was easy for us to convert our assignments to Moodle. Now, we've seen how easy it is for students to convert to using Moodle to hand in their assignment submissions. Now, we've actually got a piece of work to mark (albeit a pretend piece), I am ready to start marking. Before moving on to the next section, make sure you are logged in as yourself rather than as a student. Marking Assignments Managing student grades and the paperwork associated with student submissions is one of my biggest headaches. By converting to Moodle, I can avoid all of these problems. Let's see how easy it is to mark assignments in Moodle. Marking Offline Assignments My Offline assignment, the poster project, is being carried out in the real world. Currently, I take a digital photograph of the poster and record my comments and grades on separate pieces of paper. Let's see how I can convert this to Moodle... Time for Action – Mark an Offline Assignment From the course front page, click on your Offline assignment. Click on the No attempts have been made on this assignment/View 0 submitted assignments link in the top right-hand corner of the page. You are now taken to the Submissions page. I've only got one student enrolled on my course—the pretend student my admin put on my course for me—so this is what I see: To grade John Smith's work, I need to click on the Grade link, found in the Status column. The Feedback dialog is displayed: I can use this dialog to comment on a student's work. At this point, I could include a photograph of the poster in the comment, if I wanted to (or I could get the students to take photographs of their posters and then to upload the images as part of an online submission).
Read more
  • 0
  • 0
  • 1611
article-image-real-content-php5-cms-part-1
Packt
27 Oct 2009
14 min read
Save for later

Real Content in PHP5 CMS: Part 1

Packt
27 Oct 2009
14 min read
The problem There are some common features in providing website content, but also many differences. Applications easily become complex as they tackle real world problems, and there has been much real innovation in web systems. So the areas to look at in this article are: Major areas for content development A review of minor yet important areas How a simple text manager is built An outline of a complex content delivery extension Discussion and considerations Now, we will work through the major areas of website content, devoting a section to each one. A round up of some less important aspects of content completes the discussion, leaving us ready to move on to details of implementation. Articles, blogs, magazines, and FAQ The most basic requirement is for text and pictures, and the simplest scheme needs little more than the standard database and a WYSIWYG editor. An extension that works at this level is illustrated later in the article. It is pretty much essential to have an ability to create items of this kind in an unpublished state so that they can be revised until ready for use. The state is then changed to published. Almost immediately, a further requirement arises to specify a range of publication dates, so that material aimed at a specific event can be automatically published at the appropriate time. Likewise, it is desirable to have an automatic mechanism for removing information that is no longer current, for example because it refers to a coming event in terms that will be irrelevant once the event has passed. A website that carries plainly obsolete articles is unlikely to be popular! There are many ways to organize textual material. One is to place it into some kind of tree structure, rather akin to the classification schemes used in libraries. Ideally, such a scheme has no particular constraints on the depth of the tree structure. A concern with this approach is that it can quickly lead to a conflict between two alternative uses—classification according to subject and classification according to reader permissions. An option that can be used in conjunction with a tree structure is to use some form of tagging. This introduces much greater flexibility in some respects, as it is easy to apply multiple tags to a single item of content, which can therefore be classified in a wide variety of ways, and can appear under multiple headings. A blog is an example of a system that might work best with a combination of a classification tree and a tagging scheme. Where there are several people creating blogs, the different authors fit well with a tree structure, since there is no question of an item belonging to more than one author. On the other hand, items are often tagged according to their subject matter, and several tags may be applicable to an individual article. If authors create more than one blog and there are questions about which visitors are able to see which blog, then careful thought needs to be given as to whether the split of blogs is best handled by the classification tree or by tagging. Using a tree achieves rigid separation, and is easily amenable to imposing access controls. But if the same item appears in more than one blog, then tagging works better as the item is ideally stored only once but has multiple tags. Blogs also frequently provide for comments, discussed in the next section. A magazine is typically a collection of articles. For a simple case, it might be adequate for the articles of the magazine to be equated to website pages, but a more sophisticated magazine would want to avoid restrictions of that kind. The basic unit of content would still need to be an individual article, but website pages then require some kind of template to build a page from multiple items. One popular application for quite simple content is the compilation of frequently asked questions (FAQ's). Advanced implementations might be described more grandly as knowledge bases. Again, both a classification tree and tagging can be relevant, but a useful FAQ (and especially one that wants to be a knowledge base) also needs effective search facilities so that information can be easily found. In all of these cases, added complexity arises if facilities like versioning are needed. Another similar issue is the need for workflow and differing roles, such as authors and editors. Mention of roles suggests a RBAC mechanism. It seems unlikely that one single model will ever meet every requirement in areas such as versioning and workflow. Version control can become extremely complex, and usually requires the allocation of roles that involve access rights and functional capabilities. Workflow is much the same. In both cases, though, simple and rigid schemes are liable to create problems. For example, the same person is quite likely to be an author in some situations, and an editor or publisher in others. A flexible and an efficient RBAC system is a pre-requisite for handling these problems, but as discussed earlier, the technical provision of RBAC is only a start. Applying it to particular systems and creating an appropriate user interface is a considerable challenge. Comments and reviews One of the successful innovations brought about by widespread use of the Web has been feedback through comments and reviews. Amazon is only one of many sites that now include reviews by customers of the products on sale. It could be said that this is a form of social networking, as the more sophisticated sites maintain profiles of reviewers and encourage them to achieve their own identity. Regular readers in particular areas of interest can get to know reviewers and form an opinion on the reliability of their views. There are two main problems with implementing comments and reviews. One is the question of how to generalize the facility, so as to avoid implementing it repeatedly in different applications. The other is how to deal with the ever present threat of spam. From the point of view of a developer, handling comments raises much the same issues regardless of what may be the subject of the comments. So blogs, selections of products, image galleries, and so on are all capable of having comments added to their items using similar mechanisms. This suggests a structure something like the scheme where the coarse grained structure is the component, but its display is achieved through the use of a template and a number of modules. Comments can thus be generated by a module that knows relatively little about the application, only enough to keep its comments separate from those for other applications and to relate a set of comments to a particular item, whether it is a blog item, product, gallery image, or whatever. That deals with the display of existing comments, which still leaves a requirement for a general interface that allows new comments to be added. The comment facility can easily enough handle the acceptance of a new comment, although it may need help if the page that accepts comments is to also show the object to which the comment applies. The comment facility also needs to know where to hand control once a new comment has been completed. Some moderately tricky detailed design is involved in providing an implementation of the full scheme. The other big problem with any facility that permits visitors to a site to enter information for display is that it attracts spammers. Usually, they arrive not in person but in the form of automated bots that can become very sophisticated. There are bots that know how to obtain an account, and log in to a range of systems. There are even bots that can handle CAPTCHAs (those messed up images out of which you are supposed to decipher letters or numbers). Some of the bots can handle CAPTCHAs better than some humans, which makes for accessibility problems. Fortunately, much link spamming is for the purpose of promoting websites, and so the spammer has to give away some information in the form of the link to the site being promoted. A reasonably effective defense against this kind of spamming is a collaborative scheme for blacklisting sites. Even that is not totally effective, as spammers find ways to create new sites quickly and cheaply, so that the threat is constantly changing. As with most forms of attack, there is unlikely to be any conclusion to this battle. Forums Forums are a very popular Web feature, providing a structured means for public or private discussion. Developing a forum is a major undertaking, and most people will prefer to choose from existing software products. Forum software usually provides for visitors to contribute messages, either starting a new topic or replying to an existing one. There is often a hierarchical structure to the messages so that a number of different areas of interest can be covered in a convenient way. Advanced systems include sophisticated user management, including support for a variety of different groups, which provides a means to decide who has access to which topics. Unwanted messages are a constant threat, and most active forums need moderators to weed them out. Development of a new forum will clearly need a number of the framework features discussed earlier. Robust user control is essential, and if different users are granted different access rights, a good system of RBAC is a requirement. A forum is highly amenable to the use of cache, since pages are likely to be constructed out of a number of database records, but the records are updated relatively infrequently. To be responsive, the cache needs to have a degree of intelligence so that pages with new contributions are refreshed quickly. Mail services are likely to be employed so that subscribers can receive notification of new contributions to topics in which they have registered an interest. Another approach is to seek a degree of integration between off the shelf forum software and the CMS. The most popular area for integration is user login. Obviously it is necessary to obtain some information about the way in which the forum software is implemented. Provided that can be found, then it is a relatively simple matter to integrate with a CMS that has been built with plentiful plug in triggers around the area of user authentication. From the point of view of visual integration, the amount of screen space needed by a forum is such that it is often difficult to build it within the framework of a typical CMS. Often a better approach is to build a custom theme for the forum that includes links back to the main site, so as to avoid completely losing continuity of navigation. Galleries, repositories, and streaming Although they have come from different requirements, galleries, and file repositories have a lot in common. Both start out simple and rapidly become complex. The general idea of a gallery is to build a collection of images, typically organized into categories and accessible via small versions of the images (thumbnails). File repositories have long been popular since the days of bulletin boards, where collections of files (often programs) were made available for download. Ideally the organization into categories (or folders or containers) is flexible with no particular limit on the depth to which subcategories can go. Some basic requirements relate to security. It is obviously essential to avoid hosting files that could contain malicious PHP code. This includes avoiding uploads of image files that contain PHP code embedded within actual image data. Simple checks can be fooled by this technique, but a block on the .php extension prevents the code being interpreted. Another potentially major security issue is bandwidth theft. If files or images are too easily accessed, then other sites may choose to use them without acknowledgment, transferring the bandwidth costs to the site hosting the material. As applications broaden, access control becomes an issue. Files are to be made available only to a restricted group, and uploads may be restricted more tightly again. There may be administrator oversight, with uploads needing approval. Once again, we are seeing a demand for an effective access control system, preferably role-based. In fact demands on systems of this kind can easily become very sophisticated, such as allowing users to have personal upload areas over which they have complete control to determine who is able to gain access. An RBAC system that is technically capable of handling this can be built relatively easily, although creating a good user interface is a challenge. Whether the system is a gallery or file repository, the use of thumbnail images is increasingly prevalent. File uploads may, therefore, be accompanied by one or more image files that are used to enhance the display of the files available. Information about the system is likely to be needed, such as which are the most recent additions to the collection, which items are most popular, who has accessed what, and who has uploaded what. Information of this kind can also contribute to security by providing an audit trail of what has been happening to the system. Streaming of files is a demand now often placed on a file repository, as the files can be audio or video files made available for immediate access. Streaming is simply a mode of file processing whereby the information is delivered to the user at a speed adequate for consumption in real time. Clearly video tends to place greater demands on the system than audio. The problems are both hardware and software related, although with steadily improving technology it is increasingly feasible to overcome both. E-commerce and payments Everyone is aware of the huge growth of commercial transactions on the Web. The kind of transaction involved can vary widely across simple fixed price retail sales, auctions of various kinds, and reverse auctions for procurement. For retail transactions immediate settlement is usually required, whereas larger scale business to business transactions are usually handled through relatively traditional invoicing methods. Even those are tending to be altered towards paperless billing and payment schemes that cut transaction costs to a minimum. Systems for e-commerce vary enormously in their sophistication from simple requests for payment using a PayPal button to highly sophisticated Web operations such as Amazon and eBay. Open source PHP software exists to cover a significant part of this spectrum, some of it in the form of extensions to CMS frameworks. PayPal has achieved a very high profile, especially with smaller operators, by offering easy access for merchants combined with technology that is relatively simple to implement. This includes the ability to complete a transaction with online confirmation in a way that is suitable for the sale of electronically deliverable goods such as software. Clearly, robust authentication of users is essential for e-commerce. For all but the simplest transactions, some kind of shopping cart is highly desirable. These requirements imply a need for good session handling, preferably taking effect as soon as a visitor arrives at a site. Nearly every shopping site will allow a visitor to accumulate items in a shopping cart prior to any kind of login. There is a plethora of payment systems, some of them suitable mainly for large volume uses, but others that can be applied on a small scale. A particular CMS framework might adopt some standard payment mechanisms that are then integral to the CMS and can be used whenever needed. Security is obviously paramount, as loss of data is both financially damaging and extremely bad for the site's reputation. E-commerce sites also often use a number of the features described in other sections here. A popular addition is the ability for customers to review the items they have purchased. This kind of facility may lead to further requirements to distinguish categories of users so as to give incentives to people who regularly write reviews.
Read more
  • 0
  • 0
  • 1689

article-image-adding-pages-image-gallery-and-plugins-wordpress-blog
Packt
27 Oct 2009
10 min read
Save for later

Adding Pages, Image Gallery, and Plugins to a WordPress Blog

Packt
27 Oct 2009
10 min read
Pages At first glance, pages look very similar to posts. They also have a title and a content area in which we can write extended text. However, pages are handled quite differently from posts. Pages don't have a timestamp, categories, or tags. Posts belong to your blog, which is meant to be a part of an ongoing expanding section of your website, and are added regularly. Pages are more static, and the regular parts of your site that stand alone in a separate part of the site. When you installed WordPress, a page was automatically created for you (along with the first post and first comment). You can see it by clicking on the About link under Pages in the sidebar: Adding a page To add a new page, go to your WP Admin and navigate to Pages | Add New, or use the drop-down menu in the top grey menu by clicking on the arrow next to New Post and choosing New Page. This will take you to the Add New Page page: The minimum you need to do to create a new page is type in a title and some content. Then click on the blue Publish button, just as you would for a post, and your new page will appear linked in the sidebar of your website. You'll recognize most of the fields on this page from the Add New Post page, and they work the same for pages as they do for posts. Let's talk about the one new section, the box called Attributes Parent WordPress allows you to structure your pages hierarchically. This way, you can organize your website's pages into main pages and subpages, which is useful if you're going to have a lot of pages on your site. For example, if I was writing this blog along with three other authors, we would each have one page about us on the site, but they'd be subpages of the main About page. If I was adding one of these pages, I'd choose About as the parent page for this new page. Template Theme designers often offer alternate templates that can be used for special pages. The default WordPress theme comes with two templates: Archives and Links. Let's try using the Archives template. Just give your new page a title (for example, Blog Archives) and some content (for example, Let's experiment with the archives template). Then choose Archives from the Template pull-down menu and publish your page. When you go to your site and click on the Blog Archives link in the sidebar, you'll see this: As you can see, your title and content both do not appear, which makes this different from pages that use the default template (such as the About page). The sidebar is also missing. What does appear are the search box, a list of blog archives organized by month, and a list of archives organized by subject, that is, Categories. This particular template doesn't appear useful because all of its information is currently in the sidebar of the rest of the site. However, this shows you the power of a template. If you're designing a theme for your own website, you can create any number of templates that have special content. The Links template creates a similar page, but it lists all of your links. Order By default, the pages in your page list on the sidebar of your blog will be in alphabetical order. If you want them in some other order, you can specify it by entering numbers in the Order box for all of your pages. Pages with lower numbers (0) will be listed before pages with higher numbers (5). As the WordPress developers acknowledge right on this page, this method of ordering pages is quite clunky. Luckily, there is a plugin that makes ordering pages much easier. You can download this from http://wordpress.org/extend/plugins/pagemash/. Managing pages  To see a list of all the pages on your website in the WP Admin, navigate to Pages | Edit in the main menu. You'll see the Edit Pages page: By now this list format should begin to look familiar to you. You've got your list of pages, and in each row are a number of useful links allowing you to Edit, Quick Edit, Delete, or View the page. You can click on an author's name to filter the list by that author. You can use the two links at the top, All and Published, to filter the pages by status. And you can check boxes and mass-edit pages by using the Bulk Actions menu at the top and bottom of the list. You can also search your pages with the search box at the top. Links Word Press gives you a very powerful way of organizing external links or bookmarks on your site. This is a way to link other related blogs—websites you like, websites that you think your visitors will find useful, or just any category of link you want—to your blog. Speaking of categories, you can create and manage link categories that are separate from your blog categories. When you installed WordPress, it created the link category Blogroll along with a number of links in that category. You can see them in your blog's sidebar as follows: Adding a new link Let's add a new link to the Blogroll category. In your WP Admin, navigate to Links | Add New. This will take you to the Add New Link page, which has a number of boxes in which you can add information about your new link. Let's look at the first three here: Of all the fields on this page, it's the top two that are the most important. You need to give your link a Name, which is the text people will see and can click on. You also need to give a Web Address, which is the URL of the website that is linked to your blog. You can add a description, which will show up when visitors hover over the link. (Alternatively, you can also choose to have the description show up on the page below the link.) Now let's look at the next two boxes in the following screenshot: The first box in the screenshot above should look familiar because it's very similar to the Categories selection box for posts. Keep in mind that link categories are separate from post categories. On this page, you will only see link categories. You can assign a category to the new link that you're adding or create a brand new category by clicking on the + Add New Category link. Your links will be organized by the categories on your website. The second box lets you choose whether your visitors will be taken to a new window, or a new tab, when they click on the link. I generally recommend always using _blank when sending people to an external website. The other boxes on this page are used less commonly. You can use the two new boxes to specify XFN (XHTML Friends Network) relationships between you and any individuals you link to. Learning moreIf you want to learn more about XFN, take a look at this website: http://gmpg.org/xfn/. The final box at the bottom of this page will allow you to specify: An image that belongs with this link (for example, the logo of the company whose site you are linking to) The RSS feed for the website you're linking to Any notes you have about the site, beyond what you entered into the Description box A rating for the site from 0 to 9 To make use of any of these pieces of information, you need to have a theme that recognizes and makes use of them. At the top right of the page is a Save box with a checkbox that you can check if you want to keep the link private, that is, if you don't want it to show up on your site to anyone but you. Click on the Add Link button in that box to save your new link. I added a link for a recipe and food website using this form. I filled in only the first three boxes as seen in this screenshot: Now when I save and then re-load my website, I see my new link here: Managing links and categories You can manage your links just as you manage posts and pages. Navigate to Links and you will see this: From here, you can click on the name of a link to edit it, click on the URL to visit it, and see which categories you've chosen for it. Using the View all Categories pull-down menu, you can filter links by categories, change the order, and do bulk deletes. Just as with post categories, you can manage and add new link categories on the Link Categories page. You can access this page by navigating to Links | Link Categories: From this page, you can both add a new category using the form at the left and also manage your existing categories using the table at the right. Media library The media library is where WordPress stores all of your uploaded files—images, PDFs, music, video, and so on. To see your media library, navigate to Media in the main menu: This is the now-familiar management table. My media library has only one photo that I uploaded when I posted about the butternut squash soup recipe. As you can see from this table, it shows me the following: A thumbnail of the image. If this were another type of media, I'd see an icon representing the type of media. The title that I gave the file when I uploaded it, along with the format extension. The author. Information about which post or page the file is attached to. This will be important when it comes to making an image gallery. The uploaded file will be attached to the post or page that you are editing while uploading a file. The number of comments waiting on the attached post or page. The date when the file was uploaded. If you hover over the row with your mouse, links for Edit, Delete, and View will appear. You can click on the file's title or the Edit link to edit the Title, Caption, and Description. You cannot edit anything else about uploaded files. You can also add a new file to your media library. Navigate to Media | Add New to get a page similar to the upload media page that you got while uploading a file for a post. When you click on the Select Files button and select the file to be uploaded, it will upload it and then give you the options shown in this screenshot: Enter a title, caption, and description if you want, and click on the Save all changes button. Your new item will appear in the media library, which will be unattached to any post or page. However, you'll still be able to use what you just uploaded in any post or page. To do that, click on the Upload/Insert button as you did before. But instead of choosing a file From Computer, click on the Media Library tab on the top of the box: When you click on the Show link that is next to the image you want to use, you'll get the same set of options you got after uploading an image. Now you can click on the Insert into Post button.
Read more
  • 0
  • 0
  • 4334

article-image-understanding-model-development-process-ibm-cognos-8
Packt
27 Oct 2009
23 min read
Save for later

Understanding the Model Development Process in IBM Cognos 8

Packt
27 Oct 2009
23 min read
The process The Model Development Process is a proven step-by-step approach for designing and deploying planning models in an organization. This process enables us to chart various activities involved in identifying the organization's planning requirements in order to devise functional and efficient modeling solutions. The following diagram illustrates the Model Development Process and shows the typical stakeholders and IBM Cognos tools involved in the process: In the previous diagram, we saw four typical roles in organizations that are currently using the IBM Cognos Planning model and applications. They are described briefly as: Analyst Modeler: Responsible for gathering business requirements—designing, building, and testing Analyst models, and managing the data workflow within the model. System or Contributor Administrator: Responsible for creating, maintaining, and securing Contributor applications translated from Analyst models. Business Users: Responsible for entering, submitting, and reviewing planning data. Users will be referred to as the Business Users or Planners. Support Team: Responsible for maintaining models and applications, during or after the initial roll-out. Considerations for building an Analyst planning model When purchasing a vehicle, you may consider many attributes before finalizing your decision. For example, you may determine the type of vehicle to buy (sedan, minivan, and so on) or may evaluate the commuting needs. Likewise, before beginning to build the planning model, you must consider some key factors about our planning processes. To build and deploy the correct planning models in an organization, Project Managers, Business Users, Modelers, and other project stakeholders should consider the following factors at the initial stage of the planning project: Planning functional models Planning cycles and horizons Planning approaches Planning functional models Every business organization uses a variety of planning models to produce its business plans. A number of planning models are common in most of the organizations. For example, many business organizations have some form of revenue, cost of sales, payroll, capital, and operating expense models. On the other hand, some models are unique to a particular industry and trade. For example, a pharmaceutical company may have a Clinical trial or R&D model, or an international shipping company may need an aircraft fleet cost-control model. Other models may reflect an organization's business focus. The organization may develop a model to project and control a particular cost that is critical to its business strategy. For instance, a beverage company that places a heavy emphasis on brand recognition may have a separate marketing model, or a consulting company that routinely rotates its employees to offices around the world may have a separate travel model. Whatever purpose the models serve, it is important that you understand the rationale underlying the organization's use of them, so that you can build models that are more closely aligned to the organization's business needs. Planning cycles and horizons You also need to be aware of the organization's planning cycle and horizon. The planning cycle refers to the frequency by which an organization develops or updates its business plans. The planning horizon refers to how far into the future the organization plans. An organization may have multiple planning cycles, but may only plan for a single time horizon. The frequency with which an organization plans depends on many factors. For instance, organizations that operate in highly dynamic and competitive environments, such as technology companies, tend to have more frequent planning cycles. Companies in more stable environments, such as an alkaline batteries manufacturing company, tend to have less frequent cycles. Planning horizons may be driven by the organization's strategic focus or the nature of the business. For instance, the planning horizon of a pharmaceutical company's R&D plan may span up to 20 years, which is the amount of time that a clinical drug may take to get from inception to testing and eventually to marketability. A construction company may require multi-year plans to coincide with the time it takes to construct a building. More commonly, organizations develop a plan once a year in the form of an annual budget. The organization then revisits and calibrates the plan mid-year, after several months of actual data has been gathered. Actual data is used to measure year-to-date performance against the plan, so that the organization can forecast for the remainder of the year. The typical planning horizon is twelve months, usually the organization's fiscal year. If a long-range plan exists, the long-range plan is updated with changes to the annual plan or forecast. Planning cycle refers to the frequency at which an organization develops or updates its business plans. Planning horizon refers to how far into the future the organization plans. Knowing an organization's planning cycle and horizon is important when building a model. Many organizations use cycle-specific models because the business assumptions and calculations tend to differ between planning cycles. For instance, an organization can have a P&L model for the annual budget and another for the mid-year forecast because an annual budget and mid-year forecast usually require different data and calculation requirements. Knowing an organization's planning cycle can give you an insight into how you may want to build your models. The organization may start with detailed plans once or twice a year. If rolling forecasts are prepared, the forecasts may be done at a higher level, for instance, at an account or organizational summary level. This means that you may have to create a detailed model and a summary model. Knowing the planning horizon enables you to construct the appropriate timescale that can be used by other models. An organization that plans its revenue every quarter may also plan its expenses in the same way. An efficient planning model is built on standard data structures, such as timescale. Thus, timescales are an important consideration because they can be shared across several of the organization's planning models. Planning approaches Business organizations can use different approaches to plan their budgets and forecasts. You need to consider these approaches when building the model, as these approaches dictate how the model will be designed and deployed. Examples of common approaches are as follows: Zero-based budgeting: Each planner prepares estimates of their proposed revenue or expenses for a specific period of time as if they were planning for the first time. By starting from scratch at each budget cycle, for example, managers are required to take a closer look at all of their revenues and expenses. Driver based: Driver based planning models typically calculate plan numbers by adding, subtracting, or multiplying various drivers or metrics. Examples of drivers: number of units sold, price of a product, and so on. Top-down: Top Upper-level management sets the targets and pushes them to lower management who then pushes them further down the organization. Then the plans for achieving the targets are submitted up the chain of command for review and approval. Bottom-up: Lower-level management prepares the plans and then submits them up the chain of command for review and approval. The approval and rejection process follows until the plan and finalized. Designing the model template in Analyst A planning model is a set of Analyst objects whose purpose is to generate specific plans using a variety of data inputs, assumptions, and calculations.  In practice, a model is named after the output it produces. An output can be a specific budget for product lines or it can be a category of expenses consisting of several general ledger accounts, such as payroll. Once you have identified the model output, break it down into its inputs, assumptions, and calculations. For example, a salary plan may be the outcome of the inputs of employees and positions, their current salary, earned merit increases, and bonuses. The salary for newly-hired staff may be assumed based on their position. To produce the salary plan, the model would calculate the merit increases and bonuses for each employee by multiplying the salary by the merit and bonus percentages and then by adding the results to the salary. Then it would pull the appropriate salary for each new hire depending on position. Finally, the model would aggregate all of the employees' and new hires' salaries to come up with the salary plan. In this simplified example, four model functions are apparent: inputs, assumptions, calculations, and outputs. In fact, you can say that a model is a collection of these four functions. The IBM Cognos Planning Analyst tool allows you to build objects that collect inputs from users, designate assumed values, and perform calculations on them in order to produce the expected output. Flowcharting the model structure Before building an effective planning model, it is important to develop a detailed flowchart that logically illustrates all of the model's structural components. Just as an architect develops a building's blueprints before even breaking the ground, you must begin with the model's blueprints. Often, many modelers skip this important step and begin constructing the objects, without a clear path to the final outcome. Unfortunately, such haste results in a disorganized and inefficient model. A poorly-designed model can adversely impact an application's performance and cause a downstream effect on user productivity. The consequence can be severe. When the model is deployed to hundreds or thousands of users, a single instance of inefficiency will multiply at an equivalent scale. Flowcharting helps you to avoid these problems. It gives you a glimpse of the final product and forces you to think through the various factors and issues that must be addressed before starting to build the model. A disciplined and methodical approach can steer you away from many of model building's hidden pitfalls. Indeed, a well thought out flowchart can cut the build time significantly by minimizing rework and trial and error. Flowcharting can lead you to uncovering the important design elements, such as the dimensions, datastore, and data flow. A good flowchart should show the sources of data inputs, and whether they are entered by the planner or originate from other data sources such as an ERP system or a general ledger system. The flowchart should also illustrate the way that data will be stored and used, how it enters the model, and how it flows from source to target. Finally, the flowchart should describe the different ways in which data can be viewed so that you can gather the various dimensions that need to be included in the model. For instance, data can be viewed by cost center, departments, or profit centers. Alternatively, it can be viewed across time (days, weeks, months, years) or by versions (this year, last year, plan, scenarios). Some developers may refer to model flowcharts as model schematics or Data Flow Diagrams (DFD). You, the Modeler, typically initiate this design step in the model development process after learning and understanding the key business planning requirements. You then 'white-board' the design of the model template, and then document the design specification in a document called a Detailed Design Specification (DDS). Finally, you take the design specification and implement it in IBM Cognos Planning Analyst using the Analyst's features and functionality. The concept of multi dimensionality IBM Cognos Planning is based on a multi-dimensional data structure in which data is organized around specific attributes, or dimensions. In the following table, data is organized around Account, Year, Version, Cost Center, and Month. Each record in the table contains data by account, year, version, cost center, and month. One of the most common ways of presenting multi-dimensional data is in the form of a cube. In a multi-dimensional cube, data is displayed as one slice at a time along two or more dimensions. Each slice represents a subset of the population. Those familiar with Excel pivot tables should have little problem grasping this concept. However, those who are only familiar with spreadsheets can still find some similarities. In a spreadsheet, the rows and columns are actually two separate dimensions. A third dimension, the worksheet, gives you a three-dimensional view of data. If you enter data into the first cell in a spreadsheet, you are actually entering the data along three dimensions—Sheet 1, Column A, and Row 1. Hence, when you reference that cell, Excel denotes it as      Sheet1!A1. A multi-dimensional cube lets you view data the same way. But a cube can have several dimensions. Each dimension contains a list of related data such as accounts, version, cost center, or time period. When two or more dimensions intersect, the intersection represents a record or view of the data. For instance, a cost center dimension may list all the cost centers in the organization. A second dimension lists a group of expense accounts, a third lists 12 months, and a fourth lists the version (Plan or Actual). The intersection of these dimensions gives you data by cost center, by account, by month, and by version. The following Excel pivot table is an example of a multi-dimensional cube. Here you see a slice of the cube with the following dimensions: Account, Cost Center, Month, and Version. In a multi-dimensional cube, you can arrange data in a variety of ways by swapping rows, columns, and pages. This is a powerful feature that facilitates in-depth data analysis. Those who have worked with multi-dimensional cubes understand their benefits. Multi-dimensional cubes can help you sift through masses of data to find valuable information. IBM Cognos Planning takes multi dimensionality a step further by leveraging its features to enforce rules and standards in order to make model maintenance easier. Analyst is the tool that lets you create the planning template that the users will use to enter their plans, while Contributor is the tool that lets you replicate the templates and deploy them to a number of users based on a defined hierarchy. The plans are stored in a central database, and users connect to it through the Web. In a spreadsheet environment, similarities exist. You have a master template that you can use to build the worksheets. The worksheets are stored in a central folder, within sub-folders that are organized according to a hierarchy. Users connect to the shared folder to access their worksheets.     Understanding dimensions, datastore, and data flow Analyst objects are the building blocks of the planning model. These objects enable you to define the data structure, store and calculate the data, and move data from source to targets. There are a host of objects in Analyst, each offering useful capabilities. However, the key objects are the D-List, D-Cube, and D-Link. These objects are indispensable to a model and thus deserve special attention. Determining dimensions: D-List The D-List is the basic building block of the model. In Analyst, dimensions are referred to as D-Lists. Each item in a D-List represents an attribute of the data. In a D-List, we decide what data to include in the model and how the data will behave. The data could be something that will be entered by the planner; it could be pre-populated, or it could be calculated. For example, to build a model of your personal expenses, you may have a list of expense categories (travel, food, and entertainment), you may want to track your spending over time (month, quarter, and year), and you may want to compare different versions of spending (actual and planned). Each of these lists of items could be a D-List. In the Spending Category D-List, you might include a Total that sums up Travel, Food, and Entertainment (see the following screenshot). In the Versions D-List, you may want a "Variance" between actual and planned values. There is virtually no restriction to the type of data that you can include. However there are certain principles to adhere to when creating D-Lists. The first step in constructing a model is to identify the dimensions that will be used. There are many sources of information that will give you an idea of the dimensions that you need. Data entry templates from the organization's existing planning systems or Excel spreadsheets can suggest many ways in which data is gathered. The spreadsheet can also reveal the calculations used. Performance reports can be used to determine what the model outputs will be. Often, simply inquiring about the business can be a good start. Consider that you're working on a project that requires you to design and build a revenue forecasting model for a Fortune 100 global consumer electronics retailer. One approach to determining the dimensions of this forecasting model is to ask the following questions: What does the company sell? The dimensions could contain a list of consumer electronics products, such as MP3 players and laptops, product categories such as audio and computers, or even brands. Who is the company selling to? The retailer's customer list could be a dimension. Where does the company operate? Dimensions may contain a list stores, states, cities, countries, global regions, or market segments. What is the forecasting timeline? The timeline dimensions may be weeks, months, quarters, or years. The words "D-List" and "dimension" are often used interchangeably. When used in the context of a cube, "dimension" is often more appropriate. Building the datastore: D-Cubes Whereas the D-List is where the data is defined, the D-Cube is where the data is stored. After you have decided what data will be included in the model, you determine how the data will be stored. The D-Cube is formed by two or more D-Lists. A typical planning model consists of several cubes. The cubes store a particular set of data and perform a specific function. For example, an Employee cube may store data about employees. A P&L cube may contain revenue and expense data. D-Cubes can be functionally classified as either an input cube that allows data entry, a calculation cube that processes data, or an output cube that displays the result. The Employee cube can be broken into an Employee Input cube (see the following example), Employee Calculation cube, and Employee Summary cube. The words "D-Cube" and "cube" are often used interchangeably. Except for the terminology, there is no distinction between the two. "D-Cubes" are usually used in an Analyst setting, but "cubes" can work as well. The key to building D-Cubes is to understand their primary function. Is the cube a place where planners will enter data? Will it be used simply to stage data? Will it be used to calculate inputs and feed the result somewhere else? Will it be used to present data in a report format for reviewers? These important questions must be answered before building the cube. Another factor to think about is data. Data is stored in a cube. Consequently, the cube structure needs to follow the format of the data source that will be feeding it. As a modeler, you need to understand what type of data will be going into the model. For instance, planners need data to compare and analyze planning and actual information. They would like to see actual year-to-date sales compared to next-year projections. During the initial design process, you may decide to work with the data provider to review the source data and develop a process to extract, load, and validate data in planning models. Perhaps the most important consideration is size. In a multi-dimensional data structure, size is always a constraint. Size has a direct impact on performance; the greater the size, the more time it will take to process data and transmit it over the web. In fact, performance can be such a tremendous constraint that it affects the way the model is designed. Controlling data flow: D-Links In a model that shares data among several cubes, data must flow from one cube to another. The D-link is an object that moves data. Similar to a data transformation or ETL tool, the D-Link maps dimension items in the source to dimension items in the target, enabling you to control the flow of data within the model. For multi-dimensional cubes where data sparseness can be a problem, the D-Link has a practical purpose. The D-Link allows you to break a large cube into smaller, specialized cubes while still making the same data available. Most models use function-specific cubes, where outputs from one cube are inputs to another. The D-Link connects input, calculation, and output cubes, bringing them together to allow the seamless movement of data. Any cube that requires data in order to perform its function can retrieve data without going outside of the model. Because data can be reused, it only needs to enter the model once, thereby simplifying the data import process. The D-Link's ability to transport data is not limited to cubes. D-links can import data from a database, an ASCII file, an Excel spreadsheet, or a Contributor application. The words "D-Link" and "link" are often used interchangeably. Except for the terminology, there is no distinction between the two. "D-Link" is usually used in the context of Analyst. What makes an optimal model? The saying goes: "There is more than one way to skin a cat." The same can be said about model building. There are myriad ways to create the same output by using a combination of inputs, assumptions, and calculations. IBM Cognos Planning allows you to create highly complex models using its advanced forecasting algorithms and scenario planning facilities. With this capability at your disposal, you may be tempted to build a model that "does everything at the push of the button". While such automation can appear impressive, it is often accompanied with many problems. Complex models make ownership and maintenance difficult. A highly-customized model can become so inflexible that when it's time to enhance it, starting from scratch is an easier option, rather than building on its current form. Support and maintenance can also become a nightmare when you need to go through a laundry list of tasks to prepare for the next cycle. The tendency towards over-automation and over-customization, must be tempered with caution. More often than not, the model that "does everything" also requires everything to support and maintain it. So what is an optimal model? The answer is one that delivers planning information in a timely manner at the lowest possible cost. Although delivering better information has always been at the forefront of every planning project, the cost of delivering it tends to be elusive. To be sure, the financial cost of the system is closely monitored, but there are costs hidden within the system's inner workings that cannot be quantified and are often left to persist. The cost can take many forms: What is the cost of a poorly designed model? What is the cost of a Contributor application taking twice as long to process? What is the cost of thousands of users waiting an extra 10 seconds each time they can download a planning model? These costs must be taken into consideration when building the model. You, as a Modeler, must not only build a model that does its job, you must do so without placing an undue burden on these cost factors. Principles of model building If you ask ten people what makes an optimal model, you are likely to get ten different answers. This is not surprising. The quest for the one-size-fits-all formula has been a long one, owing mostly to the differences in the ways that organizations plan, but also to the openness of the tool and the absence of a shared body of knowledge. Although there are no hard and fast rules, there are three guiding principles that can help lead you down the correct path. Efficiency Performance Maintenance Efficiency An optimal model must be built with an eye towards efficiency. An efficient model is one that takes the shortest path to performing its task. Usually this means fewer objects in the model. But it could mean other things: Data flows in one direction, D-Cubes perform clear and specific functions, calculations are more intuitive and easy to understand, D-Lists contain as few dimension items as possible, redundancies are non-existent, and data is organized in a logical fashion. Efficiency and simplicity go hand-in-hand. Simplicity eliminates clutter. It begs the question: Is this absolutely necessary? To a savvy Modeler, the concept of simplicity may be counter-intuitive and run contrary to his nature. Yet the ability to take complex processes and re-engineer them down to a few moving parts is indispensable to model building. Indeed, it is a higher skill, one that compels you to abandon conventional wisdom, think out of the box, and explore unfamiliar territories. Performance An optimal model is one that performs its task faster using the same resources. Performance combines effectiveness with timeliness. This means delivering the right information at the right time. The model must be able to process data and respond to user requests within reasonable time and without unnecessary delays. Although not everyone will agree on what "reasonable time" means, everyone can agree on what constitutes "unnecessary delays". It is the difference between how the model performs and how it should perform. A model that is built on a weak foundation almost always bears extra processing overhead that takes additional time. There are essentially three areas where performance is most visible: Application processing Web client access Web client processing Application processing refers to the server batch process that implements changes to the model, or loads data. Web client access is the point where users connect to the database to retrieve or save their plans. Web client processing is where users actually work with their planning templates, entering data and switching from cube to cube. All of these areas have a direct impact on user productivity, so that any lag in performance creates cost in some form. Maintenance An optimal model is one that requires the least amount of effort to set up and maintain. In a constantly-changing business landscape, organizations must be able to adapt to new environments quickly. Competitive pressures may push organizations to shorten their planning cycles or drive them to a new strategic direction. Planning models must reflect new realities in order to accurately project the future. They must therefore be flexible and easy to maintain. An optimal model is built on the premise that change is constant. The model must allow for its assumptions and calculations to change without a complete overhaul. It must use standards and share objects so that changes can cascade rapidly throughout its various parts. The model should enable a non-developer to easily take ownership of it without the need for advanced training. These principles can be self-reinforcing. For instance, an efficient model usually performs faster and is easier to maintain. However, they are not exclusive and trade-offs can occur. When two good approaches contradict, you must weigh the benefit of one over the other and accept the trade-off. In a way, modeling is an art. No strict rules govern how a model should be built, lending the entire exercise to one's own creativity. As a modeler, you should look to these principles for guidance, while keeping a close watch on other factors. In the final analysis, the planning system, like any other system, must be viewed in the light of its benefits, as well as its cost.  
Read more
  • 0
  • 0
  • 5771
article-image-aspnet-social-networks-blogs-fisharoo
Packt
27 Oct 2009
8 min read
Save for later

ASP.NET Social Networks—Blogs in Fisharoo

Packt
27 Oct 2009
8 min read
Problem This article, as stated in Introduction, is all about adding the Blogging feature to our site. This will handle creating and managing a post. It will also handle sending alerts to your friends' filter page. And finally we will handle creating a friendly URL for your blog posts. Here we are making our first post to our blog: Once our post is created, we will then see it on the Blogs homepage and the My Posts section. From here we can edit the post or delete it. Also, we can click into the post to view what we have seen so far. The following screenshot shows what one will see when he/she clicks on the post: I have the blog post set up to show the poster's avatar. This is a feature that you can easily add to or remove. Most of your users want to be able to see who the author is that they are currently reading! Also, we will add a friendly URL to our blog post's pages. Design The design of this application is actually quite simple. We will only need one table to hold our blog posts. After that we need to hook our blog system into our existing infrastructure. Blogs In order for us to store our blog, we will need one simple table. This table will handle all the standard attributes of a normal blog post to include the title, subject, page name, and the post itself. It has only one relationship out to the Accounts table so that we know who owns the post down the road. That's it! Solution Let's take a look at the solution for these set of features. Implementing the database Let's take a look at the tables required by our solution. Blogs The blogs table is super simple. We discussed most of this under the Blogs section. The one thing that is interesting here is the Post column. Notice that I have this set to a varchar(MAX) field. This may be too big for your community, so feel free to change it down the road. For my community I am not overly worried. I can always add a UI restriction down the road without impacting my database design using a validation control. After that we will look at the IsPublished flag. This flag tells the system whether or not to show the post in the public domain. Next to that we will also be interested in the PageName column. This column is what we will display in the browser's address bar. As it will be displayed in the address bar, we need to make sure that the input is clean so that we don't have parsing issues (responsible for causing data type exceptions) down the road. We will handle that on the input side in our presenter later. Creating the relationships Once all the tables are created, we can then create all the relationships. For this set of tables we have relationships between the following tables: Blogs and Accounts Setting up the data access layer To set up the data access layer follow the steps mentioned next: Open the Fisharoo.dbml file. Open up your Server Explorer window. Expand your Fisharoo connection. Expand your tables. If you don't see your new tables try hitting the Refresh icon or right-clicking on tables and clicking Refresh. Then drag your new tables onto the design surface. Hit Save and you should now have the following domain objects to work with! Keep in mind that we are not letting LINQ track our relationships, so go ahead and delete them from the design surface. Your design surface should have all the same items as you see in the screenshot (though perhaps in a different arrangement!). Building repositories With the addition of new tables will come the addition of new repositories so that we can get at the data stored in those tables. We will be creating the following repository to support our needs. BlogRepository Our repository will generally have a method for select by ID, select all by parent ID, save, and delete. We will start with a method that will allow us to get at a blog by its page name that we can capture from the browser's address bar. public Blog GetBlogByPageName(string PageName, Int32 AccountID){Blog result = new Blog();using(FisharooDataContext dc = _conn.GetContext()){result = dc.Blogs.Where(b => b.PageName == PageName &&b.AccountID == AccountID).FirstOrDefault();}return result;} Notice that for this system to work we can only have one blog with one unique page name. If we forced our entire community to use unique page names across the community, we would eventually have some upset users. We want to make sure to enforce unique page names across users only for this purpose. To do this, we require that an AccountID be passed in with the page name, which gives our users more flexibility with their page name overlaps! I will show you how we get the AccountID later. Other than that we are performing a simple lambda expression to select the appropriate blog out of the collection of blogs in the data context. Next, we will discuss a method to get all the latest blog posts via the GetLatestBlogs() method. This method will also get and attach the appropriate Account for each blog. Before we dive into this method, we will need to extend the Blog class to have an Account property. To extend the Blog class we will need to create a public partial class in the Domain folder. using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Fisharoo.FisharooCore.Core.Domain{ public partial class Blog { public Account Account { get; set; } }} Now we can look at the GetLatestBlogs() method. public List<Blog> GetLatestBlogs(){ List<Blog> result = new List<Blog>(); using(FisharooDataContext dc = _conn.GetContext()) { IEnumerable<Blog> blogs = (from b in dc.Blogs where b.IsPublished orderby b.UpdateDate descending select b).Take(30); IEnumerable<Account> accounts = dc.Accounts.Where(a => blogs.Select(b => b.AccountID).Distinct().Contains(a.AccountID)); foreach (Blog blog in blogs) { blog.Account = accounts.Where(a => a.AccountID == blog.AccountID).FirstOrDefault(); } result = blogs.ToList(); result.Reverse(); } return result;} The first expression in this method gets the top N blogs ordered by their UpdateDate in descending order. This gets us the newest entries. We then add a where clause looking for only blogs that are published. We then move to getting a list of Accounts that are associated with our previously selected blogs. We do this by selecting a list of AccountIDs from our blog list and then doing a Contains search against our Accounts table. This gives us a list of accounts that belong to all the blogs that we have in hand. With these two collections in hand we can iterate through our list of blogs and attach the appropriate Account to each blog. This gives us a full listing of blogs with accounts. As we discussed earlier, it is very important for us to make sure that we keep the page names unique on a per user basis. To do this we need to have a method that allows our UI to determine if a page name is unique or not. To do this we will have the CheckPageNameIsUnique() method. public bool CheckPageNameIsUnique(Blog blog){ blog = CleanPageName(blog); bool result = true; using(FisharooDataContext dc = _conn.GetContext()) { int count = dc.Blogs.Where(b => b.PageName == blog.PageName && b.AccountID == blog.AccountID).Count(); if(count > 0) result = false; } return result;} This method looks at all the blog entries except itself to determine if there are other blog posts with the same page name that are also by the same Account. This allows us to effectively lock down our users from creating duplicate page names. This will be important down the road when we start to discuss our pretty URLs. Next, we will look at a private method that will help us clean up these page name inputs. Keep in mind that these page names will be displayed in the browser's address bar and therefore need not have any characters in them that the browser would want to encode. While we can decode the URL easily, this conversation is more about keeping the URL pretty so that the user and search engine spiders can easily read where they are at. When we have characters in the URL that are encoded, we will end up with something like %20 where %20 is the equivalent to a space. But to read my%20blog%20post is not that easy. It is much easier to ready my-blog-post. So we will strip out all of our so called special characters and replace all spaces with hyphens. This method will be the CleanPageName() method. private Blog CleanPageName(Blog blog){ blog.PageName = blog.PageName.Replace(" ", "-").Replace("!", "") .Replace("&", "").Replace("?", "").Replace(",", ""); return blog;} You can add to this as many filters as you like. For the time being I am replacing the handful of special characters that we have just seen in the code. Next, we will get into the service layers that we will use to handle our interactions with the system.
Read more
  • 0
  • 0
  • 4476

article-image-overview-cherrypy-web-application-server-part2
Packt
27 Oct 2009
5 min read
Save for later

Overview of CherryPy - A Web Application Server (Part2)

Packt
27 Oct 2009
5 min read
Library CherryPy comes with a set of modules covering common tasks when building a web application such as session management, static resource service, encoding handling, or basic caching. The Autoreload Feature CherryPy is a long-running Python process, meaning that if we modify a Python module of the application, it will not be propagated in the existing process. Since stopping and restarting the server manually can be a tedious task, the CherryPy team has included an autoreload module that restarts the process as soon as it detects a modification to a Python module imported by the application. This feature is handled via configuration settings. If you need the autoreload module to be enabled while in production you will set it up as below. Note the engine.autoreload_frequency option that sets the number of seconds the autoreloader engine has to wait before checking for new changes. It defaults to one second if not present. [global]server.environment = "production"engine.autoreload_on = Trueengine.autoreload_frequency = 5 Autoreload is not properly a module but we mention it here as it is a common feature offered by the library. The Caching Module Caching is an important side of any web application as it reduces the load and stress of the different servers in action—HTTP, application, and database servers. In spite of being highly correlated to the application itself, generic caching tools such as the ones provided by this module can help in achieving decent improvements in your application's performance. The CherryPy caching module works at the HTTP server level in the sense that it will cache the generated output to be sent to the user agent and will retrieve a cached resource based on a predefined key, which defaults to the complete URL leading to that resource. The cache is held in the server memory and is therefore lost when stopping it. Note that you can also pass your own caching class to handle the underlying process differently while keeping the same high-level interface. The Coverage Module When building an application it is often beneficial to understand the path taken by the application based on the input it processes. This helps to determine potential bottlenecks and also see if the application runs as expected. The coverage module provided by CherryPy does this and provides a friendly browseable output showing the lines of code executed during the run. The module is one of the few that rely on a third-party package to run. The Encoding/Decoding Module Publishing over the Web means dealing with the multitude of existing character encoding. To one extreme you may only publish your own content using US-ASCII without asking for readers' feedback and to the other extreme you may release an application such as bulletin board that will handle any kind of charset. To help in this task CherryPy provides an encoding/decoding module that filters the input and output content based on server or user-agent settings. The HTTP Module This module offers a set of classes and functions to handle HTTP headers and entities. For example, to parse the HTTP request line and query string: s = 'GET /note/1 HTTP/1.1' # no query stringr = http.parse_request_line(s) # r is now ('GET', '/note/1', '','HTTP/1.1')s = 'GET /note?id=1 HTTP/1.1' # query string is id=1r = http.parse_request_line(s) # r is now ('GET', '/note', 'id=1','HTTP/1.1')http.parseQueryString(r[2]) # returns {'id': '1'}Provide a clean interface to HTTP headers:For example, say you have the following Accept header value:accept_value = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"values = http.header_elements('accept', accept_value)print values[0].value, values[0].qvalue # will print text/html 1.0 The Httpauth Module This module provides an implementation of the basic and digest authentication algorithm as defined in RFC 2617. The Profiler Module This module features an interface to conduct a performance check of the application. The Sessions Module The Web is built on top of a stateless protocol, HTTP, which means that requests are independent of each other. In spite of that, a user can navigate an e-commerce website with the impression that the application more or less follows the way he or she would call the store to pass an order. The session mechanism was therefore brought to the Web to allow servers to keep track of users' information. CherryPy's session module offers a straightforward interface to the application developer to store, retrieve, amend, and delete chunks of data from a session object. CherryPy comes natively with three different back-end storages for session objects: Back-end type Advantages Drawbacks RAM Efficient Accepts any type of objects No configuration needed Information lost when server is shutdown Memory consumption can grow fast File system Persistence of the information Simple setup File system locking can be inefficient Only serializable (via the pickle module) objects can be stored Relational database (PostgreSQL built-in support) Persistence of the information Robust Scalable Can be load balanced Only serializable objects can be stored Setup less straightforward
Read more
  • 0
  • 0
  • 2853
Modal Close icon
Modal Close icon