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-real-content-php5-cms-part-2
Packt
27 Oct 2009
8 min read
Save for later

Real Content in PHP5 CMS: Part 2

Packt
27 Oct 2009
8 min read
Framework solution To explore implementation details, we will look at an example that is simple enough to be shown in some detail. It is an application for handling pages composed largely of text and images. After studying the example, we will consider how the application could be made more advanced. A simple text application Here, we'll look at a component that can be used on its own but is also intended as a starting point for more sophisticated uses. Its essence is that it handles a piece of text, created using the site WYSIWYG editor by the administrator. The text can be displayed as the main portion of a Web page. Ancillary information is held about the text. Any particular text can be the target of a menu entry, so the component can be used for simple pages. The WYSIWYG editor provides for moderately complex text layout and the inclusion of images. We shall see that writing a text handling extension is made very much simpler by the various elements of the CMS framework. The database table for simple text After the ID number that is used as the main key we have the primary constituents of a piece of text. They are the headline, the subheading, and the body of the article. Each of these will simply reflect whatever text is put in them by the author, who in this simple implementation must also be an administrator. Next we have a couple of time stamps that can be automatically maintained by the software. Rather obviously, the created time stamp is set when the row is created, and the modified time stamp is set every time the row is updated. We then have fields that control the publication of the text. First, there is a simple indicator, which is set to zero if the text is not published and is set to one if it is published. When set to unpublished, the indicator overrides the start and end dates, if they are present. If a non-zero start date is set, then the text will not be published before that date. Likewise, if a non-zero finish date is set, the article will cease to be published after that date. Publishing dates are very useful to control when text will appear as it is often helpful to time the start of publication, and it creates a bad impression if obsolete text is not removed. Then we have data that describes who has worked on the text. The original creator is recorded as a user ID, and the last modifier is likewise recorded as a user ID. These fields are intended for tracking what is happening to the text rather than for display. On the other hand, the byline is entirely for display. Version is a character field that has no defined structure in this simple component, but could be elaborated in many different ways. Storage for metadata is provided as keys and description. This information is not for display on the browser page, but is used to generate meta information in the header of a page containing the text. Tags containing metadata can influence search engines used for indexing of pages, although description is much more influential than keywords, which are believed to be largely disregarded. Finally, a hit counter is automatically maintained by the system, being set initially to zero and then updated every time the text is shown to a site visitor. A text data object When a text item is loaded into memory from the database, a class provides for the definition of the object will be created. For the simple text application, the class is: class textItem extends aliroDatabaseRow { protected $DBclass = 'aliroDatabase'; protected $tableName = '#__simple_text'; protected $rowKey = 'id'; public function store ($updateNulls=false) { $userid = aliroUser::getInstance()->id; if ($this->id) { $this->modified = date('Y-m-d H:i:s'); $this->modify_id = $userid; } else { $ this->created = date('Y-m-d H:i:s'); $this->author_id = userid; } parent::store($updateNulls); } } Much of the hard work is done in the parent class, aliroDatabaseRow. Because the database framework derives information from the database itself, there is no need to specify the fields that are in the table, which makes it easier to cope with future changes. The minimum that has to be done is to specify the name of the singleton database class, the name of the table (using a symbol in place of the actual prefix), and to define the name of the primary key field. In this case, the store method is also extended. This provides an easy way to maintain the time stamps on the text. The current user is found through the aliroUser singleton class. We know whether a text row is new from whether it already has a value for id. The correct date and user field can then be updated. Finally, the standard store method in the parent class is invoked. Administering text items—controller The administrator logic for handling simple text follows the usual pattern of first providing a list of items, paged if necessary, then allowing more detailed access to individual items, including the ability to edit. Logic for overall control is provided by the aliroComponentAdminManager class, and the aliroComponentAdminControllers class. In fact, we could nominate in the packaging XML aliroComponentAdminManager as the adminclass for our component, since the dedicated textAdmin class does nothing: class textAdmin extends aliroComponentAdminManager { // This could be omitted - included here in case extra code needs to be added public function __construct ($component, $system, $version) { parent::__construct ($component, $system, $version); } // Likewise, this could be omitted unless extra code is needed public function activate () { parent::activate(); } } Why might we want to write a dedicated extension to aliroComponentAdminManager? Well, this is the common entry point for the administrator side of our component, so if we wanted any processing to exist that could affect every use of the component, this is the place to put it. The two possible locations are the constructor and the activation method. The constructor receives information from the CMS environment in the form of a component object (describing this component), the name of the system that is calling us, and its version. It is invoked as soon as the correct component has been determined. The standard processing in the aliroComponentAdminManager constructor includes creating the controller class, and acquiring some common variables from $_REQUEST. Once setup is completed, the activation method is invoked without any parameters. The activate method of the aliroComponentAdminManager class strips any magic quotes, and decides what method to call. Of course, the framework allows us to construct a component completely differently if we choose. The only constraint is that we must write a class whose name is given in the packaging XML, and provide it with an activate method. But usually it is a lot easier to follow the standard construction, and the bare bones of a new component can be built and downloaded online from http://developer.aliro.org. Nothing specific has been done yet, and we have to move into the controller code before we can find anything to do with handling text objects. The controller is subclassed from aliroComponentAdminControllers and starts off as shown: class textAdminText extends aliroComponentAdminControllers { private static $instance = null; // If no code is needed in the constructor, it can be omitted, relying on the parent class protected function __construct ($manager) { parent::__construct ($manager); } public static function getInstance ($manager) { return is_object(self::$instance) ? self::$instance : (self::$instance = new self ($manager)); } public function getRequestData () { // Get information from $_POST or $_GET or $_REQUEST // This method will be called before the toolbar method } // If this method is provided, it should return true if permission test is satisfied, false otherwise public function checkPermission () { $authoriser = aliroAuthoriser::getInstance(); if ($test = $authoriser->checkUserPermission('manage', 'aSimpleText', '*')) { if (!$this->idparm) return true; if ($authoriser->checkUserPermission('edit', 'aSimpleText', $this->idparm)) return true; } return false; } Here, the constructor is not needed; it is shown only to indicate the possibility of having code at the point the controller object is created. The constructor receives the manager object as a parameter, in this case an instance of textAdmin, a subclass of aliroComponentAdminManager. The controller is a singleton class, and here a form of the getInstance method is shown that can be used completely unchanged from component to component. Then we have two methods that are standard. Neither has to be provided, and in this case, the getRequestData method is not needed since it does nothing. Its purpose is to run early on (it is called before the toolbar processing and well before the processing specific to the current request) to acquire information from $_REQUEST or $_GET or $_PUT (or possibly other super-globals). They can be saved as object properties so as to be available for toolbar construction or other processing. The checkPermission method provides the component with a way to easily control who is able to access its facilities. If the method returns true then the user will be allowed to continue, but if it returns false, they will be refused access. In this example, there is always a check that the user is permitted to manage objects of the type aSimpleText and if a specific one is identified by its ID, then there is a further check that the user is permitted to edit that particular text item.
Read more
  • 0
  • 0
  • 1832

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

Creating a VB.NET application with EnterpriseDB

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

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

Managing Student Work using Moodle: Part 2

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

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

Managing Student Work using Moodle: Part 1

