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-creating-analysis-services-cube-visual-studio-2008-part-1
Packt
22 Oct 2009
4 min read
Save for later

Creating an Analysis Services Cube with Visual Studio 2008 - Part 1

Packt
22 Oct 2009
4 min read
  Reviewing Jayaram's other OLAP related articles may greatly help in understanding this article. Installing SQL Server Analysis Services SQL Server Analysis Services (SSAS) gets installed during the SQL Server 2008 (February 2008 CTP) installation. At that time the Service Accounts for the various components are also set up as shown in this screen shot taken during a typical installation. For full details review the following article on SQL Server 2008 installation. The Analysis Services is also configured during the same installation as shown displaying the default directories for Data, log file, backup etc. Starting and Stopping the SSAS The Analysis Services can be started and stopped from the Services in the local machine which can be accessed from All Programs | Control Panel | Administrative Tools | Services. Connecting to SSAS from SQL Server Management Studio File | Connect Object Explorer... in SQL Server Management Studio allows you to access the UI shown below where you can provide login information and get connected to the Analysis Services as shown. Out of the box, the SSAS comes up with a simple folder structure as shown. It does not come with databases. You may create a new database (this is not to be confused with databases on the Database Engine of SQL Server 2008). The database you create here will have the same folder structure as the Analysis Services Project folder structure when you start with VS 2008. Creating an Analysis Services Project in VS 2008 File | New | Project... opens the New Project window. Choose Business Intelligence Projects and from the Visual Studio installed templates choose Analysis Services Project. Change the default name of project to Nwind2008. This creates an empty project with a number of folders as shown. Although this is an empty structure you can deploy it on the server. To deploy right click with Nwind2008 highlighted and choose to deploy. After the processing is successfully completed you will see that Nwind 2008 is now available on the localhost. Adding a Data Source Right click on Data Sources folder and this will display the menu item New Data Source... as shown. Click on New Data Source... to open the Data Source Wizard as shown in the next figure. Read carefully the instructions on this page. In particular note that in order to change features of the data source you need to call up the next wizard - The Data Source View Wizard. Click on the Next button. This opens the page "Select how to define the connection" of the wizard as shown in the next figure. Here you can either create a data source based on an existing connection or use a new connection, or create a data source based on another object. The window also displays the existing connections under Data Connections and for each highlighted connection displays the properties on the right side. The New... button allows you to create a new connection by guiding you with more interactive windows. Click on Hodentek2.Northwind (<Server Name>.<database name>) (this will be different in your case) choose this data source and click on the Next button. This opens the Impersonation Page of the Data Source Wizard as shown with all text boxes empty, but with the Windows user name and password as default choice. Northwind database is not installed when you install SQL Server 2008. You may follow the procedure described in these articles to bring the Northwind database to SQL server 2008. Copying a Database from SQL Server 2005 to SQL Server 2008 using the Copy Database Wizard and Moving a Database from SQL Server 2005 to SQL Server 2008 in Three Steps. Change it to Use the service account and click on the Next button. This displays the Completing the Wizard page as shown where a Data source name and its connection information are displayed. Click on the Finish button. This adds the chosen data source to the Data Sources folder as shown. Northwind.ds is the file that is added and any changes to the source can be made by double clicking this file and applying the changes.  
Read more
  • 0
  • 0
  • 5380

article-image-visual-sourcesafecreating-service-oriented-application
Packt
22 Oct 2009
17 min read
Save for later

Visual SourceSafe:Creating a Service-Oriented Application

Packt
22 Oct 2009
17 min read
I will build a prototype for a hotel reservation system outlining the way Software Configuration Management makes the job easier. Don't worry if you are not fully familiar with the technologies used. The purpose of this application is purely for reference, so you can sit back and relax. At this point I will use my time machine and get a screenshot for the final application so you can see how it will look like. Or, I can insert the screenshot after it finished. I think the first way seems more reasonable. This is what the public reservation site looks like: If you like it, you can download the application from the book's website: http://orbitalhotel.alexandruserban.com. Now let's get back to our time and start the development lifecycle on the Orbital Hotel product. The first phase is the specifications phase. Specifications—Project Architecture In order to build a software system, we need a list of requirements. What is the purpose of the system? What are the actions performed by the system and against the system? Who will use the system and how? The answers to these questions will let us identify the main parts of the system and the way these parts work together. System Requirements Let's take a look at the Orbital Hotel's reservation system's requirements. The purpose of the reservation system is to allow guests to make room reservations. There are several room types each having a number, occupancy, price, availability, description, and image. The reservations can be made by using the hotel's internet website, through the websites of travel agencies (third parties), or by making phone calls to the hotel's client service. Reservations can be also made by internal client service staff who receive phone calls from guests. When guests use the hotel's website, they will create a user with a username and password and input their personal details such as first name, last name, address, city, zip code, state, country, phone, email address, and card number. Then they will choose a room and complete the reservation details such as arrival date, the number of nights they will be staying and the number of adults, teenagers, children, and pets. They will also be able to cancel their reservation. When making a reservation over the phone, a guest will provide the same personal information and reservation details to the hotel's client-service staff. The staff will create a reservation for the guest using an internal application. The staff members will also authenticate using a username and password. Travel agencies and other third parties must also be able to make hotel reservations. Taking a big picture about the type of system we are going to build, what we need is an application design that will be as flexible as possible. It should provide us with a variety of options like reservations through phone calls, personal or third-party websites, smart devices like PDAs or cell phones, and so on. This is where we gather the specifications and plan the system architecture. In this phase we have to consider as many aspects as we can, based on our requirements and specifications. So, let's see what the main existing application architectures are, and see what application architecture fits our requirements. Application Architectures The computer and computer programming history is a very short one in comparison with that of other industries. Although it is short, it has evolved and continues to evolve very rapidly, changing the way we live. Taking into account the architectures used at the beginning of computer programming, we can see an evolution from the single, powerful, fault-tolerant, expensive super mainframe computer applications, towards multiple, distributed, less expensive smaller machine applications, the personal computers. During this evolution, three main application architectures can be identified: Compact application architecture Component application architecture Service-Oriented Architecture (SOA) We are going to take a brief look at these application architectures and outline their characteristics. Compact Application Architecture During application development for the single mainframe, there was no clear separation between application layers and no reusable components were used. All the data access, business logic, and user interface-specific code were contained in a single executable program. This traditional compact architecture was used because the mainframe computers had specific proprietary programming languages and formats for accessing and manipulating the data. All the data access-specific procedures as well as the business logic and business rules code are written in this programming language. At the surface, a user interface is presented to the user for data visualisation and manipulation. This application architecture works for applications that do not need data input from multiple sources and can be easily developed by a single programmer. However, this approach has several major disadvantages when it comes to building large-scale systems: Application components cannot be reused in other applications because they are tightly coupled and dependent on one another. Tight coupling means that in order for a piece of code to use another piece of code, it must have intimate knowledge about its implementation details. Being tightly coupled, a change to one component can affect the functionality of another, making debugging and maintenance a difficult task. The application is actually a black box; no one, except the main developer, knows what it is in there. Applying security is another problem because the user interface cannot be separated from the business logic components using security-specific mechanisms like authentication and authorization. Application integration is affected because the code is platform dependent. Integration between two such applications requires special and specific coding and can be difficult to maintain. Scalability issues are considered when the system grows and need to be scaled across several machines. Using this application architecture, scalability is not possible as you can't separate different application parts across different physical boundaries because of the tight coupling. To address the issues with the compact application architecture, the component-based application architecture was developed. Component Application Architecture In the component application architecture, the application's functionality is defined using components. A component is like a black box, a software unit that encapsulates data and code and provides at the surface a set of well-defined interfaces used by other components. Since a component only needs to support a well-defined set of interfaces, it can change the inner implementation details without affecting other components that use its external interfaces. Components that export the same interfaces can be interchanged, allowing them to be reused and tight coupling to be eliminated. This makes them loosely coupled because they don't need to know internal implementation details of one another. This separation of application functionality using components allows the distribution of development tasks across several developers and makes the overall application more maintainable and scaleable. In the Windows environment, the most used component application architecture is the Component Object Model (COM). Typically, components are grouped into logical layers. For example, an application uses the data access layer to access the different data sources, the business logic layer to process the data according to the business rules, and the presentation layer also known as the user interface layer to present the data to end users. Using well-defined application layers allows for a modular design, component decoupling, and therefore the possibility for component reuse. Data Access Layer This architecture forms a chain of layers that communicate with one another. The base is the data access layer, which is responsible for querying, retrieving, and updating the data from and to different data sources while providing a uniform data view to the layers above. Business Layer Above the data access layer is the business logic layer. The business logic layer uses the uniform data provided by the data access layer and processes it according to the business rules it contains. The business logic layer doesn't need to know from what source and how the data was obtained. Its purpose is only data manipulation and processing. Presentation Layer At the top of the chain is the presentation layer or the user interface layer. Its purpose is to present the data processed by the business logic layer to end users and to receive input and commands from these end users. The presentation layer will propagate these commands down the chain to the business layer for processing. Characteristics The component application architecture solves many software problems and it has been used extensively in the past. But because software evolves continuously, new requirements introduce new challenges. Let's suppose we have several applications on different platforms, each incorporating its presentation layer, business logic layer, and data access layer. We want to integrate them into a bigger distributed system, a system that spans across several heterogeneous environments. At some point, one application will need to access the data existing in another application. While components can work well in a homogenous environment on the same platform, for example COM in the Windows environment, problems appear in components working across several platforms. For example, it is very difficult for a COM component to be used from a Java application or vice-versa, mainly because they don't speak the same language. Integration between two or more applications running on different platforms would require a middle component-dependent intercommunication layer that is expensive, difficult to build, and reintroduces tight coupling between systems, which is what we tried to avoid in the first place. Avoiding building this intercommunication layer would require that the data exchange between these applications be done by a person who will read the necessary data from the source application and write it into the target application. We need to integrate these systems, and maintain the loose coupling between them. What we need to do, is make these components understand each other, making them to speak the same language. This is where the concept of services and Service-Oriented Architecture (SOA) comes into play. Service-Oriented Architecture SOA describes an information technology architecture that enables distributed computing environments with many different types of computing platforms and applications. To enable distributed computing environments, SOA defines the concept of services. A service is a well-defined, self-contained unit of functionality, independent of the state of other services. Let's see how services can be used to create distributed applications, integrate component-based applications, and make them communicate with each other. We keep our data access layer and business logic layer as they are, but we completely decouple the presentation layer so we can change it later without affecting the other layers. In order to expose the functionality of the business logic layer, we wrap it in a service interface. The service interface wraps the business logic layer components offering a point of access for any process that needs to access the business logic, whose functionality has now become a service. Service-oriented architecture is basically a collection of services that communicate with each other. The communication can involve either simple data passing or it can involve two or more services coordinating some activity. Whatever the required functionality may be, we have now separated the functionality of applications into specific units, the services that we use to construct flexible, distributed applications. Typically services reside on different machines. They are exposed to the outside world by service interfaces. A service provider provides its functionality using the service interfaces that are used or consumed by the service consumers. A service consumer sends a service request to a service interface and receives a service response. The following figure represents a typical service consumer-service provider request. A service can be a service provider and a service consumer at the same time as it can consume other services. They communicate using a communication medium like a local area network for internal services or the Internet for external services. This communication medium is called a service bus. We saw that services don't have a presentation layer as we've decoupled the presentation layer from the rest. This presents an advantage because we can now use any platform able to understand and consume the service to build a presentation layer. The service interface has to provide a standard and open way of communication, a common language that both service providers and service consumers can understand, regardless of the machine type they are deployed on, their physical location, and the language in which they are written. XML Web Services In today's world, the communication standard used to connect services is achieved using web services. Web services are small, reusable applications that help computers with many different operating system platforms work together by exchanging messages. Web services are based on industry protocols that include XML (Extensible Markup Language), SOAP (Simple Object Access Protocol), and WSDL (Web Services Description Language). These protocols help computers work together across platforms and programming languages enabling data exchange between otherwise unconnected sources: Client-to-Client: Devices, also called smart clients, can host and consume XML web services, allowing data sharing anywhere, anytime. Client-to-Server: A server application can share data with desktop or mobile devices using XML web services over the Internet. Server-to-Server: Independent server applications can use XML web services as a common interface to share and exchange data. Service-to-Service: Systems that work together to deliver complex data processing can be created using XML web services. The following figure shows an example of services exposed using web services, which deliver their functionality to a wide variety of platforms and applications. Service-oriented architecture provides us with the maximum flexibility in building applications. Individual services define specific application functions and interact with one another to provide the entire business process functionality. Encapsulation: Just as an object encapsulates its internal implementation details inside while providing public methods to external objects, services encapsulate their internal complexity and implementation from the service consumers who don't have to know the internal details. Mobility: As services are independent and encapsulated, they can be deployed in any location. Since they are using the same standard communication language, they are accessed in the same way irrespective of their physical location or implementation details. Parallel development: A service-oriented application is built using several service layers and clients. These application components can be built in parallel by developers specialized in specific layer functionality, speeding up the development process. Platform independence: Service providers and service consumers can be written in any language and deployed on any platform, as long as they can speak the standard communication language. Security: More security can be added to a service-oriented application at the service interface layer. Different application components require different security levels. The security can be enforced by using firewalls configured to allow access only to the required service providers only by the required service consumers. In addition, by using Web Service Enhancements (WSE), authentication, authorization, and encryption can be easily added. Reusability: Once a service is constructed and deployed, it can be used by any other service consumer without problems related to platform integration and interoperability. Choosing an Application Architecture Now that we have seen the existing application architectures, we must choose one that meets our project requirements. As you may have guessed by this point, the best application architecture we can use for our project is a Service-Oriented Architecture (SOA). The SOA allows us to build a distributed system, a system that has great flexibility and interoperability with other systems on other platforms. This will allow us to build the business logic functions and expose them as services that will be used by higher functionality layers. Choosing an Application Platform After choosing our application architecture, we must choose a platform capable of building and supporting it. For the purpose of our system we will choose the Microsoft .NET Framework platform and build the system using Microsoft Visual Studio.NET 2005 and Microsoft SQL Server as the back-end database for storing the data. Microsoft .NET Framework From a Service-Oriented Architecture point of view, the .NET Framework is the Microsoft strategy for connecting systems, information, and devices through software such as web services. .NET technology provides the capability to quickly build, deploy, manage, and use connected, security-enhanced solutions through the use of web services. Intrinsically, the .NET Framework is an environment for development and execution that allows different programming languages and libraries to work together to create Windows-based applications that are easier to build, manage, deploy, and integrate with other networked systems. The .NET core components are: The Common Language Runtime (CLR): A language-neutral development and execution environment that provides a consistent model and services to manage application execution that includes: Support for different programming languages: A variety of over 20 programming languages that target the CLR, such as C#, VB.NET, and J#, can be used to develop applications. Support for libraries developed in different languages: Libraries developed in different languages integrate seamlessly, making application development faster and easier. Support for different platforms: .NET applications are not tied to a single platform and can be executed on any platform that supports the CLR. Enhanced security: The .NET Code Access Security model provides a managed environment for application execution and security. Automatic resource management: The CLR automatically handles process, memory, and thread management, enabling developers to focus on the core business logic code.   The Framework Class Libraries (FCL): An object-oriented library of classes that extends a wide range of functionality including: Support for basic operations: Input/output and string management, standard network protocols, and network standards such as TCP/IP, XML, SOAP, and HTTP are supported natively to allow basic operations and system connections. Support for data access and data manipulation: The FCL includes a range of data access and data manipulation classes forming the ADO.NET technology that natively supports XML and data environments such as SQL Server and Oracle. Support for desktop applications: Rich desktop and mobile client applications can be easily created using the Windows Forms technology. Support for web applications: Thin web clients, websites, and web services can be created using web forms and XML web services technologies that form ASP.NET.   In the planning phase we've gathered the project requirements and specifications and we've also chosen an application architecture. The next phase is the design phase. Designing the System In the design phase, we will create an application design based on the application architecture, project requirements, and specifications. Gathering all the information needed to design the system is a difficult task, but the most important step is to start writing down the first idea. System Structure The system will be composed from the following main component categories: Core components (Data Access Layer, Business Logic Layer) forming the middle-tier component layers. Web service components (XML Web service) forming the Service Interface layer. Website components (ASP.NET website) forming the front-end WebReservation application, a web presentation layer. Windows Application components (Windows Forms Application) forming the WinReservation application, a Windows presentation layer. The following figure illustrates the overall system structure, outlining each system component: As we saw earlier, one major advantage of a service-oriented application is the decoupling of the presentation layer from the business logic layer. This allows for the business logic layer being exposed as a web service to be used by other third parties to integrate its functionality into their business process. Database Structure The back-end database is hosted by a Microsoft SQL Server system. According to the project specifications the internal database structure will be composed of the following database tables: User (Contains the user accounts) Guest (Contains the personal details of the guests) Room (Contains the details of each of the hotel's rooms) Reservation (Contains the details of the reservation made by each user) The following figure illustrates these tables and the relations between them. The bold fields are mandatory (not NULL). The User table contains the following rows:    
Read more
  • 0
  • 0
  • 4652