Packt
27 Oct 2009
8 min read
In this article, we take a turn from work I hand out to students to look at how to manage online work that they hand to me. Currently, in my Backyard Ballistics course, I set two major end-of-course projects: A poster on energy sources A PowerPoint presentation to the group on how energy is transferred when objects are sent flying through the air Both tasks are graded separately. For me, the final project has always been a major headache: PowerPoint presentations go missing. Students claim they have emailed me files that never reach me. The school technician is wary of students bringing in work on memory sticks because of the threat of viruses. Marking the posters involves me having to make notes on paper, and having a system to associate those notes with digital photographs of the posters stored elsewhere. I want a system that allows me to manage student submissions in one self-contained tool—one that can be used to exchange files between my students and me without having to resort to other, far less reliable, means. Also, wouldn't it be good to have a tool that allows us to comment (and include photographs, videos—in fact any digital file we liked) and grade work all under one umbrella? Added to that, my course specification also demands that I grade students on key skills: numeracy, literacy, and the use of ICT. And that's not something I specifically set a project for. I need a way of grading students on those aspects of their work separate from any specific project. That's another headache. That may seem like a lot to worry about, but (as you've probably already heard) by converting to Moodle, we can easily find answers to all of these issues, and more. So let's get on with it, and make a start with converting my poster project and PowerPoint assignments to Moodle... Converting Projects and Assignments Moodle provides four types of assignment activity, and they well match any kind of project that you are likely to set for your students. Turn editing on, go to any topic, and click on the Add an activity list. In this list, you will see the four different assignment types Moodle supports. They are: Offline activity—If your student projects can't be uploaded into Moodle because the student submission isn't electronic (just like my poster project), then you can manage grades and your notes on the students' work using this kind of assignment type. Online text—Students are going to be creating the assignment submission using the text editor built into Moodle. That's the one we've been using to create our course so far. Upload a single file—Does what it says on the tin. Students can only upload one file. Advanced uploading of files—Students can upload more than one file. As a teacher, you can also use Moodle as a mechanism for exchanging files between students, instead of using email (unreliable) or a memory stick (virus risk). Don't be afraid to have a look at these assignment types now. With editing turned on, click on Add an activity... and select any of the assignment types. That way you can get a feel for the kinds of settings we'll be dealing with before we start. Remember: if, while you are trying out different assignment types, you mistakenly add an assignment to your course, you can easily delete it by clicking on the delete icon next to the assignment name. How to Structure Converted Projects and Assignments Online For larger projects or assignments, it is often preferable to have a self-contained topic containing the actual assignment itself, together with any supporting materials. You could include exemplars (e.g. work from previous years) and give students the opportunity to discuss them together. Having the assignment, and all of the supporting materials, in a single topic means I can hide the assignment from students until it is time for them to attempt it. To demonstrate how this would be done, firstly we need to add a new topic to our course, and then we can add in an assignment activity... Adding a New Topic to a Course I'm going to add a new topic to my course specifically for my student projects. Then, I'm going to hide that topic until we have covered the course. I'm going to do the same with my projects and the support materials associated with them. You don't have to treat assignments in this way: as you work through the settings for a Moodle assignment, you'll notice that you can specify a time period that those assignments are available for (it's a setting we'll talk about shortly). I've decided that I want to ensure that my students focus on the preliminary work before they start attempting any assignments by completely hiding them from students. Time for Action – Add a Topic to a Course and Hide It Return to your course front page and choose Settings from the Administration block. Scroll down to the number of weeks/topics setting and change the number in the drop down-list to add another topic to your course: At the bottom of the page, press the Save changes button. That's it, we're done—and now there's a new empty topic at the end of your course. For the moment, I want to hide this topic from students. Click on the eye icon on the right-hand side to hide the topic: It depends on your theme but, to show that a topic is hidden, two grey bars are shown on the left- and right-hand sides of the topic: What Just Happened? We've now got a new, empty topic added to our course. I don't want students to be able to view the assignment until we are all ready, so I've hidden this topic from them for now. Which Assignment Type? For the purpose of my project I'm only going to be looking at two different assignment activity types—but by looking at those two we'll gain the skills and confidence to be able to use all four quite happily. Converting a Project to Moodle Example 1 – Using an Offline Assignment The first project—the poster project—is going to be converted to use the Offline activity assignment type. I'm going to use Moodle to manage student grades and to organize my notes and comments on their work. Let's see how easy it is to add an Offline activity... Time for Action – Add an Offline Activity Assignment Make sure you still have editing turned on. In the topic you want to add your new assignment to (in my case my new, hidden topic) click on Add an activity... and choose Offline activity from the list. You're now taken to the Editing assignment page. Give your assignment a name. Enter in a brief description of the task in the Description box. Don't worry if the box looks a bit small. We can include all of the supporting materials in the topic together with the assignment activity itself on the course front page: Use the Grade setting to specify the maximum grade you are going to give for this assignment. I'm going to leave the Grade setting at 100 (meaning I can grade this assignment out of 100). Maybe your assignment forms part of an overall mark and you need to mark it out of less. You could choose to mark your assignment in this way. You can even choose to create your own custom grades (e.g. A, B, C, D, E, or F), which we learn how to do later on in this article. Choose when you want the assignment to be available. I want to hide both the assignment and the supporting resources and materials, so this option is redundant. I do have the option of disabling this setting so this is what I'm going to do, in this instance. If you aren't hiding the assignment, the Available from and Due date settings are a useful way of preventing students handing work to you before you are ready: That's it! We're done. Press the Save and return to course button. A new assignment has just been added to the course: What Just Happened? Converting my poster project to Moodle was as easy as adding an Offline assignment activity to my Backyard Ballistics course. Click on the assignment now to see what happens. You'll see a screen displaying the task you've just set, and in the top right-hand corner you'll see a No attempts have been made on this assignment link: Click on that link now. You'll be taken to a list of students who are enrolled on your course. If you don't have any students enrolled on your course, then this is what you will see: I don't yet want students enrolled on my course until I know it is set up to be just how I want it. The solution is to introduce a "control student" on our course, and later in this article we'll see how. Before we do that, I'm going to think about the second assignment I need to convert—where students are required to produce a PowerPoint presentation.
Read more
  • 0
  • 0
  • 1538

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

Understanding the Model Development Process in IBM Cognos 8

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

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

Creating a Shopping Cart using Zend Framework: Part 1

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

Building the User Portal with SerMyAdmin for OpenSER

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

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

New SOA Capabilities in BizTalk Server 2009: UDDI Services

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

article-image-creating-dialplan-asterisk-16-part-1
Packt
27 Oct 2009
12 min read
Save for later

Creating a Dialplan in Asterisk 1.6: Part 1

Packt
27 Oct 2009
12 min read
When calls come into the switch, we tell Asterisk step-by-step how to handle the call. Steps can be as simple as playing a sound file to running a customized script. We are limited mostly by our imaginations at this point. We define all the steps we want Asterisk to perform in our extensions.conf file, in the customary location /etc/asterisk. Before we begin, we need to set priorityjumping=yes in the [general] section of extensions.conf. This will allow the tips and tricks in this article to work with Asterisk 1.6.x. Creating a context What is a context? Simply said, a context is a group of extensions. Each extension must exist within a context. There is more to contexts than grouping extensions though. In our extensions.conf file (or any included files), a context is denoted by square brackets "[ ]", as shown: [mycontext]. . . So, if a context is a group of extensions, why do we need more than one? Let's think for a minute. Not all employees should be able to dial every phone. Would you trust your 16-year-old intern with the ability to dial international calls? I wouldn't. Also, do you want your president to be bothered by customers in the waiting room who use a courtesy phone and misdial? We could find that hazardous to our continued employment. Certain extensions are hidden or made inaccessible from other extensions by context. This gives us some level of security. It also allows us to host multiple phone systems on a single server. Imagine you have two businesses on the same phone system, each with only two handsets. It'd be a pain to have each dial four digits to reach the other handset. We can use contexts to treat each company as if it were on a separate server. Something very important about contexts is we can include other contexts through the use of the include directive. This means all extensions in an included context are available. The value of this may not be immediately apparent, but soon we will see the full power of this tool. Suppose we have some context named bob. If we wanted bob to include default, then we would have the following in our extensions.conf: [bob]include => default This single line placed in any context gives that context the ability to dial any extension in the default context, as well as all contexts included in the default context. This means that if the default context included the foo context, then anybody in the bob context could dial extensions in the foo context. Suppose we had the following in our extensions.conf file: [foo]exten => 1,1,Playback(tt-monkeys)include => bar[bar]exten => 1,1,Playback(tt-weasels) Now I know that we haven't yet discussed the definition of extensions. That's OK. All we need to know is that extension 1 in foo will play back a file that sounds like monkeys, and extension 1 in bar will play back a file that says, "weasels have taken over our phone system". If we are in context foo and press 1, which file will play? This shows us the danger of include. We should be careful not to include multiple matches for the same extension. If we do include multiple contexts, the first included context with a match will win. Consider the following file: [foobar1]include => fooinclude => bar[foobar2]include => barinclude => foo If we are in context foobar1 and press 1, we will hear monkeys, while if we are in context foobar2 and press 1, we will hear weasels. While this can trip the unwary, we will use it to our advantage later on. Creating an extension We all have a good idea about what an extension is. On our legacy PBX, each handset was an extension. Pretty simple, right? While conceptually simple, there is a little wrinkle. If all we want to do is provide a few handsets, then there's one extension per phone. But Asterisk can do much more! We need to think of an extension as a group of commands that tells Asterisk to do some things. As amorphous as that may be, it's true. An extension can be tied to one handset, a queue, groups of handsets, or voicemail. An extension can be attributed to many different areas of the system. If you're familiar with programming terms, perhaps you could say that extensions are polymorphic. To go further, extensions can be used to provide access to other applications, sound files, or other services of Asterisk. Extensions are important to the magic of Asterisk. Now that we know why we create extensions, let's think about how we create them. Again, they are in the extensions.conf file, or any files that you include from there. We may decide to break up files such as extensions.conf into multiple configuration files. A common example of this is when we create large groups of extensions and choose to give each its own file. This also applies to the other configuration files we use. The general format for a line in the extensions.conf file is: exten => extensionnum,priority,action Let's take a closer look. Each line begins with the command exten. This is a directive inside Asterisk. You do not change this for each extension. Next, we have the extension number. Each extension has a unique number. This number is how Asterisk knows which set of commands to run. This extension can be detected in three major ways. First, the phone company may send it in with the calls, as is the case with DID numbers. Users can enter an extension using their touch-tone keys. Finally, there are a few special extensions defined. Some of these are: s: start extension. If no other extension number is entered, then this is the extension to execute. t: timeout extension. If a user is required to give input, but does not do so quickly enough, this is the extension that will be executed. i: invalid extension . If a user enters an extension that is not valid, this is the extension that will be executed. fax: fax calls. If Asterisk detects a fax, the call will be rerouted to this extension. Then we have the priority. Asterisk will start at priority 1 by default, complete the requested command, and then proceed to priority n+1. Some commands can force Asterisk to jump to priority n+101, allowing us to route based on decisions, such as if the phone is busy. Finally, we have the action. This is where we tell Asterisk what we want to do. Some of the more common actions we may want to perform are: Answer: This accepts the call. Many applications require that the call be answered before they can run as expected. Playback(filename): This command plays a file in .wav or .gsm format. It is important to note that the call must be answered before playing. Background(filename): This command is like Playback, except that it listens for input from the user. It too requires that the call be answered first. Goto(context,extension,priority): Here, we send the call to the specified context, extension, and priority. While useful, this can be a bad style, as it can be very confusing to us if something goes wrong. However, it can be a good style if it keeps us from duplicating extension definitions, as moves, adds, or changes would only have to be updated in one place. Queue(queuename|options): This command does what it seems like it should. It places the current call in the queue, which we should have already defined in the queues.conf file. Voicemail(extension): This transfers the current call to the voicemail application. There are some special options as well. If we preceed the extension with the letter s, it skips the greeting. When we place the letter u before the extension, it uses the unavailable greeting, and b uses the busy greeting. VoicemailMain: This application allows users to listen to their messages, and also record their greetings and name, and set other configuration options. Dial(technology/id,options,timeout): This is where we tell Asterisk to make the phone ring, and when the line is answered, to bridge the call. Common options include: t: Allow the called user to transfer the call by pressing the # key. T: Allow the calling user to transfer the call by pressing the # key. r: Indicate ringing to the calling party. m: Provide music on hold to the calling party. H: Allow the calling party to hang up by pressing the * key. g: Go on in the context if the destination hangs up. While this list is not exhaustive, it should be enough to get us started. Suppose we just want to make a DAHDI phone ring, which is on interface 1, and we are going to work completely in the default context. Our extensions.conf file would look like: [default]exten => s,1,Dial(dahdi/1) Pretty simple, right? Now, imagine we want to transfer to the voicemail of user 100 if someone is on the phone. As Dial sends you to priority n+101 when the line is busy or not available, all we have to do is define what we want to do. Our dialplan would look like: [default]exten => s,1,Dial(dahdi/1)exten => s,102,Voicemail(b100) Great! We have some of the functionality that users have come to expect. But are you happy yet? The problem is that a phone could ring for years before someone picks it up. So, for our next exercise, suppose we want to transfer the call to voicemail when the phone is not answered in 30 seconds. So, obviously, we're going to have to use the option in Dial to define a time-out. Our dialplan would have something like: [default]exten => s,1,Dial(dahdi/1|30)exten => s,2,Voicemail(u100)exten => s,102,Voicemail(b100) All we're doing is telling Asterisk how to handle the call, in a step-by-step way. It is important to think about all scenarios that a call can go through, and plan for them. Just to reiterate a point I made earlier, planning ahead will save us hours of debugging later. Suppose we want to send anyone who is in a place where they shouldn't be to user 0's voicemail, which will be checked periodically by the receptionist. [default]exten => s,1,Dial(dahdi/1|30)exten => s,2,Voicemail(u100)exten => s,102,Voicemail(b100)exten => i,1,Voicemail(s0)exten => t,1,Voicemail(s0) All right, we're getting somewhere now! At least we know each call will be handled in some way. What about faxes? Suppose we have only one fax machine (or a centralized fax server) on DAHDI interface 2, then our dialplan should look similar to: [default]exten => s,1,Dial(dahdi/1|30)exten => s,2,Voicemail(u100)exten => s,102,Voicemail(b100)exten => i,1,Voicemail(s0)exten => t,1,Voicemail(s0)exten => fax,1,Dial(dahdi/2) Congratulations! We now have a working phone system. May be not the most interesting yet, but we're making great progress. Don't worry, our phone system will grow in features. Now, to create a list of useful extensions, we need to define a set of commands for each handset we have. Suppose we have three SIP phone users—1001-1003, with extensions 1001-1003. Our default context would look like: [default]exten => 1001,1,Dial(SIP/1001|30)exten => 1001,2,Voicemail(u1001)exten => 1001,102,Voicemail(b1001)exten => 1002,1,Dial(SIP/1002|30)exten => 1002,2,Voicemail(u1002)exten => 1002,102,Voicemail(b1002)exten => 1003,1,Dial(SIP/1003|30)exten => 1003,2,Voicemail(u1003)exten => 1003,102,Voicemail(b1003)exten => i,1,Voicemail(s0)exten => t,1,Voicemail(s0)exten => fax,1,Dial(dahdi/2) For every extension we add, the length of extensions.conf will grow by four lines (three lines of code, and one line of whitespace). This is not very easy to read, and it is very easy to make mistakes. There has to be a better way, right? Of course there is! We can use macros to define common actions. We will create a special macro context. The name of these contexts always starts with macro-. Suppose we want to call this one macro-normal. We would have: [macro-normal]exten => s,1,Dial(${ARG2}|30)exten => s,2,Voicemail(u${ARG1})exten => s,102,Voicemail(b${ARG1}) Now, to create the same three extensions, we would have: exten => 1001,1,Macro(normal|1001|SIP/1001)exten => 1002,1,Macro(normal|1002|SIP/1002)exten => 1003,1,Macro(normal|1003|SIP/1003) So now, each extension we add requires only one extra line in extensions.conf. This is much more efficient and less prone to errors. But what if we knew that any four-digit extension beginning with a 1 would be a normal, SIP extension? Here it is time for us to discuss Asterisk's powerful pattern-matching capabilities. We can define extensions with certain special wildcards in them, and Asterisk will match any extension that fits the description. Using the underscore (_) character warns Asterisk that the extension number will include pattern matching. When matching patterns, the X character represents any number (0 to 9), the Z character will match the numbers 1 to 9, the N character represents numbers 2 to 9, and the period (.) represents a string of any number of digits. Also, we can use certain variables in our dialplan. One such variable is ${EXTEN}, which represents the extension that was used. So, for this example, we could use the following definition: exten => _1XXX,1,Macro(normal|${EXTEN}|SIP/${EXTEN}) This one line of code has now defined 1000 extensions, from 1000 to 1999. All we have to do is ensure that our voicemail user, extension, and SIP user are all the same number. Pretty cool, huh? Note that if we wish to modify the behavior of all extensions, all we have to do is modify the macro. This should help us quite a bit as we tweak Asterisk to fit our business needs.
Read more
  • 0
  • 0
  • 6453

article-image-real-content-php5-cms-part-3
Packt
27 Oct 2009
8 min read
Save for later

Real Content in PHP5 CMS: Part 3