article-image-custom-types-documentum
Packt
22 Oct 2009
4 min read
Save for later

Custom Types in Documentum

Packt
22 Oct 2009
4 min read
Custom Types Documentum provides a large number of built-in object types that support the functionality of the platform. Some object types are general purpose and can be used for business purposes as well. However, all possible business needs can neither be anticipated nor supported by default. Therefore, Documentum allows creation of new object types, which are called custom types. This article addresses creation and management of custom types. Before reading this article, it would be helpful to know about Objects and Types, since the majority of the concepts pertaining to object types apply here as well. Some concepts are explained here. Managing Custom Types A user-defined object type is called a custom type and the user-defined properties are called custom properties. Properties are also known as attributes. Custom types can be created, modified, and removed as long as certain rules are followed. This section describes the detail around managing custom types. Creating a Custom Type A custom type can be created using Documentum Application Builder (DAB), using Documentum Administrator (DA), or using DQL/API scripts. DAB is the most commonly used application for creating custom types since it fully supports the data dictionary (see Data Dictionary later in this article) and it has a Graphical User Interface (GUI) specifically designed for creating and managing custom types. Further, DAB can also be used for packaging the types into a DocApp. The following screenshot shows the DAB screen for creating and updating a custom type: DA provides basic support for managing custom types. For example, DA does not provide an interface for defining value assistance for a property. The following screenshot shows the screen for creating and updating custom types in DA: Creating a custom type is a privileged operation and only the users with following privileges can do so: Create Type Sysadmin Superuser        The user creating the type becomes the owner of the type. A custom type can extend an existing type through inheritance (see Type Hierarchy in Documentum). A new custom type can have an existing custom type or one of the sets of Documentum object types as its supertype. The most common supertype for a new custom type for representing documents is dm_document. It is also possible to create a custom type without a supertype. Such a type is called a NULL type. Only a user with Superuser privilege can create a NULL type. A NULL type is useful for storing data that does not need the usual object management features such as versioning. There are several built-in types that are NULL types such as dm_user, dm_session, and dm_alias_set. If a custom type is intended to only store non-versionable data, a NULL type may be appropriate for this purpose. Recall that any given type uses up to two tables (one for single-valued properties and one for repeating) of its own for storing non-inherited properties of its objects. There are additional views for retrieving all the properties together. The following key information is needed or captured in DAB when creating a new custom type:   Info Description Name Name of the type. A type name must be unique (caseinsensitive) in the repository and can be up to 27 characterslong. The additional constraints on the type name are that itcannot contain a space or punctuation nor can it be same asany DQL reserved word, such as SELECT or WHERE. Further, it cannot start with dm_, dmi, dmr_, a number, space, or a single quote. It is recommended that a custom prefix be used for custom type names to distinguish them from the other types. Creator The user creating the type. Supertype The supertype of the new type. This can be NULL. Label User-friendly version of the name, for display purposes in Documentum client applications. Default Lifecycle A lifecycle that can be attached to a document of this type, without identifying the lifecycle explicitly. Default Storage Area A storage area identifies where the content files are stored for objects. The default storage area identifies where the content files for objects of this type will be stored by default. Default Permission Set The default permission set is used when the default ACL mode for the Content Server is set to Type. In this case, a new object of this type gets this permission set. Template Document One or more template documents can be created for the type, which are available to users when they are creating a new object of this type. The template documents are stored in the Templates cabinet in Documentum repository.
Read more
  • 0
  • 0
  • 5481

article-image-podcasting-linux-command-line-tools-and-audacity
Packt
22 Oct 2009
5 min read
Save for later

Podcasting with Linux Command Line Tools and Audacity

Packt
22 Oct 2009
5 min read
Introduction Recording a good podcast is as much about good voice training and delivery, as much as it is about the technology used to record it. As with other things, you only get better with practice. In this article we will use Linux command line tools and optionally Audacity to create a quick, no-frills podcast with a background music track. The only other GUI-based tool we will manipulate, will be the ALSA Mixer. The mixer has a command-line interface too, but the GUI is intuitive and quicker. The emphasis is on quick turnaround. If you are the type that attaches a quick voice message to an e-mail for impact, ("We simply must get this done by Friday!!") then the podcast creation method outlined here should appeal to you. If you are new to podcasting and audio mixer setups, the next few sections might be tedious. But towards the end of this article, we will see how quickly one can run down these steps so that you spend more time recording your message than wrestling with technology or complicated screens. The Recording Setup A stereo headset with a microphone works best for making or listening to podcasts; but do not despair if you have a desktop microphone and a pair of speakers. You can always upgrade your setup later. For now just make sure that the sound from the speakers does not directly reach the microphone and cause feedback. Place the microphone towards the lower right of your mouth as you speak, away from your nose. This avoids breathing sounds getting captured. Minimizing ambient noise by choosing a quieter time of the day is also a good idea. Recording Tips All through the recording and mixing process, there are a couple of things to keep in mind. First, stay above the noise floor. The signal should be recorded high enough to stay above the background noise and hiss. If your audio signals are like little, beautiful flowers growing in a grassy field, make sure their stalks are tall enough to tower over the field. Else you would lose the flowers in the prickly grass just as your audio signal would be lost in the background hiss and noise. Second, stay below the clipping or overload level of the audio channels. If your audio channels were like open water canals, then overloading them past the clipping limit would have a similar undesirable effect on your audio experience as a canal overflowing its banks -- puddles around your feet or a jarring quality to your sound. Since sound level is a dynamic quantity, record your audio at a level of around 80% keeping some margin (or headroom) against clipping. Setting up the Audio Mixer Connections An audio mixer application helps us record our podcast by allowing us to mix various signal sources in the right proportion. You can bring up the sound mixer from the Linux start menu by getting into the Sound and Video category. To those who are new to the red and green lights of the Linux ALSA mixer, let us run a quick intro. There are audio signal sources and there are destinations. An audio mixer allows you to route one or more sources after adjusting their relative levels to one or more destinations and achieve your project goal. The project goal might be listening to music -- the destination in this case being a pair of headphones or speakers; or it might be a recording device, say, to capture a podcast as we will do presently. Once the ALSA mixer or Kmix is up, select the Output tab. Make sure the Master output channel as well as the PCM channel is switched on (click over the green lights so they turn on) and their gains -- the slider positions -- are at the maximum. Briefly, go the Switches tab and click over the LED indicator to switch on the 'Mix Mono'. We will use this mixing switch to mix the microphone (voice) and the CD (background score) signals to both the monitoring and the recording channels. You can optionally select the 'Mic Boost' switch but experiment with your microphone to check if you indeed need it. Now, go to the Input tab. The two input sources that interest us are the 'Mic' or microphone for our voice and the CD for our background music score. We need to mix these two signal sources in the right proportion and deliver them to the Capture device. Turn on the green LEDs for the 'Mic' and 'CD' sources ensuring that their outputs feed into the 'Mono Mix' and also to your monitoring headphones or speakers. That way you get to listen to what is being recorded. All other input sources should be off (their corresponding green LEDs should be off). Lastly, turn on the red LED under the Capture slider on the Input tab ensuring that the 'Mix Mono' output gets connected to the recording channel.
Read more
  • 0
  • 0
  • 27058

Packt
22 Oct 2009
8 min read
Save for later

Working with Rails – ActiveRecord, Migrations, Models, Scaffolding, and Database Completion

Packt
22 Oct 2009
8 min read
ActiveRecord, Migrations, and Models ActiveRecord is the ORM layer (see the section Connecting Rails to a Database in the previous article) used in Rails. It is used by controllers as a proxy to the database tables. What's really great about this is that it protects you against having to code SQL. Writing SQL is one of the least desirable aspects of developing with other web-centric languages (like PHP): having to manually build SQL statements, remembering to correctly escape quotes, and creating labyrinthine join statements to pull data from multiple tables. ActiveRecord does away with all of that (most of the time), instead presenting database tables through classes (a class which wraps around a database table is called a model) and instances of those classes (model instances). The best way to illustrate the beauty of ActiveRecord is to start using it. Model == Table The base concept in ActiveRecord is the model. Each model class is stored in the app/models directory inside your application, in its own file. So, if you have a model called Person, the file holding that model is in app/models/person.rb, and the class for that model, defined in that file, is called Person. Each model will usually correspond to a table in the database. The name of the database table is, by convention, the pluralized (in the English language), lower-case form of the model's class name. In the case of our Intranet application, the models are organized as follows: Table Model class File containing class definition (in app/models) people Person person.rb companies Company company.rb addresses Address address.rb We haven't built any of these yet, but we will shortly. Which Comes First: The Model or The Table? To get going with our application, we need to generate the tables to store data into, as shown in the previous section. It used to be at this point where we would reach for a MySQL client, and create the database tables using a SQL script. (This is typically how you would code a database for a PHP application.) However, things have moved on in the Rails world. The Rails developers came up with a pretty good (not perfect, but pretty good) mechanism for generating databases without the need for SQL: it's called migrations, and is a part of ActiveRecord. Migrations enable a developer to generate a database structure using a series of Ruby script files (each of which is an individual migration) to define database operations. The "operations" part of that last sentence is important: migrations are not just for creating tables, but also for dropping tables, altering them, and even adding data to them. It is this multi-faceted aspect of migrations which makes them useful, as they can effectively be used to version a database (in much the same way as Subversion can be used to version code). A team of developers can use migrations to keep their databases in sync: when a change to the database is made by one of the team and coded into a migration, the other developers can apply the same migration to their database, so they are all working with a consistent structure. When you run a migration, the Ruby script is converted into the SQL code appropriate to your database server and executed over the database connection. However, migrations don't work with every database adapter in Rails: check the Database Support section of the ActiveRecord::Migration documentation to find out whether your adapter is supported. At the time of writing, MySQL, PostgreSQL, SQLite, SQL Server, Sybase, and Oracle were all supported by migrations. Another way to check whether your database supports migrations is to run the following command in the console (the output shown below is the result of running this using the MySQL adapter): >> ActiveRecord::Base.connection.supports_migrations? => true We're going to use migrations to develop our database, so we'll be building the model first. The actual database table will be generated from a migration attached to the model. Building a Model with Migrations In this section, we're going to develop a series of migrations to recreate the database structure outlined in Chapter 2 of the book Ruby on Rails Enterprise Application Development: Plan, Program, Extend. First, we'll work on a model and migration for the people table. Rails has a generate script for generating a model and its migration. (This script is in the script directory, along with the other Rails built-in scripts.) The script builds the model, a base migration for the table, plus scripts for testing the model. Run it like this: $ ruby script/generate model Person exists app/models/  exists test/unit/    exists test/fixtures/    create app/models/person.rb    create test/unit/person_test.rb    create test/fixtures/people.yml    exists db/migrate    create db/migrate/001_create_people.rb Note that we passed the singular, uppercase version of the table name ("people" becomes "Person") to the generate script. This generates a Person model in the file app/models/person.rb; and a corresponding migration for a people table (db/ migrate/001_create_people.rb). As you can see, the script enforces the naming conventions, which connects the table to the model. The migration name is important, as it contains sequencing information: the "001" part of the name indicates that running this migration will bring the database schema up to version 1; subsequent migrations will be numbered "002...", "003..." etc., each specifying the actions required to bring the database schema up to that version from the previous one. The next step is to edit the migration so that it will create the people table structure. At this point, we can return to Eclipse to do our editing. (Remember that you need to refresh the file list in Eclipse to see the files you just generated). Once, you have started Eclipse, open the file db/migrate/001_create_people.rb. It should look like this:     class CreatePeople < ActiveRecord::Migration        def self.up            create_table :people do |t|                # t.column :name, :string            end        end        def self.down            drop_table :people        end    end This is a migration class with two class methods, self.up and self.down. The self.up method is applied when migrating up one database version number: in this case, from version 0 to version 1. The self.down method is applied when moving down a version number (from version 1 to 0). You can leave self.down as it is, as it simply drops the database table. This migration's self.up method is going to add our new table using the create_table method, so this is the method we're going to edit in the next section. Ruby syntaxExplaining the full Ruby syntax is outside the scope of this book. For our purposes, it suffices to understand the most unusual parts. For example, in the create_table method call shown above:,     create_table :people do |t|        t.column :title, :string        ...    end The first unusual part of this is the block construct, a powerful technique for creating nameless functions. In the example code above, the block is initialized by the do keyword; this is followed by a list of parameters to the block (in this case, just t); and closed by the end keyword. The statements in-between the do and end keywords are run within the context of the block. Blocks are similar to lambda functions in Lisp or Python, providing a mechanism for passing a function as an argument to another function. In the case of the example, the method call create_table:people is passed to a block, which accepts a single argument, t; t has methods called on it within the body of the block. When create_table is called, the resulting table object is "yielded" to the block; effectively, the object is passed into the block as the argument t, and has its column method called multiple times. One other oddity is the symbol: that's what the words prefixed with a colon are. A symbol is the name of a variable. However, in much of Rails, it is used in contexts where it is functionally equivalent to a string, to make the code look more elegant. In fact, in migrations, strings can be used interchangeably with symbols.  
Read more
  • 0
  • 0
  • 5395