Packt
27 Oct 2009
8 min read
Administering text items—viewer Generating the XHTML is handled in a separate class, thus implementing the principles of the MVC pattern. The viewer class constructor establishes strings for translation in a way that will allow them to be picked up by gettext, as well as invoking the constructor in the parent class basicAdminHTML, which will provide useful methods and also transfer information such as the page navigation object from the controller object passed as a parameter: class listTextHTML extends basicAdminHTML { public function __construct ($controller) { parent::__construct($controller); $lang_strings = array(T_('Simple Text'),T_('Title'), T_('Byline'),T_('Version'), T_('Publishing'),T_('Published'), T_('Start date'),T_('End date'), T_('Article text'),T_('Metadata'), T_('Keys'),T_('Description'), T_('Hits'),T_('ID')); $this->translations = array_combine( $lang_strings, $lang_strings); } The actual display of a list of text items is then quite simple, involving the creation of a heading first, followed by a loop through the text items, and then some final XHTML including hidden fields that allow for effective navigation. Note that the parent class will have set up $this->optionurl and $this->optionline to help in the construction of links within the component and a hidden variable to identify the component respectively. public function view ($rows) { $mainhtml = $this->listview($rows); echo <<<ALL_HTML $mainhtml <div> <input type="hidden" name="task" value="" /> $this->optionline <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="hidemainmenu" value="0" /> </div>ALL_HTML; } The view method does very little, relying on the listview method for most of the work, and only adding hidden fields needed to ensure that navigation and the toolbar will work correctly. Note that the parent class helps us by setting $this->optionline with a hidden input field for the critical option variable needed to ensure the correct component is invoked when the form is submitted. Actual XHTML form tags are created by the CMS framework so that every administrator page is a form. The reason for splitting the page creation in this way will become apparent later, when we look at menu creation. So, moving on to the listview method, we find quite a lot of simple code, which is mainly just a definition of the page in XHTML. The second and third parameters will be set differently from their default values when we come to menu creation. public function listview ($rows, $showlinks=true, $subhead='') { $rowcount = count($rows); $html = <<<ADMIN_HEADER {$this->header($subhead)} <table class="adminlist" width="100%"> <thead> <tr> <th width="3%" class="title"> <input type="checkbox" name="toggle" value="" onclick="checkAll($rowcount);" /> </th> <th> {$this->T_('ID')} </th> <th width="50%" class="title"> {$this->T_('Title')} </th> <th> {$this->T_('Byline')} </th> <th> {$this->T_('Hits')} </th> <th align="left"> {$this->T_('Published')} </th> </tr> </thead> <tbody>ADMIN_HEADER; $i = $k = 0; foreach ($rows as $i=>$row) { if ($showlinks) $title = <<<LINK_TITLE <a href="{$this->optionurl}&amp;task=edit&amp; id=$row->id">$row->title</a>LINK_TITLE; else $title = $row->title; $html .= <<<END_OF_BODY_HTML <tr class="row$k"> <td> {$this->html('idBox', $i, $row->id)} </td> <td align="center"> $row->id </td> <td> $title </td> <td> $row->byline </td> <td align="center"> $row->hits </td> <td align="center"> {$this->html('publishedProcessing', $row, $i )} </td> </tr>END_OF_BODY_HTML; $i++; $k = 1 - $k; } if (0 == $rowcount) $html .= <<<NO_ITEMS_HTML <tr><td colspan="6" class="center"> {$this->T_('No items')} </td></tr>NO_ITEMS_HTML; $html .= <<<END_OF_FINAL_HTML </tbody> </table> {$this->pageNav->getListFooter()}END_OF_FINAL_HTML; return $html; } When it comes to adding a new item or editing an existing one, no looping is required, and the WYSIWYG editor is activated to provide a helpful interface for the administrator who is editing a text item. Note that the use of PHP heredoc allows the XHTML to be written out quite plainly, with the PHP insertions unobtrusive but effective. Actual text for translation is shown in its correct place (in the base language) by using the T_ method that is inherited from aliroBasicHTML via basicAdminHTML. public function edit ($text) { $subhead = $text->id ? 'ID='.$text->id : T_('New'); $editor = aliroEditor::getInstance(); echo <<<EDIT_HTML {$this->header($subhead)} <div id="simpletext1"> <div> <label for="title">{$this->T_('Title')}</label><br /> <input type="text" name="title" id="title" size="80" value="$text->title" /> </div> <div> <label for="byline">{$this->T_('Byline')}</label><br /> <input type="text" name="byline" id="byline" size="80" value="$text->byline" /> </div> <div> <label for="version">{$this->T_('Version')}</label><br /> <input type="text" name="version" id="version" size="80" value="$text->version" /> </div> <div> <label for="article">{$this->T_('Article text')}</label><br /> {$editor->editorAreaText( 'article', $text->article, 'article', 500, 200, 80, 15 )} </div> </div> <div id="simpletext2"> <fieldset> <legend>{$this->T_('Publishing')}</legend> <div> <label for="published">{$this->T_('Published')}</label><br /> <input type="checkbox" name="published" id="published" value="1" {$this->checkedIfTrue($text->published)} /> </div> <div> <label for="publishstart">{$this->T_('Start date')}</label><br /> <input type="text" name="publish_start" id="publishstart" size="20" value="$text->publish_start" /> </div> <div> <label for="publishend">{$this->T_('End date')}</label><br /> <input type="text" name="publish_end" id="publishend" size="20" value="$text->publish_end" /> </div> </fieldset> <fieldset> <legend>{$this->T_('Metadata')}</legend> <div> <label for="metakey">{$this->T_('Keys')}</label><br /> <textarea name="metakey" id="metakey" rows="4" cols="40">$text->metakey</textarea> </div> <div> <label for="metadesc">{$this->T_('Description')}</label><br /> <textarea name="metadesc" id="metadesc" rows="4" cols="40">$text->metadesc</textarea> </div> </fieldset> <input type="hidden" name="task" value="" /> $this->optionline </div> <div id="simpletext3"> <input type="hidden" name="id" value="$text->id" /> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="hidemainmenu" value="0" /> </div>EDIT_HTML; } Finally, there is a common method to deal with the creation of the heading. It uses the addCSS method provided by the parent class to link to a small amount of CSS that is held in a separate file. Although the list of text items defined in the XHTML above is perfectly legitimate as a table, since it really is a tabular structure, the heading would be better built out of other XHTML elements. The only reason for using a table here is that it is one of the features retained from earlier systems for the sake of backwards compatibility: private function header ($subhead='') { $this->addCSS(_ALIRO_ADMIN_DIR.'/components /com_text/admin.text.css'); if ($subhead) $subhead = "<small>[$subhead]</small>"; return <<<HEAD_HTML <table class="adminheading"> <tr> <th class="user"> {$this->T_('Simple Text')} $subhead </th> </tr> </table>HEAD_HTML; } }
Read more
  • 0
  • 0
  • 2309
article-image-customizing-elgg-themes
Packt
27 Oct 2009
8 min read
Save for later

Customizing Elgg Themes

Packt
27 Oct 2009
8 min read
Why Customize? Elgg ships with a professional looking and slick grayish-blue default theme. Depending on how you want to use Elgg, you'd like your network to have a personalized look. If you are using the network for your own personal use, you really don't care a lot about how it looks. But if you are using the network as part of your existing online infrastructure, would you really want it to look like every other default Elgg installation on the planet? Of course not! Visitors to your network should easily identify your network and relate it to you. But theming isn't just about glitter. If you thought themes were all about gloss, think again. A theme helps you brand your network. As the underlying technology is the same, a theme is what really separates your network from the others out there. What Makes Up a Theme? There are several components that define your network. Let's take a look at the main components and some practices to follow while using them. Colors: Colors are an important part of your website's identity. If you have an existing website, you'd want your Elgg network to have the same family of colors as your main website. If the two (your website and social network) are very different, the changeover from one to another could be jarring. While this isn't necessary, maintaining color consistency is a good practice. Graphics: Graphics help you brand the network to make it your own. Every institution has a logo. Using a logo in your Elgg theme is probably the most basic change you'd want to make. But make sure the logo blends in with the theme, that is, it has the same background color. Code: It takes a little bit of HTML, a sprinkle of PHP, and some CSS magic to Code: It takes a little bit of HTML, a sprinkle of PHP, and some CSS magic to manipulate and control a theme. A CSS file: As the name suggests, this file contains all the CSS decorations. You can choose to alter colors and fonts and other elements in this file. A Pageshell file: In this pageshell file, you define the structure of your Elgg network. If you want to change the position of the Search bar or instead of the standard two-column format, move to a three-column display, this is the file you need to modify. Front page files: Two files control how the landing page of your Elgg network appears to logged out or logged in users. Optional images folder: This folder houses all the logos and other artwork that'll be directly used by the theme. Please note that this folder does not include any other graphic elements we've covered in previous tutorials such as your picture, or icons to communities, and so on. Controlling Themes Rather than being single humongous files, themes in Elgg are a bunch of small manageable files. The CSS decoration is separated from the placement code. Before getting our hands dirty creating a theme, let's take a look at the files that control the look and feel of your network. All themes must have these files: The Default Template Elgg ships with a default template that you can find under your Elgg installation. This is the structure of the files and folders that make up the default template. Before we look at the individual files and examine their contents in detail, let's first understand their content in general. All three files, pageshell, frontpage_logedin, and frontpage_loggedout are made up of two types of components. Keywords are used to pull content from the database and display them on the page. Arranging these keywords are the div<.em> and span tags along with several others like h1, ul, and so on that have been defined in the CSS file. What are <div> and <span>? The <div> and <span> are two very important tags especially when it comes to handling CSS files. In a snap, these two tags are used to style arbitrary sections of HTML. <div> does much the same thing as a paragraph tag <p>, but it divides the page up into larger sections. With <div>, you can also define the style of whole sections of HTML. This is especially useful when you want to give particular sections a different style from the surrounding text. The <span> tag is similar to the <div> tag. It is also used to change the style of the text it encloses. The difference between <span> and <div> is that a span element is in-line and usually used for a small chunk of in-line HTML. Both <div> and <span> work with two important attributes, class and id. The most common use of these containers together with the class or id attributes is when this is done with CSS to apply layout, color, and other presentation attributes to the page's content. In forthcoming sections, we'll see how the two container items use their two attributes to influence themes. The pageshell Now, let's dive into understanding the themes. Here's an exact replica of the pageshell of the Default template. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head><title>{{title}}</title> {{metatags}}</head> <body>{{toolbar}} <div id="container"><!-- open container which wraps the header, maincontent and sidebar --><div id="header"><!-- open div header --><div id="header-inner"> <div id="logo"><!-- open div logo --> <h1><a href="{{url}}">{{sitename}}</a></h1> <h2>{{tagline}}</h2> </div><!-- close div logo --> {{searchbox}}</div> </div><!-- close div header --> <div id="content-holder"><!-- open content-holder div --><div id="content-holder-inner"> <div id="splitpane-sidebar"><!-- open splitpane-sidebar div --> <ul><!-- open sidebar lists --> {{sidebar}} </ul><!-- close sidebar lists --></div><!-- close splitpane-sidebar div --> <div id="splitpane-content"><!-- open splitpane-content div --> {{messageshell}} {{mainbody}}</div><!-- close open splitpane-content div --></div> </div><!-- close content-holder div --> <div id="footer"><!-- start footer --><div id="footer-inner"><span style="color:#FF934B">{{sitename}}</span> <a href="{{url}}content/terms.php">Terms and conditions</a> | <a href="{{url}}content/privacy.php">Privacy Policy</a><br /><a href="http://elgg.org/"><img src="{{url}}mod/template/ icons/elgg_powered.png" title="Elgg powered" border="0" alt="Elgg powered"/></a><br /> {{perf}}</div> </div><!-- end footer --> </div><!-- close container div --> </body> </html> CSS Elements in the pageshell Phew! That's a lot of mumbo-jumbo. But wait a second! Don't jump to a conclusion! Browse through this section, where we disassemble the file into easy-to-understand chunks. First, we'll go over the elements that control the layout of the pageshell. <div id="container">: This container wraps the complete page and all its elements, including the header, main content, and sidebar. In the CSS file, this is defined as: div#container {width:940px;margin:0 auto;padding:0;background:#fff;border-top:1px solid #fff;} <div id="header">: This houses all the header content including the logo and search box. The CSS definition for the header element: div#header {margin:0;padding:0;text-align:left;background:url({{url}}mod/template/templates/Default_Template/images/header-bg.gif) repeat-x;position:relative;width:100%;height:120px;} The CSS definition for the logo: div#header #logo{margin: 0px;padding:10px;float:left;} The search box is controlled by the search-header element: div#header #search-header {float:right;background:url({{url}}mod/template/templates/Default_Template/images/search_icon.gif) no-repeat left top;width:330px;margin:0;padding:0;position:absolute;top:10px;right:0;} <div id="header-inner">: While the CSS file of the default template doesn't define the header-inner element, you can use it to control the area allowed to the elements in the header. When this element isn't defined, the logo and search box take up the full area of the header. But if you want padding in the header around all the elements it houses, specify that using this element. <div id="content-holder">: This wraps the main content area. #content-holder {padding:0px;margin:0px;width:100%;min-height:500px;overflow:hidden;position:relative;} <div id="splitpane-sidebar">: In the default theme, the main content area has a two-column layout, split between the content and the sidebar area. div#splitpane-sidebar {width: 220px;margin:0;padding:0;background:#fff url({{url}}mod/template/templates/Default_Template/images/side-back.gif) repeat-y;margin:0;float: right;}div#splitpane-content {margin: 0;padding: 0 0 0 10px;width:690px;text-align: left;color:#000;overflow:hidden;min-height:500px;} <div id="single-page">: While not used in the Default template, the content area can also have a simple single page layout, without the sidebar. div#single-page {margin: 0;padding: 0 15px 0 0;width:900px;text-align: left;border:1px solid #eee;} <div id="content-holder-inner">: Just like header-inner, is used only if you would like a full page layout but a defined width for the actual content. <div id="footer">: Wraps the footer of the page including the links to the terms and conditions and the privacy policy, along with the Elgg powered icon. div#footer {clear: both;position: relative;background:url({{url}}mod/template/templates/Default_Template/images/footer.gif) repeat-x top;text-align: center;padding:10px 0 0 0;font-size:1em;height:80px;margin:0;color:#fff;width:100%;} <div id="footer-inner">: Like the other inner elements, this is only used if you would like a full page layout but restrict the width for the actual footer content.
Read more
  • 0
  • 101
  • 124765