article-image-php-data-objects-error-handling
Packt
22 Oct 2009
11 min read
Save for later

PHP Data Objects: Error Handling

Packt
22 Oct 2009
11 min read
In this article, we will extend our application so that we can edit existing records as well as add new records. As we will deal with user input supplied via web forms, we have to take care of its validation. Also, we may add error handling so that we can react to non-standard situations and present the user with a friendly message. Before we proceed, let's briefly examine the sources of errors mentioned above and see what error handling strategy should be applied in each case. Our error handling strategy will use exceptions, so you should be familiar with them. If you are not, you can refer to Appendix A, which will introduce you to the new object-oriented features of PHP5. We have consciously chosen to use exceptions, even though PDO can be instructed not to use them, because there is one situation where they cannot be avoided. The PDO constructors always throw an exception when the database object cannot be created, so we may as well use exceptions as our main error‑trapping method throughout the code. Sources of Errors To create an error handling strategy, we should first analyze where errors can happen. Errors can happen on every call to the database, and although this is rather unlikely, we will look at this scenario. But before doing so, let's check each of the possible error sources and define a strategy for dealing with them. This can happen on a really busy server, which cannot handle any more incoming connections. For example, there may be a lengthy update running in the background. The outcome is that we are unable to get any data from the database, so we should do the following. If the PDO constructor fails, we present a page displaying a message, which says that the user's request could not be fulfilled at this time and that they should try again later. Of course, we should also log this error because it may require immediate attention. (A good idea would be emailing the database administrator about the error.) The problem with this error is that, while it usually manifests itself before a connection is established with the database (in a call to PDO constructor), there is a small risk that it can happen after the connection has been established (on a call to a method of the PDO or PDO Statement object when the database server is being shutdown). In this case, our reaction will be the same—present the user with an error message asking them to try again later. Improper Configuration of the Application This error can only occur when we move the application across servers where database access details differ; this may be when we are uploading from a development server to production server, where database setups differ. This is not an error that can happen during normal execution of the application, but care should be taken while uploading as this may interrupt the site's operation. If this error occurs, we can display another error message like: "This site is under maintenance". In this scenario, the site maintainer should react immediately, as without correcting, the connection string the application cannot normally operate. Improper Validation of User Input This is an error which is closely related to SQL injection vulnerability. Every developer of database-driven applications must undertake proper measures to validate and filter all user inputs. This error may lead to two major consequences: Either the query will fail due to malformed SQL (so that nothing particularly bad happens), or an SQL injection may occur and application security may be compromised. While their consequences differ, both these problems can be prevented in the same way. Let's consider the following scenario. We accept some numeric value from a form and insert it into the database. To keep our example simple, assume that we want to update a book's year of publication. To achieve this, we can create a form that has two fields: A hidden field containing the book's ID, and a text field to enter the year. We will skip implementation details here, and see how using a poorly designed script to process this form could lead to errors and put the whole system at risk. The form processing script will examine two request variables:$_REQUEST['book'], which holds the book's ID and $_REQUEST['year'], which holds the year of publication. If there is no validation of these values, the final code will look similar to this: $book = $_REQUEST['book'];$year = $_REQUEST['year'];$sql = "UPDATE books SET year=$year WHERE id=$book";$conn->query($sql); Let's see what happens if the user leaves the book field empty. The final SQL would then look like: UPDATE books SET year= WHERE id=1; This SQL is malformed and will lead to a syntax error. Therefore, we should ensure that both variables are holding numeric values. If they don't, we should redisplay the form with an error message. Now, let's see how an attacker might exploit this to delete the contents of the entire table. To achieve this, they could just enter the following into the year field: 2007; DELETE FROM books; This turns a single query into three queries: UPDATE books SET year=2007; DELETE FROM books; WHERE book=1; Of course, the third query is malformed, but the first and second will execute, and the database server will report an error. To counter this problem, we could use simple validation to ensure that the year field contains four digits. However, if we have text fields, which can contain arbitrary characters, the field's values must be escaped prior to creating the SQL. Inserting a Record with a Duplicate Primary Key or Unique Index Value This problem may happen when the application is inserting a record with duplicate values for the primary key or a unique index. For example, in our database of authors and books, we might want to prevent the user from entering the same book twice by mistake. To do this, we can create a unique index of the ISBN column of the books table. As every book has a unique ISBN, any attempt to insert the same ISBN will generate an error. We can trap this error and react accordingly, by displaying an error message asking the user to correct the ISBN or cancel its addition. Syntax Errors in SQL Statements This error may occur if we haven't properly tested the application. A good application must not contain these errors, and it is the responsibility of the development team to test every possible situation and check that every SQL statement performs without syntax errors. If this type of an error occurs, then we trap it with exceptions and display a fatal error message. The developers must correct the situation at once. Now that we have learned a bit about possible sources of errors, let's examine how PDO handles errors. Types of Error Handling in PDO By default, PDO uses the silent error handling mode. This means that any error that arises when calling methods of the PDO or PDOStatement classes go unreported. With this mode, one would have to call PDO::errorInfo(), PDO::errorCode(), PDOStatement::errorInfo(), or PDOStatement::errorCode(), every time an error occurred to see if it really did occur. Note that this mode is similar to traditional database access—usually, the code calls mysql_errno(),and mysql_error() (or equivalent functions for other database systems) after calling functions that could cause an error, after connecting to a database and after issuing a query. Another mode is the warning mode. Here, PDO will act identical to the traditional database access. Any error that happens during communication with the database would raise an E_WARNING error. Depending on the configuration, an error message could be displayed or logged into a file. Finally, PDO introduces a modern way of handling database connection errors—by using exceptions. Every failed call to any of the PDO or PDOStatement methods will throw an exception. As we have previously noted, PDO uses the silent mode, by default. To switch to a desired error handling mode, we have to specify it by calling PDO::setAttribute() method. Each of the error handling modes is specified by the following constants, which are defined in the PDO class: PDO::ERRMODE_SILENT – the silent strategy. PDO::ERRMODE_WARNING – the warning strategy. PDO::ERRMODE_EXCEPTION – use exceptions. To set the desired error handling mode, we have to set the PDO::ATTR_ERRMODE attribute in the following way: $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); To see how PDO throws an exception, edit the common.inc.php file by adding the above statement after the line #46. If you want to test what will happen when PDO throws an exception, change the connection string to specify a nonexistent database. Now point your browser to the books listing page. You should see an output similar to: This is PHP's default reaction to uncaught exceptions—they are regarded as fatal errors and program execution stops. The error message reveals the class of the exception, PDOException, the error description, and some debug information, including name and line number of the statement that threw the exception. Note that if you want to test SQLite, specifying a non-existent database may not work as the database will get created if it does not exist already. To see that it does work for SQLite, change the $connStr variable on line 10 so that there is an illegal character in the database name: $connStr = 'sqlite:/path/to/pdo*.db'; Refresh your browser and you should see something like this: As you can see, a message similar to the previous example is displayed, specifying the cause and the location of the error in the source code. Defining an Error Handling Function If we know that a certain statement or block of code can throw an exception, we should wrap that code within the try…catch block to prevent the default error message being displayed and present a user-friendly error page. But before we proceed, let's create a function that will render an error message and exit the application. As we will be calling it from different script files, the best place for this function is, of course, the common.inc.php file. Our function, called showError(), will do the following: Render a heading saying "Error". Render the error message. We will escape the text with the htmlspecialchars() function and process it with the nl2br() function so that we can display multi-line messages. (This function will convert all line break characters to tags.) Call the showFooter() function to close the opening and tags. The function will assume that the application has already called the showHeader() function. (Otherwise, we will end up with broken HTML.) We will also have to modify the block that creates the connection object in common.inc.php to catch the possible exception. With all these changes, the new version of common.inc.php will look like this: <?php/*** This is a common include file* PDO Library Management example application* @author Dennis Popel*/// DB connection string and username/password$connStr = 'mysql:host=localhost;dbname=pdo';$user = 'root';$pass = 'root';/*** This function will render the header on every page,* including the opening html tag,* the head section and the opening body tag.* It should be called before any output of the/*** This function will 'close' the body and html* tags opened by the showHeader() function*/function showFooter(){?></body></html><?php}/*** This function will display an error message, call the* showFooter() function and terminate the application* @param string $message the error message*/function showError($message){echo "<h2>Error</h2>";echo nl2br(htmlspecialchars($message));showFooter();exit();}// Create the connection objecttry{$conn = new PDO($connStr, $user, $pass);$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch(PDOException $e){showHeader('Error');showError("Sorry, an error has occurred. Please try your requestlatern" . $e->getMessage());} As you can see, the newly created function is pretty straightforward. The more interesting part is the try…catch block that we use to trap the exception. Now with these modifications we can test how a real exception will get processed. To do that, make sure your connection string is wrong (so that it specifies wrong databasename for MySQL or contains invalid file name for SQLite). Point your browser to books.php and you should see the following window:
Read more
  • 0
  • 0
  • 6809
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-pop-image-widget-using-javascript-php-and-css
Packt
22 Oct 2009
7 min read
Save for later

Pop-up Image Widget using JavaScript, PHP and CSS

Packt
22 Oct 2009
7 min read
If you’re a regular blog reader then it’s likely that you’ve encountered the Recent Visitors widget form (http://mybloglog.com). This widget displays the profile like name, picture and sites authored by members of Mybloglog who have recently visited your blog. In the Mybloglog widget, when you move the mouse cursor to the member’s picture, you’ll see a popup displaying a brief description of that member. A glance at MyBlogLog widget The above image is of a MyBlogLog widget. As you can see in the right part of the widget, there is a list of the recent visitors to the blog from members of MyBlogLog. You may also have noticed that in the left part of the widget is a popup showing the details and an image of the visitor. This popup is displayed when the mouse is moved over the image on the widget. Now, let’s look at the code which we got from MyBlogLog to display the above widget. <script src="http://pub.mybloglog.com/comm3.php?mblID=2007121300465126&r= widget&is=small&o=l&ro=5&cs=black&ww=220&wc=multiple"></script> In the above script element, the language and type attributes are not specified. Although they are optional attributes in HTML - you must specify a value in the type attribute to make the above syntax valid in an XHTML web page. If you closely looked at the src attribute of the script element, you can see that the source page of the script is a .php file. You can use the JavaScript code with any file extension like .php , .asp, and so on , but whenever you use such a file in src attribute please note that the final output code of the file (after being parsed by server) should be a valid JavaScript code. Creating pop-up image widget This pop-up image widget is somewhat similar to MyBlogLog widget but it is a simplified version of that widget. This is a very simple widget with uses JavaScript, PHP and CSS. Here you’ll see four images in the widget and a pop-up image (corresponding to the chosen image) will be displayed when you move the mouse over it. After getting the core concept, you can extend the functionality to make this look fancier. Writing Code for Pop-up Image Widget As I’ve already discussed, this widget is going to contain PHP code, JavaScript and a little bit of CSS as well. For this, you need to write the code in a PHP file with the .php extension. First of all, declare the variables for storing the current mouse position and string variables for storing the string of the widget. var widget_posx=0;var widget_posy=0;var widget_html_css=''; The widget_posx variable is to hold the x co-ordinate values of the mouse position on the screen, whereas, the widget_posy variable will store the y co-ordinate. The widget_html_css variable stores the HTML and CSS elements which will be used later in the code. The (0,0) co-ordinate of the output devices like monitor is located at the top left position. So the mouse position 10,10 will be somewhere near the top left corner of monitor. After declaring the variables, let’s define an event handler to track the mouse position on the web page. document.onmousemove=captureMouse; As you can see above, we’ve called a function captureMouse() When the mouse is moved anywhere on the document (web page), the event handler which is the function captureMouse() is called on the onmousemove event. The Document object represents the entire HTML document and can be used to access and capture the events of all elements on a page. Each time a user moves the mouse one pixel, a mousemove event occurs. It engages system resources to process all mousemove events, hence, use this event carefully! Now, let’s look at the code of the captureMouse() function. function captureMouse(event){ if (!event){var event = window.event;}if (event.pageX || event.pageY) { widget_posx = event.pageX; widget_posy = event.pageY; } else if (event.clientX || event.clientY) { widget_posx = event.clientX; widget_posy = event.clientY; } } As you can see in the above function, the event variable is passed as a function parameter. This event variable is the JavaScript’s Event object. The Event object keeps track of various events that occur on the page, such as the user moving the mouse or clicking on the link, and allows you to react to them by writing code which is relevant to the event. if (!event){var event = window.event;} In the above code, the first line of the event handler ensures that if the browser doesn’t pass the event information to the above function, then we would obtain it from any explicit event registration of the window object. We can track different activity in the document by the event object with the help of its various defined properties. For example, if eventObj is the event object and we’ve to track whether the ctrl key is pressed (or not) - we can use the following code in JavaScript: eventObj.ctrlKey If we’ve assigned the x, y-position of mouse in the page using the pageX and pageY properties, we can also get the same mouse position of the mouse cursor using clientX and clientY property. Most browsers provide both pageX/pageY and clientX/clientY. Internet Explorer is the only current browser that provides clientX/clientY, but not pageX/pageY. To provide cross-browser support, we’ve used both pageX/pageY and clientX/clientY to get the mouse co-ordinates in the document, and assigned them to the widget_posx and widget_posy variables accordingly. Now, let’s look at widget_html_css variable, where we’re going to store the string which is going to be displayed in the widget. widget_html_css+='<style type="text/css">';widget_html_css+='.widgetImageCss';widget_html_css+='{ margin:2px;border:1px solid #CCCCCC;cursor:pointer}';widget_html_css+='</style>'; As you can see in the string of the above variable, we’ve added the style for the HTML element with the class name widgetImageCss within the style element. When applied, this class in the HTML adds a 2 pixel margins ‘brown color border’ to the element. Furthermore, the mouse cursor will be converted into pointer (a hand) which is defined with the cursor attribute in CSS. widget_html_css+='<div id="widget_popup"style="position:absolute;z-index:10; display:none">&nbsp;</div>'; Using the above code, we’re adding a division element with id widget_popup to the DOM. We’ve also added style to this element using inline styling. The position attribute of this element is set to absolute so that this element can move freely without disturbing the layout of the document. The z-index property is used for stacking the order of the element and in the above element it is set 10 so that this element will be displayed above all the other elements of the document. Finally, the display property is set to none for hiding the element at first. Afterwards, this element will be displayed with the pop-up image using JavaScript in the document. Elements can have negative stack orders i.e. you can set the z-index to -1 for an element. This will display it underneath the other elements on the page. Z-index only works on elements that have been positioned using CSS (such as position:absolute). Now, the PHP part of the codes comes in. We’ve used PHP to add the images to the widget_html_css string variables of JavaScript. We’ve used PHP in this part rather than using JavaScript for making this application flexible. JavaScript is a client side scripting language and can’t access the database or do any kind of server activity. Using PHP, you can extract and display the images from the database which might be the integral part of your desired widget.
Read more
  • 0
  • 0
  • 8547

article-image-consuming-adapter-outside-biztalk-server
Packt
22 Oct 2009
3 min read
Save for later

Consuming the Adapter from outside BizTalk Server

Packt
22 Oct 2009
3 min read
In addition to infrastructure-related updates such as the aforementioned platform modernization, Windows Server 2008 Hyper-V virtualization support, and additional options for fail over clustering, BizTalk Server also includes new core functionality. You will find better EDI and AS2 capabilities for B2B situations and a new platform for mobile development of RFID solutions. One of the benefits of the new WCF SQL Server Adapter that I mentioned earlier was the capability to use this adapter outside of a BizTalk Server solution. Let's take a brief look at three options for using this adapter by itself and without BizTalk as a client or service. Called directly via WCF service reference If your service resides on a machine where the WCF SQL Server Adapter (and thus, the sqlBinding) is installed, then you may actually add a reference directly to the adapter endpoint. I have a command-line application, which serves as my service client. If we right-click this application, and have the WCF LOB Adapter SDK installed, then Add Adapter Service Reference appears as an option. Choosing this option opens our now-beloved wizard for browsing adapter metadata. As before, we add the necessary connection string details and browse the BatchMaster table and opt for the Select operation. Unlike the version of this wizard that opens for BizTalk Server projects, notice the Advanced options button at the bottom. This button opens a property window that lets us select a variety of options such as asynchronous messaging support and suppression of an accompanying configuration file. After the wizard is closed, we end up with a new endpoint and binding in our existing configuration file, and a .NET class containing the data and service contracts necessary to consume the service. We should now call this service as if we were calling any typical WCF service. Because the auto-generated namespace for the data type definition is a bit long, I first added an alias to that namespace. Next, I have a routine, which builds up the query message, executes the service, and prints a subset of the response. using DirectReference = schemas.microsoft.com.Sql._2008._05.Types.Tables.dbo; … private static void CallReferencedSqlAdapterService() { Console.WriteLine("Calling referenced adapter service");TableOp_dbo_BatchMasterClient client = new TableOp_dbo_BatchMasterClient("SqlAdapterBinding_TableOp_dbo_BatchMaster"); try{string columnString = "*";string queryString = "WHERE BatchID = 1";DirectReference.BatchMaster[] batchResult =client.Select(columnString, queryString);Console.WriteLine("Batch results ...");Console.WriteLine("Batch ID: " + batchResult[0].BatchID.ToString());Console.WriteLine("Product: " + batchResult[0].ProductName);Console.WriteLine("Manufacturing Stage: " + batchResult[0].ManufStage);client.Close(); Console.ReadLine(); } catch (System.ServiceModel.CommunicationException){client.Abort(); } catch (System.TimeoutException) { client.Abort(); } catch (System.Exception) { client.Abort(); throw; } } Once this quick block of code is executed, I can confirm that my database is accessed and my expected result set returned.
Read more
  • 0
  • 0
  • 1899

article-image-backing-and-restoring-typo3-websites
Packt
22 Oct 2009
4 min read
Save for later

Backing Up and Restoring TYPO3 Websites

Packt
22 Oct 2009
4 min read
What Needs Backing Up in TYPO3? We need to back up: The TYPO3 files A copy of the database These two things make up our TYPO3 installation. We need the database as it contains the website's content and records of the website's users. We need the TYPO3 files as they contain the website's settings in the configuration files, copies of the website's design, and copies of data that has been cached by TYPO3. Backing Up the TYPO3 Files Depending on the operating system we are using, there are a number of different ways in which we can back up the files from TYPO3. In this article, we will look into backing up the files on Windows and on Linux. This is because Windows is the most used operating system, and Linux is the most popular hosting environment for websites. Backing Up Our Files on Windows In Windows, we can easily create a compressed file containing all the TYPO3 files (known as a ZIP file), using the Windows Compressed Folder tool, or a program such as WinZip. Provided we've used the default installation path, TYPO3 will be located in the folder C:Program FilesTypo3_4.0.2Apache and the folder that we want to compress is typo3_src. We could just back up the fileadmin, typo3conf, and uploads folders. This way, should we lose our entire website, we can simply restore the whole thing instead of having to restore TYPO3 and then our extra TYPO3 files. Now that we have a backup, we should copy it to a separate location (preferably on an external disk, or on another computer) for safe keeping. Backing Up Our Files on Linux or Linux Hosting We can create a complete backup of our home directory on a Linux hosting environment. This home directory contains all of our files on the hosting account. Alternatively, we can run a simple command to compress a particular folder. If we have a web hosting account that provides us with access to the cPanel hosting control panel, we can use that to generate a backup of our entire website (except for the database—which is done separately via cPanel). To access the backup utilities, we need to log in to cPanel, which is located at www.ourdomain.com/cpanel, and then enter our hosting account's username and password. In cPanel, we have the backup option on the main screen, as shown in the following screenshot: The Backups section has a number of options, but the one that we want is the Download a home directory Backup. This will generate a backup of all the files of our website and allow us to download it. In the previous screenshot, there is a warning message. This is because my web server does not have the option to back up the entire server, just an individualuser's webspace. The backup tool then takes a moment or two of processing, and then prompts us to download the backup file. Command-Line Backup To create a backup via the command line, we need to have SSH access to the server that is hosting our website. SSH is a protocol that allows us to remotely administer another machine using the command line. We can use a program such as Putty to connect to the server. We can download Putty from http://www.chiark.greenend.org.uk/~sgtatham/putty/. Putty only needs to be downloaded, after which it can be run straight away, and does not require to be installed. When we open the program, we are presented with a screen similar to the one shown in the following screenshot. We enter the server's address (i.e. the web address) into the Host Name box and then click on Open. Putty will then try to connect to the server, and will prompt us to enter our username and password, as shown in the following screenshot: Once we are connected, we can type two commands to back up our site. The first is to navigate to the folder that contains our TYPO3 installation. This depends entirely on the server's setup and your username, but is generally /home/the first 8 characters of your web address/public_html (you should contact your web host for more information or if you need help). Once we are in the correct folder, we can use the tar command to compress our TYPO3 folder to a single file named TYPO3. cd /home/michaelp/public_html/tar cvzf file.tar.gz typo3 Now that we have our backup created, we can download it from www.ourwebaddress.com/file.tar.gz (where we will be prompted to save the file). We should then delete this from our server once we have downloaded it.
Read more
  • 0
  • 0
  • 7616

article-image-codeigniter-and-objects
Packt
22 Oct 2009
12 min read
Save for later

CodeIgniter and Objects

Packt
22 Oct 2009
12 min read
To save the world from a lot of boring t-shirts, this article covers the way in which CI uses objects, and the different ways you can write and use your own objects. Incidentally, I've used 'variables/properties', and 'methods/functions' interchangeably, as CI and PHP often do. You write 'functions' in your controllers for instance, when the OO purist would call them 'methods'. You define class 'variables' when the purist would call them 'properties'. Object-Oriented Programming I'm assuming you—like me—have a basic knowledge of OOP, but may have learned it as an afterthought to 'normal' PHP 4. PHP 4 is not an OO language, though some OO functionality has been tacked on to it. PHP 5 is much better, with an underlying engine that was written from the ground up with OO in mind. But you can do most of the basics in PHP 4, and CI manages to do everything it needs internally, in either language. The key thing to remember is that, when an OO program is running, there is always one current object (but only one). Objects may call each other and hand over control to each other, in which case the current object changes; but only one of them can be current at any one time. The current object defines the 'scope'—in other words, which variables (properties) and methods (functions) are available to the program at that moment. So it's important to know, and control, which object is current. Like police officers and London buses, variables and methods belonging to objects that aren't current just aren't there for you when you most need them. PHP, being a mixture of functional and OO programming, also offers you the possibility that no object is current! You can start off as a functional program, call an object, let it take charge for a while, and then let it return control to the program. Luckily, CI takes care of this for you. Working of the CI 'Super-Object' CI works by building one 'super-object': it runs your whole program as one big object, in order to eliminate scoping issues. When you start CI, a complex chain of events occurs. If you set your CI installation to create a log, you'll see something like this:     1 DEBUG - 2006-10-03 08:56:39 --> Config Class Initialized    2 DEBUG - 2006-10-03 08:56:39 --> No URI present. Default controller    set.    3 DEBUG - 2006-10-03 08:56:39 --> Router Class Initialized    4 DEBUG - 2006-10-03 08:56:39 --> Output Class Initialized    5 DEBUG - 2006-10-03 08:56:39 --> Input Class Initialized    6 DEBUG - 2006-10-03 08:56:39 --> Global POST and COOKIE data    sanitized    7 DEBUG - 2006-10-03 08:56:39 --> URI Class Initialized    8 DEBUG - 2006-10-03 08:56:39 --> Language Class Initialized    9 DEBUG - 2006-10-03 08:56:39 --> Loader Class Initialized    10 DEBUG - 2006-10-03 08:56:39 --> Controller Class Initialized    11 DEBUG - 2006-10-03 08:56:39 --> Helpers loaded: security    12 DEBUG - 2006-10-03 08:56:40 --> Scripts loaded: errors    13 DEBUG - 2006-10-03 08:56:40 --> Scripts loaded: boilerplate    14 DEBUG - 2006-10-03 08:56:40 --> Helpers loaded: url    15 DEBUG - 2006-10-03 08:56:40 --> Database Driver Class Initialized    16 DEBUG - 2006-10-03 08:56:40 --> Model Class Initialized On startup—that is, each time a page request is received over the Internet—CI goes through the same procedure. You can trace the log through the CI files:      The index.php file receives a page request. The URL may indicate which controller is required, if not, CI has a default controller (line 2). Index.php makes some basic checks and calls the codeigniter.php file (codeignitercodeigniter.php).      The codeigniter.php file instantiates the Config, Router, Input, URL, (etc.) classes (lines 1, and 3 to 9). These are called the 'base' classes: you rarely interact directly with them, but they underlie almost everything CI does.      codeigniter.php tests to see which version of PHP it is running on, and calls Base4 or Base5 (/codeigniter/Base4(or 5).php). These create a 'singleton' object: one which ensures that a class has only one instance. Each has a public &get_instance() function. Note the &:, this is assignment by reference. So if you assign to the &get_instance() method, it assigns to the single running instance of the class. In other words, it points you to the same pigeonhole. So, instead of setting up lots of new objects, you are starting to build up one 'super-object', which contains everything related to the framework.      After a security check, codeigniter.php instantiates the controller that was requested, or a default controller (line 10). The new class is called $CI. The function specified in the URL (or a default) is then called, and life as we know it starts to wake up and happen. Depending on what you wrote in your controller, CI will then initialize any other classes you need, and 'include' functional scripts you asked for. So in the log above, the model class is initialized. (line 16) The 'boilerplate' script, on the other hand, which is also shown in the log (line 13), is one I wrote to contain standard chunks of text. It's a .php file, saved in the scripts folder, but it's not a class: just a set of functions. If you were writing 'pure' PHP you might use 'include' or 'require' to bring it into the namespace: CI needs to use its own 'load' function to bring it into the super-object. The concept of 'namespace' or scope is crucial here. When you declare a variable, array, object, etc., PHP holds the variable name in its memory and assigns a further block of memory to hold its contents. However, problems might arise if you define two variables with the same name. (In a complex site, this is easily done.) For this reason, PHP has several sets of rules. For example:      Each function has its own namespace or scope, and variables defined within a function are usually 'local' to it. Outside the function, these are meaningless.      You can declare 'global' variables, which are held in a special global namespace and are available throughout the program.      Objects have their own namespaces: variables exist inside the object for as long as the object exists, but can only be referenced through the object. So $variable, global $variable, and $this->variable are three different things. Particularly, before OO, this could lead to all sorts of confusion: you may have too many variables in your namespace (so that conflicting names overwrite each other), or you may find that some variables are just not accessible from whatever scope you happen to be in. CI offers a clever way of sorting this out for you. So, now you've started CI, using the URL www.mysite.com/index.php/welcome/ index, which specifies that you want the index function of the welcome controller. If you want to see what classes and methods are now in the current namespace and available to you, try inserting this 'inspection' code in the welcome controller:     $fred = get_declared_classes();    foreach($fred as $value)    {$extensions = get_class_methods($value);    print "class is $value, methods are: ";    print_r($extensions);} When I ran this just now, it listed 270 declared classes. Most are other libraries declared in my installation of PHP. The last 11 came from CI: ten were the CI base classes (config, router, etc.) and last of all came the controller class I had called. Here's the last 11, with the methods omitted from all but the last two:     258: class is CI_Benchmark    259: class is CI_Hooks,    260: class is CI_Config,    261: class is CI_Router,    262: class is CI_Output,    263: class is CI_Input,    264: class is CI_URI,    265: class is CI_Language,    266: class is CI_Loader,    267: class is CI_Base,    268: class is Instance,    269: class is Controller, methods are: Array ( [0] => Controller [1]    => _ci_initialize [2] => _ci_load_model [3] => _ci_assign_to_models    [4] => _ci_autoload [5] => _ci_assign_core [6] => _ci_init_scaffolding    [7] => _ci_init_database [8] => _ci_is_loaded [9] => _ci_scaffolding    [10] => CI_Base )    270: class is Welcome, methods are: Array ( [0] => Welcome [1] =>    index [2] => Controller [3] => _ci_initialize [4] => _ci_load_model    [5] => _ci_assign_to_models [6] => _ci_autoload [7] => _ci_assign_core    [8] => _ci_init_scaffolding [9] => _ci_init_database [10] => _ci_is_    loaded [11] => _ci_scaffolding [12] => CI_Base ). Notice—in parentheses as it were—that the Welcome class (number 270: the controller I'm using) has all the methods of the Controller class (number 269). This is why you always start off a controller class definition by extending the controller class—you need your controller to inherit these functions. (And similarly, models should always extend the model class.) Welcome has two extra methods: Welcome and index. So far, out of 270 classes, these are the only two functions I wrote! Notice also that there's an Instance class. If you inspect the class variables of the 'Instance' class, you will find there are a lot of them! Just one class variable of the Instance class, taken almost at random, is the array input:     ["input"]=> &object(CI_Input)#6 (4) { ["use_xss_clean"]=> bool(false)    ["ip_address"]=> bool(false) ["user_agent"]=> bool(false) ["allow_get_    array"]=> bool(false) } Remember when we loaded the input file and created the original input class? Its class variables were:     use_xss_clean is bool(false)    ip_address is bool(false)    user_agent is bool(false)    allow_get_array is bool(false) As you see, they have now all been included within the 'instance' class. All the other CI 'base' classes (router, output, etc.) are included in the same way. You are unlikely to need to write code referencing these base classes directly, but CI itself needs them to make your code work. Copying by Reference You may have noticed that the CI_Input class is assigned by reference (["input"]=> &object(CI_Input)). This is to ensure that as its variables change, so will the variables of the original class. As assignment by reference can be confusing, here's a short explanation. We're all familiar with simple copying in PHP:     $one    =    1;    $two    =    $one;    echo $two; produces 1, because $two is a copy of $one. However, if you re-assign $one:     $one    =    1;    $two    =    $one;    $one    =    5;    echo $two; This code still produces 1, because changes to $one after $two has been assigned aren't reflected in $two. This was a one-off assignment of the value that happened to be in variable $one at the time, to a new variable $two, but once it was done, the two variables led separate lives. (In just the same way, if I alter $two, $one doesn't change.) In effect, PHP creates two pigeonholes: one called $one, one called $two. A separate value lives in each. You may, on any one occasion, make the values equal, but after that they each do their own thing. PHP also allows copying 'by reference'. If you add just a simple & to line 2 of the code:     $one = 1;    $two =& $one;    $one = 5;    echo $two; Then the code now echoes 5: the change we made to $one has also happened to $two. Changing the = to =& in the second line means that the assignment is 'by reference'. Now, it's as if there was only one pigeonhole, which has two names ($one and $two). Whatever happens to the contents of the pigeonhole happens both to $one and to $two, as if they were just different names for the same thing. The principle works for objects as well as simple string variables. You can copy or clone an object using the = operator, in which case you make a simple one-off new copy, which then leads an independent life. Or, you can assign one to the other by reference: now the two objects point to each other, so any changes made to the one will also happen to the other. Again, think of them as two different names for the same thing.
Read more
  • 0
  • 0
  • 7081
article-image-modeling-orchestration-and-choreography-service-oriented-architecture
Packt
22 Oct 2009
30 min read
Save for later

Modeling Orchestration and Choreography in Service Oriented Architecture

Packt
22 Oct 2009
30 min read
  Choreography versus Orchestration Choreography and orchestration, in an SOA context, pertain to the use of processes that span multiple participants, with message traffic moving in all directions according to a complex set of rules. Choreography and orchestration are attempts to coordinate or control all of this activity. They attack the problem by putting rigor on how message exchanges are represented, and by organizing the overall process using the right set of control flow patterns. Use cases in this area can be inter-organizational (for example, B2B commerce involving buyer, seller, and wholesaler), or intra-organizational if the organization is large enough and the participants act as separate organizations (for example, bank account processes spanning the front office, the back office, and the fraud department). By convention, choreography describes the global protocol governing how individual participants interact with one another. Each participant has its own process, but choreography is a master process that acts as a kind of traffic cop. Significantly, the choreography process does not actually run. It is not a central broker in the live message exchange, but merely a message exchange protocol. If the participants follow the protocol, the live exchange will run as smoothly as if there were a central broker. 'Traffic cop' is not exactly right then; choreography is more like a set of traffic rules. To mix metaphors, choreography teaches the participant processes how to dance as a group. The process for each participant is referred to as an orchestration process, whose principal job is to build a flow of control around (that is, to orchestrate) its interactions with partners. Orchestration processes are difficult to model, especially those faced with complex combinations of inbound events. If the process is subject to choreography, its structure can be derived from the choreography; in fact, as we'll see, there are tools that can generate skeletal orchestration processes from choreography definitions. The idea is simple: the choreography tells the complete story, so the participant can determine its role by isolating the parts in which it's involved. Not all orchestrations, alas, have a choreography to guide them (not all inter-organizational domains have a precise protocol defined). If the use case is sufficiently complex, the participant ought to create its own choreography anyway, not to share with its partners but simply to improve its own understanding of its orchestration. An orchestration process has public and private activities. The public activities are those that are required by the choreography. Private activities are there to meet internal requirements, but are not visible to partners. The next figure shows the public activities of the orchestration process for an energy retailer. The steps shown (for example, Send Request to Distributor) are those required by the enrollment choreography, in which the retailer is but one participant. The next figure shows the same process with private steps (for example, Update Account) included. In the figure, steps marked with a P are public steps. We examine the energy example in detail in this article. Web Services Choreography Description Language (WS-CDL) is the leading choreography language; Business Process Execution Language (BPEL) is the dominant process orchestration language. Although these XML-based languages feature a similar flow-oriented design style, only BPEL is meant to have an actual runtime platform: BPEL processes run; WS-CDL choreographies are protocols. BPEL is better known than WS-CDL in part because orchestration is more prevalent than choreography. BPEL's user community is much larger than WS-CDL's. Today, every company is building an SOA platform, and if they don't use BPEL as their SOA orchestration language, they use something similar. The user community for choreography consists of industry committees that publish protocols such as the enrollment and funds transfer choreographies we discuss in this article. Choreography might also work as part of a large organization's enterprise architecture, helping to sort out the communication of the organization's numerous systems. Few of these committees use WS-CDL to document their protocols anyway. Choreography is more often documented less formally using English descriptions, flowchart diagrams, and an XML message schema. Examples-Energy Enrollment and Email Bank Transfer The two examples from industry that showcase our technique for modeling choreography and orchestration are the enrollment of customers with retailers in a deregulated energy market and the procedure for transferring funds by email between two banks. In the energy market for a state or small country there are three parties: customers (who use electricity to power their homes), retailers (who sell electricity to customers), and the distributor (who supplies the electricity). Before deregulation, the distributor sold electricity directly to customers; there were no retailers back then. Deregulation introduced competition and broke up the distributor's monopoly. Customers can now buy electricity from one of many competing retailers. The distributor is now merely a supplier, having moved out of the retail sales business. When a customer enrolls with a retailer, the retailer uses the following protocol to complete the enrollment: The retailer submits the customer's request for enrollment to the distributor. The distributor responds in one of the three ways. If there is a problem with the request (for example, the customer has another enrollment in progress, or the customer has been flagged for fraud), the distributor sends a rejection to the retailer. If the request is valid and the customer is not currently enrolled with a retailer, the distributor sends an acceptance to the retailer. If the customer is currently enrolled with a competing retailer but intends to switch, the distributor sends a notice of pending switch to both the retailers. In the acceptance case, there is a 10-day waiting period during which the customer may cancel the enrollment. To cancel, the customer contacts the retailer, who forwards the cancellation request to the distributor. Assuming the customer does not cancel, at the end of the waiting period, the distributor sends a completion event to the retailer. The customer is now enrolled with the retailer. In the switch case, there is also a 10-day waiting period. To cancel, the customer contacts the initiating retailer (that is, the retailer to whom the customer is switching). The initiating retailer forwards the cancellation to the distributor, who then sends completion events to both retailers indicating that the customer will remain enrolled with the original retailer. Assuming the customer does not cancel, at the end of the waiting period, the distributor sends completion events to both retailers indicating that the customer is now enrolled with the initiating retailer. Email bank transfer is a protocol for wiring money by email. It works as follows: The person sending the money contacts his bank (the Sender bank), specifying from which account to draw the funds, how much money to send, and the name and email address of the recipient. The Sender bank sets aside the amount and sends an email to the recipient with instructions on how to complete the transfer. The Sender bank sets aside the amount and sends an email to the recipient with instructions on how to complete the transfer. The Recipient bank submits the transfer request to the Sender bank. The Sender bank accepts, and the funds are moved into the recipient's account, completing the transfer. At any point, either the sender or recipient may cancel the transfer, and the transaction is automatically canceled if not completed within 30 days. On cancellation, the funds are returned to the sender's account. (We assume both banks are members of the email transfer programme.) The following figure shows the most common scenarios in these examples: Modeling Choreography in BPMN In BPMN, two possible models for choreography are as follows: Invisible hub: Although choreography is fundamentally decentralized, we imagine there is a central hub through which all messages pass, and model the choreography as the process of that hub. Sum of parts: The public process of each participant (that is, the process containing steps required by the choreography, with private steps omitted) is drawn in a swim lane. Message flow (dashed lines) is used to show inter-participant communication. A sum-of-parts model for the enrollment choreography is shown in next figure. There are three swim lanes in the diagram: one for the distributor (referred to as Distributor), one for the initiating retailer (referred to as Retailer), and one for the current retailer (referred to as CurrentRetailer). Each lane contains the public process of the participant. The dashed arrows show the flow of messages between participants. The enrollment choreography is, according to this approach, the combination of the public processes of each participant plus the message flow that connects them. The choreography begins when the customer enrolls with the retailer (Cust Enrolls in the Retailer lane). The retailer then submits the enrollment request to the distributor by calling Dist.enroll. This call sends a message to the distributor, which triggers the event Enroll (the first step in the Distributor lane). The Distributor process is now underway, and it responds to the enrollment request either by rejecting the request, accepting it, or notifying the initiating retailer and the current retailer of a pending switch. The distributor rejects by calling Ret.reject, and, as the dashed line signifies, triggers the event Dist.reject in the retailer. The remaining steps are straightforward. The sum-of-parts method is intuitive, and variations on it can be found in business process literature (in the WSCI and BPMN specifications, for example). Sum-of-parts, however, has two disadvantages. First, the message flow creates an indecipherable clutter, making complex choreographies almost impossible to read; the swim lanes, for their part, use a lot of real estate. Aesthetics aside, sum-of-parts fails to present a global, consolidated view of the choreography. We grow bug-eyed trying to keep track of what each participant is doing. We are forced to watch each dancer rather than the group as a whole. The invisible-hub representation is comparatively compact. The next figure, which shows the enrollment choreography as a hub, has fewer steps than the sum-of-parts equivalent, and it makes do without lanes or dashed lines. The hub works as you would expect a hub to work: it listens for inbound events and routes them to their intended recipients. The act of receiving an event and sending it elsewhere is a single unit of work (shown in the figure as a rounded box with a dashed line), known as an interaction. The hub choreography represents the communication of its participants as a process of interactions. Before walking through this process, consider the following notational conventions: The event with a thin border (Ret.enroll(Dist)) is the process' start event. Events with a double-line border (for example, Dist.reject(Ret)) are intermediate events, which occur over the course of the process. Intermediate events can be used in three ways: for cancellation, for deferred choice, or simply to wait for the next message before continuing. The enrollment hub has examples of the latter two forms. We'll come back to cancellation while discussing the email transfer hub. Deferred choice, also known as an event pick, uses a diamond containing an inscribed star (known as an event-based gateway) with arrows leading to a set of intermediate events. The intent is to wait for one of those events to occur, execute its activities, and discard the remaining events. There are three deferred choices in the enrollment hub. The first occurs in three steps, and selects one of the three events: Dis.reject(Ret), Dist.accept(ret), or Dist.pendingSwitch(Ret, CurrRet). If, say, Dist.reject(Ret) occurs first, the activity Ret1.reject(Dist) is executed. The intermediate event Dist.switchCompleteCurrent(Ret, CurrRet) simply waits for something to happen before continuing. This event is sandwiched between the activities Dist.cancel(Ret) and Ret.switchCompleteCurrent, CurrRet.switchCompleteCurrent(Dist). Thus, when the first activity completes, that branch of the process waits for the event to occur before continuing with the second activity. Events have labels of the form Sender.msg (Recipients), meaning that the event received by the hub is a message from the sender bound for the specified recipients. (There must be at least one.) Thus, Dist.switchCompleteCurrent(Ret, CurrRet) is the message switchCompleteCurrent from the distributor (Dist) to both the initiating retailer (Ret) and the current retailer (CurrRet). Send tasks (rounded boxes with a straight border) are labeled Recipient.msg(Sender), meaning that hub is sending the specified message to the recipient and is indicating that the message originated with the specified sender. In Dist.enroll(Ret), for instance, the hub sends the message enroll to the distributor (Dist), and is indicating to the distributor that this message came from the retailer (Ret). If the event that preceded it specifies multiple recipients, the send task sends the message to each recipient. Each send counts as one interaction.Ret.pendingSwitch, CurrRet.pendingSwitch (Dist), for example, sends the message pendingSwitch to both the retailer (Ret) and the current retailer (CurrRet), and thus spans two interactions. A rounded box with a dashed border, known in BPMN as a group, pairs up an event and a send task. Thus, the grouping of Ret.enroll(Dist) and Dist.enroll(Ret) means that when the hub receives the message enroll from the retailer bound for the distributor, it sends that message to the distributor, indicating to the distributor that the message originated with the retailer. A group that contains multiple interactions has a label in the top-center of the dashed box indicating the number of interactions. The number of interactions is equal to the number of recipients. The enrollment hub diagram reads as follows: The choreography begins with the interaction in which the retailer sends an enrollment request to the distributor. For convenience, this interaction is labeled a in the figure. Exactly one of the three interactions can happen next: the distributor sends a rejection to the retailer (b); the distributor sends an acceptance to the retailer (c); or the distributor sends a notice of pending switch to both the initiating and current retailers (d). Exactly one of the two interactions can follow acceptance: the retailer sends a cancellation to the distributor e, or the distributor sends a completion event to the retailer (f). In the pending switch case, one of the two interactions follows the notice of pending switch: the initiating retailer sends a cancellation to the distributor (g); or the distributor sends a switch completion event to both the initiating and current retailers indicating that the current retailer won (h). If the switch is cancelled, the distributor sends a switch completion event to both retailers indicating that the initiating retailer won (i). The choreography has 12 interactions assembled in a process flow. (There are nine groups, but three of them have two interactions each.) Reading the diagram means spotting the 12 interactions and traversing the control flow that connects them. The email transfer choreography hub, shown in the next figure, is somewhat more complex. The email transfer hub reads as follows: The choreography begins when the sender submits the transfer request to the sender bank (a). The sender bank can reject the request (b), or accept it (c). The acceptance event in c is routed to both the sender and the recipient, and thus results in two interactions. The remainder of the hub process is a loop that continues until the transfer is completed. The loop is modeled as a BPMN embedded sub-process labeled Loop. The arched arrow pointing counter-clockwise in the bottom-center of the sub-process box denotes that this sub-process is iterative. In the first step of the loop, the recipient requests her bank to transfer the funds into his or her account (d). The recipient's bank either rejects (e) or accepts (f) the request. In the rejection case, the recipient's bank sends a rejection notice to the recipient. In the next iteration of the loop, the recipient can try again. In the acceptance case, the recipient's bank sends a transfer request to the sender's bank. The sender's bank can either accept (g) or reject (h) the request. In the acceptance case, the sender's bank sends a transferOK message to both the recipient's bank and the sender. The recipient's bank then notifies the recipient (i), and the choreography completes. (The Set Done task sets the loop's continuation condition to false, which causes the loop to exit and the hub process to complete.) In the rejection case, the sender's bank sends a rejectTransfer message to the recipient's bank, and the recipient's bank notifies the recipient of this (j). In the next iteration of the loop, the recipient can try again. While the loop is executing, any of the parties may cancel the request (k). The label in the event *.cancel (SenderBank) informs the hub to listen for a cancel message from any party—the * works as a wildcard—and to route that message to the sender's bank. The sender's bank, in turn, sends an abort message (l) to the sender, the recipient, and the recipient's bank (the bank into which the recipient is currently requesting the transfer). Interaction (k) is an example of a cancellation intermediate event; it terminates the loop and transition into a series of cancellation activities. Choreographies are not executable, as we discussed previously. A choreography is a protocol, a set of traffic laws. It is, emphatically, not a central hub through which all participant interactions flow. Our hub model is merely a specification of how the individual participants should communicate. There are countless senders, recipients, and banks in the world of email transfer, but there is no hub that helps them talk to each other. The invisible hub for email transfer is merely a model; it is every bit as hypothetical as the invisible hand of Adam Smith's free-market economy. The economy is self-powered, and does not require the intervention of a hand; email transfer goes on without a hub. Still, the BPMN hub model is more than an informative picture. As we'll see, it maps easily to WS-CDL, and it serves as the basis for the generation of participant stubs and a choreography 'protocol' tester. Our BPMN method is practical and built with implementation in mind. Choreography modeling is also a hot topic in the academic world. Useful papers in this arena include Inheritance of Interorganizational Workflows: How to agree to disagree without loosing control? (Wil van der Aalst," BETA Working Paper Series, BP46, Eindhoven University, http://is.tm.tue.nl/staff/wvdaalst/publications/p109.pdf) and 'Let's Dance' (servicechoreographies.com, http://sky.fit.qut.edu.au/~dumas/LetsDance/01-Overview.html). The Invisible Hub in BPEL BPEL is principally an orchestration language, as just discussed, but it can also be used to model invisible hub choreographies. The code shown in the next figure is a simplified version of an actual BPEL implementation of the enrollment hub. The mapping from the BPMN hub to this BPEL implementation is straightforward: The event that starts the choreography in BPMN (Ret.enroll(Dist)) is receive that creates the BPEL process instance, marked as Start Event in the figure. An intermediate event that simply waits for a message between activities (for example, Dist.switchCompleteCurrent (Ret, CurrRet) in the BPMN model) is a BPEL receive, such as the line marked Intermediate Event in the figure. Deferred choice is a BPEL pick. The events in the choice are onMessage handlers. For example, the deferred choice in the BPMN model of Dist.reject(Ret), Dist.accept(Ret) and Dist.pendingSwitch(Ret, CurrRet) is the pick marked as Deferred Choice in the figure. The handlers are the three onMessage blocks that sit underneath the pick. Send tasks are BPEL invoke activities. For example, Dist.enroll(Ret) in the BPMN representation becomes the invoke in the line marked Send Task in the figure. The set of partner links used in the BPEL process is the union of all sender and recipient participants in the hub. Many partner links are bidirectional: they can either call the BPEL process or the BPEL process can call the partner link. The three partner links in this example, which are referred to in each receive, invoke, and onMessage tag are Ret, Dist, and CurrRet. BPEL supports dynamic partner links (where the BPEL process determines the physical address of its partner service at runtime). The series of four steps marked Dynamic partner links in the figure provides an example. The initial receive is a message from the distributor intended for one of the two retailers (either the current or the initiating retailer). The invoke that follows sends the message to that retailer. The endpoint of that retailer is resolved at runtime, based on the contents of the receive message. The next receive is a message from the distributor intended for the second retailer, and the invoke that follows sends the message to that retailer, again resolving the endpoint at runtime. In the majority of BPEL processes, partner links are resolved at deployment time, but that approach does not work in scenarios like ours. An interaction in which the sender sends to N recipients is modeled in BPEL as N separate inbound events and invokes. The series of four steps discussed in the previous bullet (and marked with Send to Multiple in the figure) provides an example. These steps model the activity Dist.switchCompleteCurrent (Ret, CurrRet) from the BPMN hub. In the BPEL code, the effect of the distributor sending the message switchCompleteCurrent to both the initiating and current retailers is achieved by having the hub receive the message from the distributor twice (using a receive), in each case forwarding the message (using an invoke) to one of the retailers. Dynamic partner links are used to resolve the endpoint of the recipient. The figure maps lines of code in the BPEL hub to interaction groups in the BPMN model. The first two lines, for example, represent group A. The reader can easily verify the mapping for groups B to I. There are two advantages to having the hub model in BPEL form: BPEL's XML form is an alternative to the leading XML choreography representation, WS-CDL (discussed in the next section). If we require an XML representation of choreography, BPEL might be a better choice than WS-CDL, because it is more familiar and has broader tool support. The BPEL hub is executable! There are numerous BPEL runtime platforms that can run this process as an actual hub. Granted, choreographies are not meant to run as part of the live exchange of actual participants, but having an executable version enables two important types of testing, shown in the next figure: unit testing of the choreography itself, and protocol testing of a particular participant. In unit testing, we build a Test Harness, driven by scripted scenarios, that sends messages to the hub and compares responses received with those expected. In protocol testing, we build the public process of a participant (say the retailer), but point it to the hub rather than its actual partners. We can embellish the hub to use test scripts to control how it responds. Once we have tested all of the scenarios and verified that the participant behaves as required, we can point the participant process to the real partners and go live Choreography in WS-CDL with Pi4SOA The description of choreography in WS-CDL with P14SOA is as follows: Defining Roles and Relationships Web Services Choreography Description Language (WS-CDL) is a specification from the W3C (Web Services Choreography Description Language Version 1.0, http://www.w3.org/TR/ws-cdl-10) for building choreographies in XML form. Like our invisible hub model, WS-CDL takes the global view: a choreography is not the sum of the public processes of its participants, but a single control flow of interactions. The WS-CDL language is exceedingly rich and best learned by example. In this section, we study how the enrollment choreography is represented in WS-CDL. Rather than building the choreography's XML from scratch, we use a visual modelling tool known as pi4SOA. pi4SOA, an open-source implementation that plugs into Eclipse, is one of the few WS-CDL implementations available today. The first step in building a WS-CDL choreography is to define participants and their structural relationships. The following figure shows the enrollment choreography open in the Participants, Roles, and Relationships tab of the pi4SOA editor.   There are five participants (shown with building icons) in the figure: Distributor, Retailer, CurrentRetailer, Customer (to model a customer's interaction with a retailer), and DistributorBizCal (a subsystem of the distributor to model the management of business calendars for completion and switch periods). Each participant has a role of the same name (designated by a stick-man icon), and each role has a behavior named for its role: Distributor's behavior is DistributorBehavior, Retailer's behaviour is RetailerBehavior, and so on. In WS-CDL, a behavior is a web service interface, and a role is a group of behaviors. A role can have multiple behaviors and a participant can have multiple roles. In our case, each participant has one role and one participant. The lines connecting roles are called relationships. There are four relationships: RD is the relationship between Retailer and Distributor, CRD the relationship between CurrentRetailer and Distributor, RC the relationship between Retailer and Customer, and DInt the relationship between Distributor and DistributorBizCal. When two roles have a relationship, they can interact by calling each other's services. The next figure shows the Base Types tab of the choreography editor. To the participants, roles, and relationships defined above, we add four important elements: information types, tokens, token locators, and channel types. An information type is an XML data type (generally based on an XML schema) exchanged during interactions. A token is a field in an information type. A token locator defines how to extract—generally using an XPath expression—the token from the information type. Our choreography has one information type, called EnergyMsg with five tokens and token locators (custID, retailer, txID, currentRetailer, and reason). A channel type is an inbound communication endpoint for a role behavior. In the enrollment choreography, there are channels for the retailer, current retailer and distributor. Each channel type is configured for one-way asynchronous requests only. Hence, Retailer receives requests on its RetailerChannel; CurrentRetailer receives requests on its CurrentRetailerChannel; and Distributor receives requests on its DistributorChannel. Combining our definitions of relationships and channels, we have the following communication structure: In the relationship RD, Retailer sends to Distributor on DistributorChannel, and Distributor sends to Retailer on RetailerChannel   In the relationship CRD, Distributor sends to CurrentRetailer on CurrentRetailerChannel. (CurrentRetailer could also send to Distributor on DistributorChannel, but the use case does not require it.) In the relationship RC, Customer sends to Retailer on RetailerChannel. (Customer does not have a channel, so the reverse direction is not permitted.) In the relationship DInt, DistributorBizCal sends to Distributor on DistributorChannel. (DistributorBizCal does not have a channel, so the reverse direction is not permitted.) Building a Control Flow of Interactions The next figure shows the overall control flow that defines the behaviour of the choreography. There are three steps. The first, RequestC2R, is an interaction in which the Customer participant sends an enrollment request to the Retailer participant. The request has the information type EnrollmentMsg, and is sent on RetailerChannel as part of the RC relationship. In the interaction that follows, RequestR2D, the retailer forwards that request to the distributor; or, in the language of WS-CDL, Retailer sends the request with information type EnrollmentMsg on the DistributorChannel as part of the RD relationship. The step that follows, enrollmentResult, is a flow construct known as a choice. There are three possible outcomes of an enrollment request—acceptance, rejection, or a pending switch. The choice allows exactly one to occur. The next figure shows the acceptance and rejection paths; the switch path is omitted for brevity. The rejection path (housed in a sequence labelled rejectEnrollment) has one interaction, RejectD2R, in which the distributor sends a rejection message to the retailer. The more complicated acceptance path is housed in the sequence labelled newEnrollment, which begins with the interaction in which the distributor notifies the retailer that the enrollment is accepted (AcceptD2R). Next is a silent action, setCompletionTimer, in which the distributor sets a timer that expires at the end of the ten-day cancellation period. A silent action in WS-CDL is a private operation performed by a role. The acceptance path has a nested choice, labelled completionPeriod, which documents the two possible outcomes for an accepted enrolment: periodExpired is a sequence that specifies what happens when the ten-day timer expires, and cancel handles the case in which the customer cancels the enrollment during the cancellation period. Each path contains two interactions. In the periodExpired sequence, the periodExpired interaction (sent from DistributorBizCal to Distributor by the DInt relationship) notifies the distributor that time is up, whereupon the distributor sends a completion event to the retailer (CompleteD2R). In the cancel sequence, the customer cancels with the retailer (CancelC2R by the RC relationship), and the retailer, in turn, cancels with the distributor (CancelR2D by the RD relationship). The following is a snippet of the WS-CDL XML encoding of the enrollment choreography, covering the acceptance case only. For the sake of simplicity, numerous details are omitted: <package name="EnergyChoreo">   <choreography name="main" root="true">     <sequence>       <!-- Cust sends request to retailer -->       <interaction channelVariable="tns:retailerChannel"                    name="RequestC2R" operation="enroll">         <participate fromRoleTypeRef="tns:Customer"                      relationshipType="tns:RC" toRoleTypeRef="tns:Retailer"/>       </interaction>       <!-- Retailer sends request to distributor -->       <interaction channelVariable="tns:distributorChannel"                    name="RequestR2D" operation="enroll">         <participate fromRoleTypeRef="tns:Retailer"                relationshipType="tns:RD" toRoleTypeRef= "tns:Distributor"/>       </interaction>       <!-- Choose what comes next -->       <choice>         <!-- Path taken if distributor rejects -->         <sequence>           <!-- This is the interaction that heads the reject path -->             <interaction name="RejectD2R" operation="reject">             </interaction>         </sequence>         <!-- Path taken if distributor accepts -->         <sequence>           <!-- This is the interaction that heads the accept path -->             <interaction name="AcceptD2R" operation="accept">             </interaction>             <silentAction name="setCompletionTimer"                           roleType="tns:Distributor">             <choice>               <!-- Accept subpaths omitted -->             </choice>          </sequence>          <!-- Omitted: switch path -->       </choice>     </sequence>   </choreography> </package> The two key elements in this example are choice and interaction. They are mapped to our hub model as follows: A receive-send pair in the hub is a WS-CDL interaction. In WS-CDL, a relationship is defined between sender and recipient, and the recipient has a channel on which the sender sends the message. An example of this is the interaction shown in bold from the customer (fromRoleTypeRef="tns: Customer") to the retailer (toRoleTypeRef="tns:Retailer") on the RC relationship (relationshipType="tns:RC"). The event arrives on the retailer's channel (channelVariable="tns:retailerChannel"). A deferred choice in the hub is a choice structure in WS-CDL. Generally, a path in the choice is a sequence. The set of events from which we are choosing is the set of first interactions on each path. The main choice structure in the choreography, shown in bold, has two interactions from which to choose: acceptance and rejection interactions (also shown in bold). The interaction that actually occurs determines which path is taken.   Generating a BPEL Role Process In addition to producing conformant WS-CDL code, pi4SOA's capabilities include scenario testing and BPEL and Java endpoint generation. The BPEL generation feature is especially useful, as BPEL is a suitable implementation choice to build orchestration process of a given participant. Here, in pseudo-code, is the BPEL process that pi4SOA generates for the distributor: <process>   <sequence>     <receive operation="enroll" partnerLink="RD"              portType="DistributorBehavior"/>       <!-- Dist receives interaction -->     <switch name="enrollmentResult"> <!-- Dist choice is switch -->       <case condition="accepted">         <sequence>           <invoke operation="accept" partnerLink="RD"                   portType="RetailerBehavior"/> <!-- Dist is sender -->           <scope name="setCompletionTimer"/>           <pick name="completionPeriod">             <onMessage operation="periodExpired" partnerLink="DInt"                        portType="DistributorBehavior">               <sequence>                 <invoke operation="complete" partnerLink="RD"                         portType="RetailerBehavior"/>               </sequence>             </onMessage>             <onMessage operation="cancel" partnerLink="RD"                        portType="DistributorBehavior"/>           </pick>         </sequence>       </case>       <case condition="rejected ">         <invoke operation="reject" partnerLink="RD"                 portType="RetailerBehavior"/>       </case>       <case condition="switch">         <!-- omitted -->       </case>   </switch> </sequence> </process> Two salient features of this process are the mapping of interactions and the conversion of the WS-CDL choice to a BPEL switch as follows: An interaction in which the distributor is the sender is a BPEL invoke activity whose partner link is the WS-CDL relationship and whose port type is the recipient's behavior. The operation element in the invoke matches the one specified in the interaction. The invoke shown in bold, for example, which is sent to the retailer, has partner link RD, port type RetailerBehavior, and operation accept. An interaction in which the participant is the recipient is either a receive activity or an onMessage handler in a pick. The partner link is the name of the relationship, and port type is the participant's behavior. The operation element, as before, matches that specified in the interaction. The bolded receive in the BPEL sample is the enroll operation on the partner link RD and port type DistributorBehavior. The WS-CDL choice is a switch for the BPEL distributor process (as the bolded comment in the switch line indicates), because the distributor begins each path of the choice by sending a message. From the distributor's perspective, the choice represents its decision to reject the request, accept it, or initiate a pending switch. Each case in the switch handles one of these possibilities. The retailer, on the other hand, begins each path by waiting for an event from the distributor. From the retailer's point of view, the choice is a pick, as in the following snippet: <pick name="enrollmentResult"> <!-- For Ret, choice is a pick -->   <onMessage operation="accept" partnerLink="RD"              portType="RetailerBehavior">     <!-- code omitted -->   </onMessage>   <onMessage operation="reject" partnerLink="RD"              portType="RetailerBehavior" />   <onMessage operation="pendingSwitch" partnerLink="RD"              portType="RetailerBehavior" >     <!-- code omitted -->   </onMessage> </pick> We have only scratched the surface of WS-CDL. Other notable capabilities are state alignment, coordination, and channel passing. WS-CDL's supporters boast that their language has its foundations in the Pi Calculus, a mathematical scheme for describing concurrent processes and how they pass messages to each other. Robin Milner, the mathematician who devised the Pi Calculus, is an advisor to the WS-CDL working group. Sadly, WS-CDL has not gained much traction in the field. There are scant tools to build WS-CDL choreographies and, frankly, not many use cases that require choreography. Few people who practice SOA technology have even heard of this language. WS-CDL is winning the mathematics battle but losing the marketing war. Summary Choreography is the global protocol governing the interaction of SOA processes partnering to achieve some business ends. An orchestration process is a process whose principal job is to build a flow of control around its interactions with partners. WS-CDL is the dominant choreography standard. BPEL is the dominant orchestration standard. Both standards provide a way to build process flows in an XML form, though only BPEL processes are meant to actually execute. The modeling tool pi4SOA is ideal for building WS-CDL examples. Key WS-CDL elements are interaction (which corresponds to the receive-send pair in the invisible hub) and choice (a kind of deferred choice in the choreography's flow of control. pi4SOA generates skeletal BPEL code for each participant in the choreography.
Read more
  • 0
  • 0
  • 7700

article-image-development-pluggable-authentication-modules-pam
Packt
22 Oct 2009
7 min read
Save for later

Development with Pluggable Authentication Modules (PAM)

Packt
22 Oct 2009
7 min read
Introduction PAM is a very powerful and flexible framework. Applications that require authentication must be aware of PAM. But most basic applications and utilities in the UNIX and Linux world have been migrated. If you are an application programmer and your application requires authentication, you might wish to dig into the possibilities of PAM. You can find modules for almost any situation, or maybe a combination of modules can solve your problem. But still you might end up in the situation where you cannot find a suitable module. In this article, you will learn how to develop your own modules. PAM-aware Applications The PAM runtime library has a well-defined API (Application Programming Interface). The PAM API is to a large extent the same on every UNIX and Linux operating system. Only a small number of differences exist, but any programmer can make a portable work-around. The differences are primarily related to the conversation function discussed later in this article. Linux-PAM provides one as a library function while other PAM implementations require the programmer to develop a conversation function. The pamtester utility provides a conversation function, which might be applicable to other applications. The example application presented here is very simple. It can store and retrieve data (strings) in a simple (GNU DBM) database. In order to gain access, authentication through the PAM system is required. The idea is that the system administrator can control the access as he or she wishes by configuring PAM in a suitable fashion. This application is called vault. The figure below outlines how a typical application uses PAM for authentication. Most of the usage is straightforward; the application calls a set of well-defined functions, which creates, operates on, and destroys data structures related to PAM. But PAM applies a little trick: the modules can call back to the application in order to retrieve user-related data. In order to call PAM functions in your applications you must include the pam_appl.h header file. The sample application includes two: #include <security/pam_appl.h>#include <security/pam_misc.h> The second header file is special to Linux-PAM and it is related to a text-based conversation function and a few other utility functions. Opening and Closing a PAM Session Any PAM session begins with creating and initializing a data structure. The data structure (C-type) is called pam_handle_t. During the application run time, it is required to hold one variable of this data structure. It contains all relevant data about the PAM session. The creation of the data structure is equivalent to opening a PAM session. The data structure is initialized by the function pam_start. Four parameters must be supplied when calling the pam_start function. In the sample application the call to pam_start is: retval = pam_start(“vault”, user, &conv, &pamh); The first parameter is the service name. It is a simple text string, and if the application programmer permits it, the service name can be set by the user instead of hard-coding the service name in the application. In the sample application the service name is set to vault precisely at the call, and at this point the PAM runtime will try to find the configuration file associated with the service (/etc/pam.d/vault in this example) or the appropriate lines in the /etc/pam.conf file. The second parameter is the user name. The standard C runtime library provides the getlogin function, which returns the user’s login name as a text string. The third parameter is a pointer to the conversation function, which is, the function that takes care of the callbacks from the modules. We will return to the conversation function shortly. The fourth and last parameter is a pointer to the PAM handling data structure (actually, a pointer to a pointer). The call to pam_start returns an integer. If the return value is PAM_SUCCESS, the initializing of the PAM handler was as it should have been. Linux-PAM provides—as defined in the pam_appl.h header file—a conversation function, while other PAM implementations require the application programmer to develop conversation functions. When the application does not need the PAM handling data structure, it can destroy it by calling the pam_end function. This is typically just before the application is to stop executing. In the sample application, the call to pam_end at the end of the main program is as follows: pam_end(pamh, retval); The argument retval is carried along from the last call to the PAM runtime, and depending on the return value of the previous call, PAM might have to shut down a PAM session differently. Authenticating the User When an application has initialized the PAM handling data structure, the next step is to authenticate the user. Since the service name and the user name are set by the call to pam_start, the authentication can be done by a simple call to the function pam_authenticate. The call is typically as simple as: retval = pam_authenticate(pamh, 0); The first parameter is the PAM handling data structure while the second parameter is optional flags. 0 (Zero) means silence authentication but others flags might be valid depending on the PAM implementation. The return value (stored in the variable retval above), is set to PAM_SUCCESS if the user is authenticated. If the user is it not known to PAM, the return value is PAM_UNKNOWN_USER, while a general authentication failure will lead to PAM_AUTH_ERR. In the case of Linux-PAM, the only flag is PAM_DISALLOW_NULL_AUTHTOK which will lead the return value PAM_AUTH_ERR if the user is not known to PAM. In order to authenticate a user for a particular service, the auth management group cannot be empty, that is the auth stack must have at least one module. If there are no modules the return value will be PAM_AUTHINFO_UNAVAIL.   Account Health Check It is one thing to authenticate the user, but it is another thing to say whether the user is allowed to use the account. A number of issues influence the health of an account. For example, an account can be expired or the user may not currently be allowed to log in. The PAM function pam_acct_mgmt is used to check the health of the requested account. The simple call to the function is as follows: retval = pam_acct_mgmt(pamh, 0); The second parameter can be set to PAM_SILENT, which suppresses any messages from the PAM runtime, or to PAM_DISALLOW_NULL_AUTHTOK in order to require an authentication token. The flag has the same effect as for the pam_authenticate function. Manipulating the PAM Handling Data Structure In the sample application, the user name is set at the time of the call to the pam_start function, but this might not be always possible, so you need a function to set any piece of data. PAM data should not be accessed directly, so PAM provides methods for storing and retrieving the data items. The function's name is pam_set_item. Many types of items are used by PAM; the table overleaf summarizes the most important types. A complete list can be found in the Linux-PAM documentation and the Open Group's single-sign on service (see http://www.opengroup.org/pubs/catalog/p702.htm for details).
Read more
  • 0
  • 0
  • 9966

article-image-joomla-installation-virtual-server-net
Packt
22 Oct 2009
3 min read
Save for later

Joomla! Installation on a Virtual Server on the Net

Packt
22 Oct 2009
3 min read
In principle the simplest approach that actually always works is the following: Load the Joomla! 1.5 beta.zip file onto your local PC and unpack it in a temporary directory. Load the just unpacked files by means of FTP onto your rented server. The files must be installed in the publicly accessible directory. These directories are usually named htdocs, public_html, or simply html. You can specify a subdirectory within the directory into which you install your Joomla!. Many web hosts allow you to link your rented domain name to a directory. This name is necessary to call your website from a browser. You have to find out what your database is called. Usually one or several databases are included in your web-hosting package. Sometimes the user name, database name, and password are fixed; sometimes you have to set them up. There is usually a browser-based configuration interface at your disposal. You can see an example of such an interface in the following figure. You will need these access data for Joomla!'s web installer. You can get going after you have loaded these data onto your server and are in possession of your access data. Joomla! Installation To install Joomla!, you need the source code. Download the Joomla_1.5.0-Beta-Full_Package.zip package and save it on your system. Selecting a Directory for Installation You have to decide whether Joomla! needs to be installed directly into a document directory or a subdirectory. This is important, since many users prefer a short URL to their homepage. An Example If Joomla! is unzipped directly in /htdocs, the web page starts when the domain name http://www.myhomepage.com is accessed from its local computer http://localhost/ and/or from the server on the Internet. If subdirectories are created under /htdocs/, for example, /htdocs/Joomla150/ and we unzip the package there, we have to enter http://localhost/Joomla150/ in the browser. This isn't a problem locally, but doesn't look good on a production Internet page. Some HTML files and subdirectories, however, are already in /htdocs in the local XAMPP Lite environment under Windows, which, for example, displays the start page of XAMPP Lite. In a local Linux environment, a starting page dependent on the distribution and the web server settings is also displayed. Directory I recommend that you create a subdirectory under the document directory named Joomla150 in Windows by using Windows Explorer. (With Linux, use the Shell, KDE Konqueror, or Midnight Commander.) [home]/htdocs/Joomla150/ The directory tree in Windows Explorer should look like this: An empty index appears in the XAMPP Lite version when the URL http://localhost/Joomla150 is entered in the browser: With Linux or with another configuration it can happen that you get a message saying that you don't have access to this directory. This depends on the configuration of the web server. For security reasons, the automatic directory display is often deactivated in Apache's configuration. A potential hacker could draw many interesting conclusions about the directory structure and the files on your homepage and target your computer for an attack. For security reasons, you are usually not allowed to access the appropriate configuration file of the Apache web server. Should you be able to, you should leave the content directories deactivated and/or only activated for those directories that contain files for downloading.        
Read more
  • 0
  • 0
  • 1685
article-image-qmail-quickstarter-virtualization
Packt
22 Oct 2009
6 min read
Save for later

Qmail Quickstarter: Virtualization

Packt
22 Oct 2009
6 min read
Generic Virtualization Framework The most straightforward mail handling in qmail is used for what are known as the local domains: those listed in the file. The users for these domains are all the same, and are typically the users defined in control/locals/etc/passwd, though they can be defined in users/assign as well (discussed in the Non-Virtual Non-System Users section). Qmail, however, has another sense in which an email can be local, which is to assign a domain to a user (or, more accurately, to a prefix). This feature is configured with the control/virtualdomains file. Power of the virtualdomains File The virtualdomains file is one of the most powerful, useful, and stunningly simple mechanisms for configuring qmail. Virtual domains and even virtual users can be created, independently of one another, and assigned to controlling users. Virtual domains are fully independent, and as they are assigned to users (or, more accurately, prefixes) they can be in different UNIX protection domains if desired. This file can also define virtual users and similarly assign them to controlling users. This file thus makes it both possible and easy to intercept specific addresses and do something special with them. Perhaps surprisingly for the power this file wields, the control/virtualdomains file is only slightly more complicated than similar control files, such as control/locals. Rather than a list of domains, the virtualdomains file is a list of patterns and their associated prefixes. The entries are of the form: matching-pattern: prefix Only one prefix is associated with each pattern. The matching pattern can be one of the following three things: a domain (that follows the same wildcarding semantics used in the control/rcpthosts file), an email address, or an empty string. The empty string is considered to match anything. An email address matches any message addressed to that email address, and a domain matches any message addressed to a user in that domain. If there are multiple possible matches, the longest match is used. Emails that match patterns listed in the control/virtualdomains file are considered to be local emails, similar to those addressed to domains in the control/locals file. Messages that match patterns in the virtualdomains file must first undergo a simple modification before delivery. While messages are prepared for delivery, if they have an envelope destination address that matches a pattern in the virtualdomains file, that destination address is prepended with the matching pattern's associated prefix. This turns the original local part of the address into an extension of the prepended user. In this way, a domain can be mapped to a user, giving that user full control over the mailboxes (or users) within that domain. The virtualdomains file can also be used to define exceptions to the matching rules, if the prefix is blank. It is important to note that the control/virtualdomains file is considered after the control/locals file, which means that if an email is addressed to a domain listed in locals, the virtualdomains file will not apply. Also, virtualdomains rewriting occurs before the mail is given to qmail-lspawn for delivery. This sounds complex, but is easy to understand with an example. Basic Virtual Domains An example virtualdomains file that demonstrates most of the file's features is as follows: example.com:foo.example.com:foo-bartwo.example.com:bazwaldo@domain.com:quxdomain.com::garply Presuming that the users mentioned i.e. foo, baz, qux, and garply are the only local users on this system; these lines cause the following results:      The first line matches any address ending in @example.com, such as user@example.com. Such a destination address will be rewritten as foo-user@example.com, ensuring that the email's delivery will be controlled by the local user named foo.      Messages addressed to user@something.example.com do not match the first line but do match the second line, and so will be delivered as if they had been addressed to foo-bar-user@something.example.com.      Because the virtualdomains file is used in a longest match wins manner, the third line (not the second) will match messages addressed to user@two.example.com. This destination will be rewritten asbaz-user@two.example.com and baz will control the delivery of such messages.      The fourth line specifies that email addressed to waldo@domain.com will be instead delivered as if it had been addressed to qux-waldo@domain.com. The qux user will control that delivery.      The fifth line specifies that any domain.com email—other than waldo@domain.com—should be treated as if had been listed in the domain.comcontrol/locals file.      Finally, the sixth line specifies that all other email will be rewritten and delivered to the local garply user. For example, email addressed to someone@somewhere.org will be rewritten as garply-someone@somewhere.org and delivery will be attempted locally. In this example, the foo user is essentially in charge of the entirety of the example.com domains. Users that are specific to example.com are defined by creating appropriately named .qmail files in foo's home directory. For example, to establish the standard postmaster@example.com address, foo would create a file named .qmail-postmaster in its home directory, containing the instructions for delivering postmaster's email. The foo user could also establish a address by creating a file named foo@example.com.qmail-foo in his or her home directory. In this way, once the example.com mapping has been established, the foo user can set up and maintain the users in the example.com domain without ever requiring further permission from or contact with the system administrator. It is worth pointing out that precisely who controls what can get more complex if real usernames have extension separator characters (a hyphen, by default) in them. For example, if the address postmaster@example.com is rewritten to be foo-postmaster@example.com, it is typically delivered according to the instructions in ~foo/.qmail-postmaster or, if that file does not exist, ~foo/.qmail-default. However, if there is a user named foo-postmaster, that user will receive email addressed to postmaster@example.com. If a .qmail file (such as ~foo/.qmail-postmaster) cannot be located for a given extension address (such as foo-postmaster@example.com), the alias user's directory is checked for .qmail files. Specifically, .qmail-foo-postmaster, .qmail-foo-default, and .qmail-default. If none of these files exist, the message is considered undeliverable and is bounced. Note that during delivery of such an email, the standard environment variables are defined per the rewritten destination rather than per the original address. For example, if a message addressed to postmaster@example.com is delivered using the example configuration, the affected environment variables will be defined as follows (assuming foo's home directory is /home/foo):   Environment Variable Content for Virtual Domain Delivery Content for Normal Delivery RECIPIENT foo-postmaster@example.com postmaster@example.com USER foo-postmaster postmaster LOCAL foo postmaster HOME /home/foo /home/postmaster HOST example.com example.com HOST2 example example HOST3 example example HOST4 example example EXT postmaster      
Read more
  • 0
  • 0
  • 3505

Packt
22 Oct 2009
6 min read
Save for later

Working with Rails – Setting up and connecting to a database

Packt
22 Oct 2009
6 min read
In this article, authors Elliot Smith and Rob Nichols explain the setup of a new Rails application and how to integrate it with other data sources. Specifically, this article focuses on turning the abstract data structure for Intranet into a Rails application. This requires a variety of concepts and tools, namely: The structure of a Rails application. Initializing an application using the rails command. Associating Rails with a database. The built-in utility scripts included with each application. Using migrations to maintain a database. Building models and validating them. Using the Rails console to manually test models. Automated testing of models using Test::Unit. Hosting a project in a Subversion repository. Importing data into the application using scripts. In this article, we'll focus on the first 3 concepts. The World According to Rails To understand how Rails applications work, it helps to get under its skin: find out what motivated its development, and the philosophy behind it. The first thing to grasp is that Rails is often referred to as opinionated software (see http://www.oreillynet.com/pub/a/network/2005/08/30/ruby-rails-davidheinemeier-hansson.html). It encapsulates an approach to web application development centered on good practice, emphasizing automation of common tasks and minimization of effort. Rails helps developers make good choices, and even removes the need to make choices where they are just distractions. How is this possible? It boils down to a couple of things: Use of a default design for applications-By making it easy to build applications using the Model-View-Controller (MVC) architecture, Rails encourages separation of an application's database layer, its control logic, and the user interface. Rails' implementation of the MVC pattern is the key to understanding the framework as a whole. Use of conventions instead of explicit configuration-By encouraging use of a standard directory layout and file naming conventions, Rails reduces the need to configure relationships between the elements of the MVC pattern. Code generators are used to great effect in Rails, making it easy to follow the conventions. We'll see each of these features in more detail in the next two sections. Model-View-Controller Architecture The original aim of the MVC pattern was to provide architecture to bridge the gap between human and computer models of data. Over time, MVC has evolved into an architecture which decouples components of an application, so that one component (e.g. the control logic) can be changed with minimal impact on the other components (e.g. the interface). Explaining MVC makes more sense in the context of "traditional" web applications. When using languages such as PHP or ASP, it is tempting to mix application logic with database-access code and HTML generation. (Ruby, itself, can also be used in this way to write CGI scripts.) To highlight how a traditional web application works, here's a pseudo-code example:     # define a file to save email addresses into    email_addresses_file = 'emails.txt'    # get the email_address variable from the querystring    email_address = querystring['email_address']    # CONTROLLER: switch action of the script based on whether    # email address has been supplied    if '' == email_address        # VIEW: generate HTML form to accept user input which        # posts back to this script        content = "<form method='post' action='" + self + "'>        <p>Email address: <input type='text' name='email_address'/></p>        <p><input type='submit' value='Save'/></p>        </form>"    else        # VIEW: generate HTML to confirm data submission        content = "<p>Your email address is " + email_address + "</p>"        # MODEL: persist data        if not file_exists(email_addresses_file)            create_file(email_addresses_file)        end if        write_to_file(email_addresses_file, email_address)    end if    print "<html><head><title>Email manager</title></head>    <body>" + content + "</body></html>" The highlighted comments indicate how the code can be mapped to elements of the MVC architecture: Model components handle an application's state. Typically, the model does this by putting data into some kind of a long-term storage (e.g. database, filesystem). Models also encapsulate business logic, such as data validation rules. Rails uses ActiveRecord as its model layer, enabling data handling in a variety of relational database back-ends.In the example script, the model role is performed by the section of code which saves the email address into a text file. View components generate the user interface (e.g. HTML, XML). Rails uses ActionView (part of the ActionPack library) to manage generation of views.The example script has sections of code to create an appropriate view, generating either an HTML form for the user to enter their email address, or a confirmation message acknowledging their input. The Controller orchestrates between the user and the model, retrieving data from the user's request and manipulating the model in response (e.g. creating objects, populating them with data, saving them to a database). In the case of Rails, ActionController (another part of the ActionPack library) is used to implement controllers. These controllers handle all requests from the user, talk to the model, and generate appropriate views.In the example script, the code which retrieves the submitted email address, is performing the controller role. A conditional statement is used to generate an appropriate response, dependent on whether an email address was supplied or not. In a traditional web application, the three broad classes of behavior described above are frequently mixed together. In a Rails application, these behaviors are separated out, so that a single layer of the application (the model, view, or controller) can be altered with minimal impact on the other layers. This gives a Rails application the right mix of modularity, fl exibility, and power. Next, we'll see another piece of what makes Rails so powerful: the idea of using conventions to create associations between models, views, and controllers. Once you can see how this works, the Rails implementation of MVC makes more sense: we'll return to that topic in the section Rails and MVC.
Read more
  • 0
  • 0
  • 3291
Modal Close icon
Modal Close icon