article-image-adding-worksheets-and-resources-moodle
Packt
27 Oct 2009
12 min read
Save for later

Adding Worksheets and Resources with Moodle

Packt
27 Oct 2009
12 min read
We're teaching the topic of Rivers and Flooding; so to start with, we'll need to introduce our class to some basic facts about rivers and how they work. We aren't going to generate any new stuff yet; we're just going to upload to Moodle what we have already produced in previous years. Putting a worksheet on Moodle The way Moodle works is that we must first upload our worksheet into the course file storage area. Then, in that central section of our course page, we make a link to the worksheet from some appropriately chosen words. Our students click on these words to get to the worksheet. We've got an introductory factsheet (done in Word) about the River Thames. Let's get it into Moodle: Time for action-uploading a factsheet on to Moodle We need to get the worksheet uploaded into Moodle. To get this done, we have to follow a few simple steps. Go to your course page and click on the Turn editing on button, as shown in the following screenshot: Don't worry about all of the new symbols (icons) that appear. In the section you want the worksheet to be displayed, so look for these two boxes: Click on the Add a resource box (I'll go through all its options when we have a recap, later). Select a link to a file or web site. In Name, type the text that you want the students to click on, and in Summary (if you want) add a short description. The following screenshot gives an example of this: Once you're done with the above steps, click on Choose or upload a file. This takes you to the course files storage area. Click on Make a folder, and in the dialog box that is displayed, choose a suitable name for the folder all your worksheets will be stored in (we'll use Worksheets). Click on Create. Click on the folder that you just created (It will be empty except for Parent Folder, which takes you back to the main course files). Click on Upload a file. You'll be prompted to browse your computer's hard drive for the worksheet. Find the worksheet, select it with your cursor and click Open. It will appear as shown in the following screenshot: Click Upload this file. Once the file has been uploaded, it will appear as shown in the following screenshot: What just happened? We just uploaded our first ever worksheet to Moodle. It's now in the course files. Next, we need to make a link on the page that students can click on to get to that worksheet. I know what you're thinking! Thirteen steps, and there's still no sign of our River Thames worksheet on the course page in Moodle. Is it going to be this long-winded every time? Don't worry! There are only two—at worst three—steps left . And although it seems to be a lot of effort the first time, it gets much quicker, as we move on. We are also trying to be organized from the start by putting our worksheets neatly into a folder, so we took a couple of extra steps that we won't have to do next time. The folder will already be there for us. Ofcourse, you can just click on Upload a file and get your worksheets straight into the course files without any sort of order, and they will display for your students just as well. But when you have a lot of worksheets loaded, it will become harder and harder to locate them unless you have a system. Time for action-displaying our factsheet on our course page To get the Moodle course started, we need to create a link that—when clicked, will get the course started, carrying on from where we left off : Click on the word Choose to the right of your worksheet. (We are choosing to put this on Moodle.) The River Thames worksheet now shows in the Location box, under Link to a file or web site. We are almost there! Scroll down and make sure that you have selected the New window option in theWindow box, as shown in the following screenshot: At the bottom of the screen, click on Save and return to course. Done! The option Search for web page would take you to Google or another search engine to find a web site. You could put that web site into the location box instead, and it would make a clickable link for your students to follow. What just happened? Congratulations! You’ve now made a link to the factsheet about the River Thames that will get our Rivers and Flooding course started! By doing the final step above, we will get taken back to the course page where we'll see the words that we wrote in the Name box. They'll be in blue with a line underneath. This tells us it's a clickable link that will take us to the factsheet. If you can do that once, you can do it many times. Have a go hero-putting a slideshow onto Moodle It's important to go through the steps again, pretty quickly, so that you become familiar with them and are able to speed the process up. So why not take one of your slide shows (maybe done in PowerPoint) and upload that to Moodle? Start by creating a folder called Slideshows, so that in future, it will be available for any slideshows that you upload. Or, if you're too tired, just upload another sheet into our Worksheets folder and display that.   Putting a week's worth of slideshows into Moodle Now let's suppose that we have already prepared a week's worth of slideshows. Actually, I could say, a month's worth of worksheets, or a year's worth of exam papers. Basically, what we're going to do is upload several items, all at once. This is very useful because once you get used to uploading and displaying worksheets, you will very quickly start thinking about how tedious it would be, to put them on Moodle one at a time. Especially if you are studying ten major world rivers, and you have to go through all of those steps ten times. Well, you don't! Let's use my River Processes slideshows as our example. I have them saved in a folder on My Computer (as opposed to being shoved at random in a drawer, obviously!). Under normal circumstances, Moodle won't let you upload whole folders just like that. You have to either compress or zip them first (that basically means squeeze it up a bit, so it slides into cyberspace more smoothly). We first need to leave Moodle for a while and go to our own computer. I'm using Windows; for Macs, it will be slightly different. Time for action-getting a whole folder of work into Moodle in one go To view the slideshows, we need to upload the folder containing them from the hard drive of our computer into Moodle. Find the folder that you want to upload, right-click on it, and select Compressed (zipped) Folder within the Send To option. You'll get another folder with the same name, but in ZIP format. Go to your Moodle course page, and in the Administration box, click Files. We're in the course files storage area—this is another way in, if you ever need one! You can upload anything straight into here, and then provide a link to a file or web site. As we have done before, click on Upload and upload the zipped folder (it ends in .zip). Now click on Unzip, which is displayed to the right of your folder name (as shown in the following screenshot), and the folder will be restored to its normal size. What just happened? We put a bunch of slideshows about how rivers work into a folder on our computer. We then zipped the folder to make it slide into Moodle, and then when it was uploaded, we unzipped it to get it back to normal. If you want to be organized, select the checkbox displayed to the left of the zipped folder, and select delete completely. We don't need the zipped folder now, as we have got the original folder back. We now have two choices. Using the Link to a file or web site option in the Add a resource block, we can display each slideshow, in an orderly manner, in the list. We did this with our Thames factsheet, so we know how to do this. Alternatively, we can simply display the folder and let the students open it to get to the slideshows. We're going to opt for the second choice. Why? Bearing in mind about appearances being vital, it would look much neater on our course page if we had a dinky little briefcase icon. The student can click on the briefcase icon to see the list of slideshows, rather than scrolling down a long list on the page. Let us see how this is done: Time for action-displaying a whole folder on Moodle Let us upload the entire folder, which contains the related slideshows, onto Moodle. This will require us to perform only four steps: With editing turned on, click on Add a resource and choose Display a directory. In the Name field, type something meaningful for the students to click on and add a description in the Summary field, if you wish. Click on Display a directory and find the one that you want—for us, RiverProcesses. Scroll down, and click on Save and return to course. What just happened? We made a link to a week's worth of slideshows on our course page, instead of displaying them one at a time. If we looked at the outcome, instead of the icon of a slideshow, such as the PowerPoint icon, we get a folder icon. When the text next to it is clicked, the folder opens, and all of the slideshows inside can be viewed. It is much easier on the eye, when you go directly to the course page, than going through a long list of stuff . Making a 'click here' type link to the River Thames web site Let's learn how to create a link that will lead us to the River Thames web site, or in fact to any web site. However, we're investigating the Thames at the moment, so this would be really helpful. Just imagine, how much simpler it would be for our students to be able to get to a site in one click, rather than type it by hand, spell it wrong, and have it not work. The way we will learn now is easy. In fact, it's so easy that you could do it yourself with only one hint from me. Have a go hero-linking to a web site Do you recollect that we uploaded our worksheet and used Link to a file or web site? We linked it to a file (our worksheet). Here, you just need to link to a web site, and everything else is just the same. When you get to the Link to a file or web site box, instead of clicking Choose or upload a file…, just type in, or copy and paste, the web site that you want to link to (making sure you include only one http://). Remember that we saw earlier, that if you click on Search for web page…, it will take you to Google or some other Search Engine web page to find you a web site that you'd like to link to. The following screenshot shows how to link a file or web site into our Moodle course : That's it! Try it! Go back to your course page; click on the words that you specified as the Name for the web page link, and check whether it works. It should open the web page in a new window, so that once finished, our students can click on the X to close the site and will still have Moodle running in the background. Recap—where do we stand now? We have learnt a lot of interesting things so far. Lets just have a recap of the things that we have learned so far. We have learnt to: Upload and display individual worksheets (as we've worked on the River Thames) Upload and display whole folders of worksheets (as we did with the River Processes slideshows folder) Make a click here type link to any web site that we want, so that our students will just need to click on this link to get to that web site We're now going to have a break from filling up our course for a while, and take a step to another side. Our first venture into Moodle's features was the Link to a file or web site option, but there are many more yet to be investigated. Let's have a closer look at those Add a resource… options in the following screenshot, so that we know, where we are heading: The table below shows all of the Add a Resource… options. What are they, which is the one we need, and what can we safely ignore? You might recognize one or two already. We shall meet the others in a moment.
Read more
  • 0
  • 0
  • 3055

article-image-podcasting-and-images-drupal
Packt
27 Oct 2009
8 min read
Save for later

Podcasting and Images in Drupal

Packt
27 Oct 2009
8 min read
Getting Started with Podcasts To create a podcast, you will need: A mp3 file A place to store the mp3 file At the risk of stating the obvious, a good podcast requires thought and planning before you make the actual recording. Later in the article, we will discuss some of these general mechanics. But, from a technical perspective, once you have your audio file, you can upload it to your Drupal site, and you will have published a podcast. Audio Module The Audio module supports the playback of audio files that have been uploaded to your site. To install this module, we will also need to install two helper modules required by the Audio module: the getID3() and Token modules. In this section, we will cover installing the Audio module, as well as the getID3() and Token modules. Install the getID3() Module Download the getID3() module from http://drupal.org/project/getid3, and upload it to your sites/all/modules directory . Do not, however, enable the module, as we need to install an additional piece of code described as follows. Install the getID3() Libraries The getID3() libraries are a tool that automatically extract information about audio files. These libraries don't require you to do any additional work; rather, they detect information that can be used by the Audio module. Download the getID3() libraries from http://getid3.sourceforge.net/. Unzip these libraries onto your hard drive. As shown in the preceding screenshot, the libraries include some demo and helper files, in addition to the readme and license files. The only files we need are contained in the getid3 directory. The getid3 directory is the only directory that you need to upload to your website. Then, use your FTP client to connect to your web server, and navigate to sites/all/modules/getid3. Upload the getid3 directory into sites/all/modules/getid3 as shown in the following screenshot: Once the module and the libraries have been uploaded to your site, enable the getID3() module by clicking the Administration | Site building | Modules link, or by navigating to admin/build/modules. Following these instructions the path to your getID3() library is sites/all/modules/getid3/getid3. If needed, this path can be adjusted at Administer | Site configuration | getID3(), or admin/settings/getid3. Install the Token Module Download the Token module from http://drupal.org/project/token, and install it. Once this module has been uploaded to your site, enable it by clicking the Administration | Site building | Modules link, or by navigating to admin/build/modules. The Token module is a helper module, and its functionality will be largely invisible to the end user. The Token module supplies pieces of text, or tokens, which can be used by other modules. The Audio module relies on the Token module and the getID3() module to help automatically generate titles and other information for audio files. Install and Enable the Audio Module Download the audio module from http://drupal.org/project/audio. Upload the module to your sites/all/modules directory, and enable it by clicking the Administer | Site building | Modules link or by navigating to admin/build/modules. Select the Audio and the Audio getID3 modules. Click the Save configuration button to submit the form and enable the modules. Configure the Audio Module Now that we have installed the Audio module and its helper modules, we need to configure the audio module to support our needs. Click the Administer | Site Configuration | Audio link, or navigate to admin/settings/audio. As pictured in the following screenshot, you will see three tabs across the top of the page: Audio, Metadata tags, and Players. The Audio Tab The options on the Audio tab, pictured in the preceding screenshot, allow you to set some default values that are used when audio posts are uploaded. The values here can be created automatically, which can be useful if you are working with songs. For most cases, however, you will want to delete the option for the Default node title format, and leave the other default values intact. When you have adjusted the settings, click the Save configuration button at the bottom of the page. To save your settings, you must click the Save configuration button before moving on to the next tab. A Brief Explanation of Tokens In the preceding screenshot, there is a collapsible fieldset titled List of available tokens. Click on the link to expand the fieldset. A portion of the tokens available are shown in the following screenshot: As suggested by the preceding screenshot, tokens expose pieces of information about content created within a site. Tokens can only be used when a module has been written to work with the tokens. Because the Audio module has been written to depend on the Token module, we have the option of using tokens if we wish. For example, we could set the title of audio nodes to automatically incorporate the username and the creation date. To make this work, we would set the Default node title format (as shown in the Audio settings screenshot) to Created by [author-name] on [yyyy]-[mon]-[date]. In most cases tokens run invisibly in the background without requiring any adjustments by the end user. The Metadata Tags Tab The options in this section will be useful if you are setting up podcasts as part of a music or radio station, but will be less useful in other environments. By reducing the number of required options, you can simplify the form for uploading podcasts. The settings pictured in the following screenshot are all you need to get started publishing audio on the web. The Players Tab The Audio module comes with several different players that can be used to play your audio files. You can use the settings on this page to choose your preferred player. As you can see in the following figure, you can specify a different player for each type of audio file. The "best" player will largely be determined by your aesthetic preference; all of the players do a great job playing audio stored on your site. After you have chosen a player, click the Save configuration button to save your preference. Assign Rights to the Audio Module Now that we have installed, enabled, and configured the audio module, we need to assign rights to it. Click the Administer | User management | Roles link, or navigate to admin/user/roles. The possible rights that can be assigned are shown in the following figure: We will need to assign rights for the teacher role, the student role, the authenticated user role, and possibly the anonymous user role. For the authenticated user role, assign rights to download audio and play audio. For the student role, assign rights to create audio and edit own audio. For the teacher role, assign rights to create audio, edit own audio, and view download stats. For the anonymous user role, assign the rights you think are appropriate. In most cases, if you are allowing anonymous users to see content, allowing them the rights to download audio and play audio is appropriate. Each time you assign rights to an individual roles, click the Save permissions button to save the rights for the role. Adjust Existing Views Currently, three views are being used to display student and teacher-created content. We will need to edit these views so that they return any audio nodes created within the site. To edit these views, click the Administer | Site building | Views link, or navigate to admin/build/views. We need to edit three views: the teacher_blog view, the student_blog and conversation views. As shown in the following screenshot, these views can be edited by using the Edit link on the main Views administration page. Editing the student_blog View Click the Edit link as shown in the preceding screenshot. Then, in the Defaults display, under Filters, click on the Node: Type link, as shown by Item 1 in the following screenshot: As shown by Item 2 in the preceding screenshot, add Audio to the node types returned in this view. Click the Update button to store this change, and then click the Save button (not pictured in the preceding screenshot) to save the view. Editing the conversations View Click the Edit link for the conversations view. Then, in the Defaults display, under Arguments, click on the Search:Links to link, as shown by Item 1 in the following figure: As shown by Item 2 in the preceding screenshot, add Audio to the list of node types where this view will be validated. Click the Update button to store this change, and then click the Save button to save the view. As we add additional content types into the site, we will need to update these views to account for the newly-added content types.
Read more
  • 0
  • 0
  • 1849
article-image-implementing-basic-helloworld-wcf-windows-communication-foundation-service
Packt
27 Oct 2009
7 min read
Save for later

Implementing a Basic HelloWorld WCF (Windows Communication Foundation) Service

Packt
27 Oct 2009
7 min read
We will build a HelloWorld WCF service by carrying out the following steps: Create the solution and project Create the WCF service contract interface Implement the WCF service Host the WCF service in the ASP.NET Development Server Create a client application to consume this WCF service Creating the HelloWorld solution and project Before we can build the WCF service, we need to create a solution for our service projects. We also need a directory in which to save all the files. Throughout this article, we will save our project source codes in the D:SOAwithWCFandLINQProjects directory. We will have a subfolder for each solution we create, and under this solution folder, we will have one subfolder for each project. For this HelloWorld solution, the final directory structure is shown in the following image: You don't need to manually create these directories via Windows Explorer; Visual Studio will create them automatically when you create the solutions and projects. Now, follow these steps to create our first solution and the HelloWorld project: Start Visual Studio 2008. If the Open Project dialog box pops up, click Cancel to close it. Go to menu File | New | Project. The New Project dialog window will appear. From the left-hand side of the window (Project types), expand Other Project Types and then select Visual Studio Solutions as the project type. From the right-hand side of the window (Templates), select Blank Solution as the template. At the bottom of the window, type HelloWorld as the Name, and D:SOAwithWCFandLINQProjects as the Location. Note that you should not enter HelloWorld within the location, because Visual Studio will automatically create a folder for a new solution. Click the OK button to close this window and your screen should look like the following image, with an empty solution. Depending on your settings, the layout may be different. But you should still have an empty solution in your Solution Explorer. If you don't see Solution Explorer, go to menu View | Solution Explorer, or press Ctrl+Alt+L to bring it up. In the Solution Explorer, right-click on the solution, and select Add | New Project… from the context menu. You can also go to menu File | Add | New Project… to get the same result. The following image shows the context menu for adding a new project. The Add New Project window should now appear on your screen. In the left-hand side of this window (Project types), select Visual C# as the project type, and on the right-hand side of the window (Templates), select Class Library as the template. At the bottom of the window, type HelloWorldService as the Name. Leave D:SOAwithWCFandLINQProjectsHelloWorld as the Location. Again, don't add HelloWorldService to the location, as Visual Studio will create a subfolder for this new project (Visual Studio will use the solution folder as the default base folder for all the new projects added to the solution). You may have noticed that there is already a template for WCF Service Application in Visual Studio 2008. For the very first example, we will not use this template. Instead, we will create everything by ourselves so you know what the purpose of each template is. This is an excellent way for you to understand and master this new technology. Now, you can click the OK button to close this window. Once you click the OK button, Visual Studio will create several files for you. The first file is the project file. This is an XML file under the project directory, and it is called HelloWorldService.csproj. Visual Studio also creates an empty class file, called Class1.cs. Later, we will change this default name to a more meaningful one, and change its namespace to our own one. Three directories are created automatically under the project folder—one to hold the binary files, another to hold the object files, and a third one for the properties files of the project. The window on your screen should now look like the following image: We now have a new solution and project created. Next, we will develop and build this service. But before we go any further, we need to do two things to this project: Click the Show All Files button on the Solution Explorer toolbar. It is the second button from the left, just above the word Solution inside the Solution Explorer. If you allow your mouse to hover above this button, you will see the hint Show All Files, as shown in above diagram. Clicking this button will show all files and directories in your hard disk under the project folder-rven those items that are not included in the project. Make sure that you don't have the solution item selected. Otherwise, you can't see the Show All Files button. Change the default namespace of the project. From the Solution Explorer, right-click on the HelloWorldService project, select Properties from the context menu, or go to menu item Project | HelloWorldService Properties…. You will see the project properties dialog window. On the Application tab, change the Default namespace to MyWCFServices. Lastly, in order to develop a WCF service, we need to add a reference to the ServiceModel namespace. On the Solution Explorer window, right-click on the HelloWorldService project, and select Add Reference… from the context menu. You can also go to the menu item Project | Add Reference… to do this. The Add Reference dialog window should appear on your screen. Select System.ServiceModel from the .NET tab, and click OK. Now, on the Solution Explorer, if you expand the references of the HelloWorldService project, you will see that System.ServiceModel has been added. Also note that System.Xml.Linq is added by default. We will use this later when we query a database. Creating the HelloWorldService service contract interface In the previous section, we created the solution and the project for the HelloWorld WCF Service. From this section on, we will start building the HelloWorld WCF service. First, we need to create the service contract interface. In the Solution Explorer, right-click on the HelloWorldService project, and select Add | New Item…. from the context menu. The following Add New Item - HelloWorldService dialog window should appear on your screen. On the left-hand side of the window (Categories), select Visual C# Items as the category, and on the right-hand side of the window (Templates), select Interface as the template. At the bottom of the window, change the Name from Interface1.cs to IHelloWorldService.cs. Click the Add button. Now, an empty service interface file has been added to the project. Follow the steps below to customize it. Add a using statement: using System.ServiceModel; Add a ServiceContract attribute to the interface. This will designate the interface as a WCF service contract interface. [ServiceContract] Add a GetMessage method to the interface. This method will take a string as the input, and return another string as the result. It also has an attribute, OperationContract. [OperationContract] String GetMessage(String name); Change the interface to public. The final content of the file IHelloWorldService.cs should look like the following: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ServiceModel;namespace MyWCFServices{[ServiceContract]public interface IHelloWorldService{[OperationContract]String GetMessage(String name);}}
Read more
  • 0
  • 0
  • 2748

article-image-creating-dialplan-asterisk-16-part-2
Packt
27 Oct 2009
14 min read
Save for later

Creating a Dialplan in Asterisk 1.6: Part 2

Packt
27 Oct 2009
14 min read
Advanced Call Distribution What exactly is Advanced Call Distribution ? Many phone systems tout this feature, but most do not adequately define what it means. Basically, it refers to using call queues, parking calls for another user to answer, and Direct Inward Dialing (DID). So that we keep our focus, we will look at each of these elements individually. Call queues We have already configured call queues through the /etc/asterisk/queues.conf file. As we go through how we're going to use our queues, we may decide we want to change the way our queues are configured. There is absolutely no problem with changing the configuration so that it more accurately reflects our needs. Just remember that we need to issue a reload on the Asterisk console, or type #asterisk –r –x reload at the command line. The power and flexibility of other ACD systems can be matched or exceeded by Asterisk. As we evaluate our needs, we should remember that configuring a single aspect of Asterisk sometimes requires changes to more than one file. For example, queues will be configured both in the queues.conf file and the extensions.conf file. We will discuss how to set up extensions.conf to give us the desired result. When dealing with call queues, we need to think about the two types of users we have. First, we have the caller who calls in and waits in the queue for the next agent. We can think of this person as our customer. Next, we have the agents who work the queue. We can think of these people as our users. As a business, we have to decide what we want our customers' experience to be. Our call queue can make it sound like a phone is ringing. Or we can use music on hold while the customer waits. We can also announce call position and estimated wait time if we want to. When we place customers in a queue, we use the Queue application. To place a caller in the queue named bob, we would use something like: exten => 1000,1,Queue(bob) Suppose we have an operator's extension. As Ollie the operator may have more than one call at a time, we decide to give him a call queue. His calls are always about a minute long. The customers waiting for him are going to be there because they got lost in a system of menus. His queue will be named operator. In this instance, we will choose to have the customer hear the ring, so they will believe they are about to be helped. The sound of ringing should not last more than about a minute. We will not announce call queue length because our customer should not know that he or she is in a queue. The entry for this queue would be: exten => 0,1,Queue(operator|tr) Notice our use of options. Options for the queue application include: t: Allow the user to transfer the customer. T: Allow the customer to transfer the user. d: This is a data-quality call. H: Allow the customer to hang up by hitting *. n: Do not retry on timeout. The next step in the dialplan will be executed. r: Give the customer the ringing sound instead of music on hold. Thus, we told the Queue application to make the customer hear the ring, and the user (Ollie) the ability to transfer calls (as he's the operator). Now, suppose we have Rebecca, the receptionist at SIP phone 1006. When Ollie goes to the bathroom, we want our poor lost customers to be routed to her. So we could use the following in our extensions.conf file: exten => 0,1,Queue(operator|trn)exten => 0,2,Dial(SIP/1006) Now, Rebecca had better answer this. Until she does, the phone will continue to ring. Notice that this call will never end up in Rebecca's voicemail, as it is not transferred to her extension, but instead dials her phone directly. We have adequately addressed the customer's experience. But now we need to look at how our users will join and leave the queue. Previously, we discussed the power and flexibility of using agents in queues. As with most things in Asterisk, there are many ways we can associate members to queues. The three main ways are—statically, dynamically, and by using agents. Our first option is to have members statically assigned to the queue. In order to do this, we use the member directive in the queues.conf file. This is most helpful when we have a queue with fixed members, such as a switchboard queue. Our second option is to allow members to log in dynamically. We do this through the AddQueueMember application. An example of this would be: exten => 8101,1,AddQueueMember(myqueue|SIP/1001) Whenever anybody dials extension 8101, the telephone handset SIP/1001 would be added to the queue named myqueue. All that we would have to do is define a login extension for every member of every queue. What happens when this member no longer wishes to be in the queue? We use the RemoveQueueMember application, like this: exten => 8201,1,RemoveQueueMember(myqueue|SIP/1001) With this configuration, whenever anybody dials extension 8201, the telephone handset at SIP/1001 is removed. Again, we would have to define a logout extension for each member of the queue. Suppose we did not wish to define a login and logout extension for each member. We have the option of leaving off the interface (SIP/1001 in the previous example) and having Asterisk use our current extension. While this is very useful, Asterisk does not always use the right value. However, if it works for all extensions that need to be in the queue, we would only have to define one login and one logout per queue. The code would look like: exten => 8101,1,AddQueueMember(myqueue)exten => 8201,1,RemoveQueueMember(myqueue) This is better than having to define a login and logout for each member of each queue, but sometimes users are not good at remembering multiple extensions to dial. The AddQueueMember application will jump to priority n+101 if that interface is already a member of the queue. Therefore, we could define an extension like: exten => 8101,1,Answerexten => 8101,2,AddQueueMember(myqueue)exten => 8101,3,Playback(agent-loginok)exten => 8101,4,Hangupexten => 8101,103,RemoveQueueMember(myqueue)exten => 8101,102,Playback(agent-loggedoff)exten => 8101,105,Hangup When we define it this way, a user dialing extension 8101 is logged in if not already a member of the queue, or logged out if in the queue. Also, we added a confirmation to the action, so that the user can know if they are now in or out of the queue. Notice that before we could use the Playback application, we had to answer the call. If we have a lot of these, we could define a macro extension, like: [macro-queueloginout]exten => s,1,Answerexten => s,2,AddQueueMember(${ARG1})exten => s,3,Playback(agent-loginok)exten => s,4,Hangupexten => s,103,RemoveQueueMember(${ARG1})exten => s,104,Playback(agent-loggedoff)exten => s,105,Hangup. . .[default]exten => 8101,1,Macro(queueloginout|queue1)exten => 8102,1,Macro(queueloginout|queue2)exten => 8103,1,Macro(queueloginout|queue3) And thus we see that using a macro will save us five lines in our extensions.conf for every queue after the first. This is how we can add queue members dynamically. Our final option for adding queue members is by using Asterisk's agent settings. We were able to define agents in /etc/asterisk/agents.conf. We create an agent by defining an ID and a password, and listing the agent's name. In the queues.conf, we could define agents as members of queues. Calls will not be sent to agents unless they are logged in. In this way, queues can be both dynamic and static—they are static when we do not change the members of the queues, but dynamic when calls will go to different handsets based upon which agents are logged in. There are two main types of agents in this world. There are the archetypical large call center agents who work with a headset and never hear rings, and there are the lower-volume agents whose phone rings each time a call comes in. Asterisk has the flexibility to handle both types of agents, even in the same queue. First, imagine a huge call center that takes millions of phone calls per day. Each agent is in multiple queues, and we have set each queue to use an announcement at the beginning of calls to let the agent know which queue the call is coming in from. As employees arrive for their shift, they sit down at an empty station, plug in their headset, and log in. Each employee will hear music in between calls, and then hear a beep, and the call will be connected. To accomplish this, we use the line: exten => 8001,1,AgentLogin Through the normal login, the call is kept active the whole time. The agents will logout by hanging up the phone. This allows large call centers to be quieter, as the distraction of ringing phones will be removed. It also allows for more efficient answering of lines, as the time required to pick up the phone is eliminated. When our users arrive at work and wish to log in, they call extension 8001, where they are prompted for their agent ID, password, and then an extension number at which they will take calls. This is how Asterisk knows how to reach them. Our agents can log out when using AgentCallbackLogin by going through the same procedure as for login, with the exception that when they are prompted for their extension, they press the # key. It may be a good idea for us to review agents.conf. If we defined autologoff, then after the specified number of seconds of ringing, the agent will be automatically logged off. If we set ackcall to yes, then agents must press the # key to accept calls. If we created a wrapuptime (defined in milliseconds), then Asterisk will wait that many milliseconds before sending another call to the agent. These options can help us make our phone system as user friendly as we want it to be. Through the use of call queues, we can distribute our incoming calls efficiently and effectively. We have plenty of options, and can mix and match these three ways of joining users to queues. Call parking In many businesses across the United States, an operator can be heard announcing "John, you have a call on line 3. John, line 3." In Asterisk, we don't really have lines the way analog PBXs do. Our users are accustomed to not having to transfer calls, especially when they may not know exactly where John is. Asterisk uses a feature known as call parking to accomplish this same goal. Our users will transfer calls to a special extension, which will then tell them what extension to call in order to retrieve the call. Then our users can direct the intended recipient to dial that extension and connect to the call. In order to be able to use this feature, we must define our parking lot. This is done in the /etc/asterisk/parking.conf file. In this file, there are only a few options that we will need to configure. First, we must create the extension that people are to dial in order to park calls. This can be whatever extension is convenient for us. Then we will define a list of extensions on which to place parked calls. These extensions will be what users dial to retrieve a parked call. Next, we will define what context we want our parked calls to be in. Finally, we will define how many seconds a call remains parked before ringing back to the user who parked it. Here is an example: [general]parkext => 8100parkpos => 8101-8199context => parkedcallsparkingtime => 120 These settings would mean that we can park calls by dialing 8100, and the call will be placed in extensions 8101 through 8199, giving us the ability to have up to 99 parked calls at any given time. The calls will be in the context called parkedcalls, which means we should be careful to include it in any context where users should be able to park and retrieve calls. When our users transfer a call to extension 8100, they will hear Asterisk read out the extension that the call has been placed on. They can now make a note of it and notify the appropriate co-worker of the extension to reach the calling customer on. If the call is not picked up within the given parkingtime, then the call will ring back to the user who parked the call. By using call parking, we can help our users by providing a feature similar to that of previous generations of PBXs. This also allows users to collaborate and redirect callers to other users who are better equipped to handle our customers' needs. Direct Inward Dialing (DID) Suppose we work at a healthcare company with over 100 employees. We have two PRI lines coming in, and only three switchboard agents to handle incoming calls. As a healthcare company, we schedule many appointments, answer questions about prescriptions, and help patients with billing questions. These three agents are always busy. Now suppose the IT guy's wife calls in to ask if he wants sprouts or mash with his dinner. Do we want our switchboard agents to have to answer the call, find out who it is and what they want, and then transfer the call, or would we rather want the IT guy's wife to call her husband directly? This is where Direct Inward Dialing (DID) comes in handy. DID is a service provided by phone companies where they send an agreed-upon set of digits, depending on the number the customer dialed. For most phone companies, the sent digits will be the full ten-digit number (in the United States). But this can be as small as the last digit. All right, so the phone company is sending digits. What are we going to do with them? Imagine you have a PRI coming in to your office, and only ten phone numbers—a block from (850) 555-5550 to 5559. Your phone company has agreed to send you only the last digit dialed, which will be from 0 to 9, because you are guaranteed for this to be unique. Asterisk can route calls based on this DID information. If we have our PRI line's channels defined to go into a context called incoming, this context could look like: [incoming]s,1,Goto(default,s,1)i,1,Goto(default,s,1)t,1,Goto(default,s,1)0,1,Goto(default,1234,1)1,1,Goto(default,2345,1)2,1,Goto(default,3456,1)3,1,Goto(default,4567,1)4,1,Goto(default,5678,1)5,1,Goto(default,6789,1)6,1,Goto(default,7890,1)7,1,Goto(default,1111,1)8,1,Goto(default,1111,1)9,1,Goto(default,1111,1) There are a few things we should notice about this. First, we handled the error cases. What if a glitch at the phone company results in four digits being sent? We cannot allow a simple mistake on their end to interrupt our ability to receive phone calls. Secondly, we are using Goto statements. We've briefly discussed how they can be both good and bad. In this case, if a user moves from one extension to another by using Goto, we have to update it only in the default context. Finally, we are allowed to send multiple incoming DIDs to the same extension, if we so desire, as in the last three lines shown in the previous code. This might be useful if extension 1111 is the operator, and we do not yet have the number 7, 8, or 9 assigned to a user. Of course, in real life this is going to get much more complicated, as phone numbers will probably come in with the full ten digits. But the concept is the same—we can define extensions based upon information that the phone company sends when the call is established. By using DIDs, we can cut down on bottlenecks and give direct access to certain extensions. This tool of Asterisk helps make our phone system fast, efficient, and friendly to our users and customers.  
Read more
  • 0
  • 0
  • 3261
Modal Close icon
Modal Close icon