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

7018 Articles
article-image-moodle-20-multimedia-creating-and-integrating-screencasts-and-videos
Packt
23 May 2011
8 min read
Save for later

Moodle 2.0 Multimedia: Creating and Integrating Screencasts and Videos

Packt
23 May 2011
8 min read
  Moodle 2.0 Multimedia Cookbook Add images, videos, music, and much more to make your Moodle course interactive and fun         Read more about this book       (For more resources on Moodle 2.0, see here.) Introduction Moodle 2.0 offers new features, which make it easier to insert videos, especially from the http://www.youtube.com website. You can find them easily from the file picker, provided you have administrative access to the course. You have to bear in mind that you need to be an administrator in order to enable this option. This article covers different ways to create and interact using either screencasts or videos. We will work with several multimedia assets, which will concern the baseline topic of Wildlife. This topic has many resources, which can be integrated with screencasts and videos available on the Web. Creating screencasts using several free and open source software available on the Web is one of the main goals of this chapter. There is plenty of commercial software, which can be used to create screencasts. We will not focus on them though. We add some special features to the screencasts in order to enhance them. Videos can be recorded in several ways. You may use your cell phone, camera, or the webcam of your computer. We are to focus on the way of creating them and uploading into our Moodle course. We can also use a recorded video from YouTube and upload it directly from the file picker in Moodle 2.0. You can also design a playlist in order to combine several videos and let your students watch them in a row. We do it by creating an account in YouTube. The channel in YouTube can be either public or private; it depends on how we want to carry it out. You can create some screencasts in order to present information to your students instead of showing presentations made using Open Office, PowerPoint, or Microsoft Word. Changing any of these into a screencast is more appealing to the students and not such a difficult task to carry out either. We can create an explanation by recording our voice, for which we will create a virtual board that we can choose to be visible to the audience; in the second case, our explanations can only be heard with no visualization. This is quite an important aspect to be taken into account, especially in teaching because students need a dynamic explanation by their teacher. There are several software available that can be used to create screencasts. One of them is Cam Studio. This software captures AVI files and it is open source. It captures onscreen video and audio. Its disadvantage is that only Windows users can use it. You can download it from http://camstudio.com/. It is time for Mac users. There is also a free program for Mac users that focuses on making quick films by saving the recorded video to get a quick access. It does not record audio. This is Copernicus and you can download it from http://danicsoft.com/software/copernicus/. We need a tool for both Mac and Windows, which is free and open source as well. So, JingProject.com is the software. It does not only record video, but also allows you to take a picture, draw, or add a message on it, and upload the media to a free hosting account. A URL is provided in order to watch the video or the image. You can download it from the following website: http://www.techsmith.com/download/jing/. Screencast-o-matic is another tool that is based on Java that does not need to be downloaded at all. It allows you to upload in an automatic way. It works well with both Mac and Windows machines. You can use this at http://www.screencast-o-matic.com/. This is the tool that we are to work with in the creation of a screencast. We may also modify the videos to make them suitable for learning. We can add annotations in different ways so as to interact through the video with our students. That is to say, we add our comments instead of adding our voice so that students read what we need to tell them. Creating a screencast In this recipe, we create a screencast and upload it to our Moodle course. The baseline topic is Wildlife. Therefore, in this recipe, we will explain to our students where wild animals are located. We can paste in a world map of the different animals, while we add extra data through the audio files. Thus, we can also add more information using different types of images that are inserted in the map. Getting ready Before creating the screencast, plan the whole sequence of the explanation that we want to show to our students, therefore, we will use a very useful Java applet available at http://www.screencast-o-matic.com/. Screencast-o-matic requires the free Java Run-time Environment (also known as JRE) for both the teacher and the students' computers. You can download and install its latest version from http://java.sun.com. How to do it... First of all, design the background scene of the screencast to work with. Afterwards, enter the website http://www.screencast-o-matic.com/. Follow these to create the screencast: Click on Start recording. Another pop-up window appears that looks as shown in the following screenshot: Resize the frame to surround the recording area that you want to record. Click on the recording button (red button). If you want to make a pause, click on the pause button or Alt + P, as shown in the following screenshot: If you want to integrate the webcam or a bluetooth video, click on the upwards arrow in this icon, as shown in the following screenshot: When the screencast is finished, click on Done. You can preview the screencast after you finish designing it. If you need to edit it, click on Go back to add more. If you are satisfied with the preview, click on Done with this screencast, as shown in the following screenshot: When the screencast is finished, our next task is to export it because we need to upload it to our Moodle course. Click on Export Movie. Click on the downwards arrow in Type and choose Flash (FLV), as shown in the following screenshot: Customize the Size and Options blocks, as shown in the previous screenshot or as you wish. When you finish, click on Export, as shown in the previous screenshot. Write a name for this file and click on Save. When the file is exported, click on Go back and do more with this screencast if you want to edit it. Click on Done with this screencast if you are satisfied with the result. A pop-up window appears, click on OK. How it works... We have just created the screencast teaching about wild animals, which students have to watch to learn about the places where wild animals live around the world. We need to upload it to our Moodle course. It is a passive resource; therefore, we can add a resource or design an activity out of it. In this case, we design an activity. Choose the weekly outline section where you want to insert it, and follow these steps: Click on Add an activity | Online text within Assignments. Complete the Assignment name and Description blocks. Click on the Moodle Media icon | Find or upload a sound, video or applet ... | Upload a file | Browse | look for the file that you want to upload and click on it. Click on Open | Upload this file | Insert. Click on Save and return to course. Click on the activity. It looks as shown in the following screenshot: There's more... In the case that we create a screencast, which lasts for around 30 minutes or longer, it will take a long time to upload it to our Moodle course. Therefore, it will be advisable to watch the screencast using a free and open source media player, that is to say VLC Media Player. VLC Media Player You can download the VLC Media Player from the following website: http://www.videolan.org/vlc/. It works with most popular video files formats such as AVI, MP4, and Flash, among others. Follow these steps in order to watch the screencast: Click on Media | Open File | browse for the file that you want to open and click on it. Click on Open. The screencast is displayed, as shown in the following screenshot: See also Enhancing a screencast with annotations  
Read more
  • 0
  • 0
  • 4430

article-image-sphinx-search-faqs
Packt
23 May 2011
9 min read
Save for later

Sphinx Search FAQs

Packt
23 May 2011
9 min read
Got questions on Sphinx, the open source search engine? Not sure if it's the right tool for you? You're in the right place - we've put together an FAQ on Sphinx. It should help you make the right decision about the software that powers your search. If you've got questions on the other kind of Sphinx, we recommend you look here instead. What is Sphinx? Sphinx is a full-text search engine (generally standalone) which provides fast, relevant, efficient full-text search functionality to third-party applications. It was especially created to facilitate searches on SQL databases and integrates very well with scripting languages; such as PHP, Python, Perl, Ruby, and Java. What are the major features of Sphinx? Some of the major features of Sphinx include: High indexing speed (up to 10 MB/sec on modern CPUs) High search speed (average query is under 0.1 sec on 2 to 4 GB of text collection) High scalability (up to 100 GB of text, up to 100 Million documents on a single CPU) Supports distributed searching (since v.0.9.6) Supports MySQL (MyISAM and InnoDB tables are both supported) and PostgreSQL natively Supports phrase searching Supports phrase proximity ranking, providing good relevance Supports English and Russian stemming Supports any number of document fields (weights can be changed on the fly) Supports document groups Supports stopwords, that is, that it indexes only what's most relevant from a given list of words Supports different search modes ("match extended", "match all", "match phrase" and "match any" as of v.0.9.5) Generic XML interface which greatly simplifies custom integration Pure-PHP (that is, NO module compiling and so on) search client API Which operating systems does Sphinx run on? Sphinx was developed and tested mostly on UNIX based systems. All modern UNIX based operating systems with an ANSI compliant compiler should be able to compile and run Sphinx without any issues. However, Sphinx has also been found running on the following operating systems without any issues. Linux (Kernel 2.4.x and 2.6.x of various distributions) Microsoft Windows 2000 and XP FreeBSD 4.x, 5.x, 6.x NetBSD 1.6, 3.0 Solaris 9, 11 Mac OS X What does the configure command do? The configure command gets the details of our machine and also checks for all dependencies. If any of the dependency is missing, it will throw an error. Which are the various options for the configure command? There are many options that can be passed to the configure command but we will take a look at a few important ones: prefix=/path: This option specifies the path to install the sphinx binaries. with-mysql=/path: Sphinx needs to know where to find MySQL's include and library files. It auto-detects this most of the time but if for any reason it fails, you can supply the path here. with-pgsql=/path: Same as –-with-mysql but for PostgreSQL. What is full-text search? Full-text search is one of the techniques for searching a document or database stored on a computer. While searching, the search engine goes through and examines all of the words stored in the document and tries to match the search query against those words. A complete examination of all the words (text) stored in the document is undertaken and hence it is called a full-text search. Full-text search excels in searching large volumes of unstructured text quickly and effectively. It returns pages based on how well they match the user's query. What are the advantages of full-text search? The following points are some of the major advantages of full-text search: It is quicker than traditional searches as it benefits from an index of words that is used to look up records instead of doing a full table scan It gives results that can be sorted by relevance to the searched phrase or term, with sophisticated ranking capabilities to find the best documents or records It performs very well on huge databases with millions of records It skips the common words such as the, an, for, and so on When should you use full-text search? You should use full-text search when: When there is a high volume of free-form text data to be searched When there is a need for highly optimized search results When there is a demand for flexible search querying Why use Sphinx for full-text search? If you're looking for a good Database Management System (DBMS), there are plenty of options available with support for full-text indexing and searches, such as MySQL, PostgreSQL, and SQL Server. There are also external full-text search engines, such as Lucene and Solr. Let's see the advantages of using Sphinx over the DBMS's full-text searching capabilities and other external search engines: It has a higher indexing speed. It is 50 to 100 times faster than MySQL FULLTEXT and 4 to 10 times faster than other external search engines. It also has higher searching speed since it depends heavily on the mode, Boolean vs. phrase, and additional processing. It is up to 500 times faster than MySQL FULLTEXT in cases involving a large result set with GROUP BY. It is more than two times faster in searching than other external search engines available. Relevancy is among the key features one expects when using a search engine, and Sphinx performs very well in this area. It has phrase-based ranking in addition to classic statistical BM25 ranking. Last but not the least, Sphinx has better scalability. It can be scaled vertically (utilizing many CPUs, many HDDs) or horizontally (utilizing many servers), and this comes out of the box with Sphinx. One of the biggest known Sphinx cluster has over 3 billion records with more than 2 terabytes of size. What are indexes? Indexes in Sphinx are a bit different from indexes we have in databases. The data that Sphinx indexes is a set of structured documents and each document has the same set of fields. This is very similar to SQL, where each row in the table corresponds to a document and each column to a field. Sphinx builds a special data structure that is optimized for answering full-text search queries. This structure is called an index and the process of creating an index from the data is called indexing. The indexes in Sphinx can also contain attributes that are highly optimized for filtering. These attributes are not full-text indexed and do not contribute to matching. However, they are very useful at filtering out the results we want based on attribute values. There can be different types of indexes suited for different tasks. The index type, which has been implemented in Sphinx, is designed for maximum indexing and searching speed. What are multi-value attributes (MVA)? MVAs are a special type of attribute in Sphinx that make it possible to attach multiple values to every document. These attributes are especially useful in cases where each document can have multiple values for the same property (field). How does weighting help? Weighting decides which document gets priority over other documents and appear at the top. In Sphinx, weighting depends on the search mode. Weight can also be referred to as ranking. There are two major parts which are used in weighting functions: Phrase rank: This is based on the length of Longest Common Subsequence (LCS) of search words between document body and query phrase. This means that the documents in which the queried phrase matches perfectly will have a higher phrase rank and the weight would be equal to the query word counts. Statistical rank: This is based on BM25 function which takes only the frequency of the queried words into account. So, if a word appears only one time in the whole document then its weight will be low. On the other hand if a word appears a lot in the document then its weight will be higher. The BM25 weight is a floating point number between 0 and 1. What is index merging, exactly? Index merging is more efficient than indexing the data from scratch, that is, all over again. In this technique we define a delta index in the Sphinx configuration file. The delta index always gets the new data to be indexed. However, the main index acts as an archive and holds data that never changes. What is SphinxQL? Programmers normally issue search queries using one or more client libraries that relate to the database on which the search is to be performed. Some programmers may also find it easier to write an SQL query than to use the Sphinx Client API library. SphinxQL is used to issue search queries in the form of SQL queries. These queries can be fired from any client of the database in question, and returns the results in the way that a normal query would. Currently MySQL binary network protocol is supported and this enables Sphinx to be accessed with the regular MySQL API. What do you mean by Geo-distance search? In a Geo-distance search, you can find geo coordinates nearby to the base anchor point. Thus you can use this technique to find the nearby places to the given location. It can be useful in many applications like hotel search, property search, restaurant search, tourist destination search etc. Sphinx makes it very easy to perform a geo-distance search by providing an API method wherein you can set the anchor point (if you have latitude and longitude in your index) and all searches performed thereafter will return the results with a magic attribute "@geodist" holding the values of distance from the anchor point. You can then filter or sort your results based on this attribute.   Further resources on this subject: Sphinx: Index Searching [Article] Getting Started with Sphinx Search [Article] Search Engine Optimization in Joomla! [Article] Blogger: Improving Your Blog with Google Analytics and Search Engine Optimization [Article] Drupal 6 Search Engine Optimization [Book]
Read more
  • 0
  • 0
  • 6671

article-image-getting-started-internet-explorer-mobile
Packt
23 May 2011
13 min read
Save for later

Getting Started with Internet Explorer Mobile

Packt
23 May 2011
13 min read
  Microsoft SharePoint 2010 Enterprise Applications on Windows Phone 7 Create enterprise-ready websites and applications that access Microsoft SharePoint on Windows Phone 7 To get started with Internet Explorer Mobile let's look at basic web page architecture.   Web page architecture Web pages on the client side mainly consist of three vital components: HTML, CSS, and JavaScript. The exact version of each of these varies, but in the end it all comes down to these three pieces. HyperText Markup Language (HTML) HyperText Markup Language (HTML) is the container for the page content. The page should contain just that content and nothing else. A properly coded site would leave the presentation and functionality portions of the page to CSS and JavaScript. In addition, the content should be constructed in a manner that makes logical sense for the content that is being delivered. This is called semantic HTML. People with disabilities use devices, such as a screen reader, to get the content of a site. These screen readers can only gather information from the actual markup of the site. If we have a PNG image with text in it, the screen reader cannot "see" that information. In that particular case, we can use the alt attribute of the image to provide a hint to the content, but it would be better to put the content inside a paragraph, unordered list, or some other textual tag and then replace it with an image if absolutely required using JavaScript. The other case that was mentioned earlier was that search engines can better determine the contents of a web page with semantic markup. This will help our page rankings and hopefully drive more visitors to our site. Think about the HTML markup like the script of a movie. Although we'll add lights, actors, and probably special effects later, right now the black and white text on paper has to convey all of the meaning. The same is true of the HTML markup for your site. As you build websites, constantly keep in mind what information you are trying to impart with the page and make that the focus. Cascading Style Sheets (CSS) Cascading Style Sheets (CSS) are documents that describe the way HTML should be displayed. The CSS language allows the web developer to separate the design aspects (layout, colors, fonts, and so on) from the page content. One could easily change the entire look and feel of a page simply by replacing the CSS files. An amazing group of examples of this is available at http://csszengarden.com. The CSS Zen Garden website demonstrates the amazing power that CSS has on the presentation of HTML content. Utilizing a proper style sheet can result in content that will quickly display the relevant information that a Windows Phone 7 user has come to expect from the applications on the phone. When developing websites that are going to be viewed on Internet Explorer Mobile, it is important to keep in mind some very important potential problems. Although float works great on desktop browsers and will work on many mobile browsers, the content within these containers may not look good on a small screen. The CSS float attribute was one of the first tools that allowed web developers to break free from table based layouts, that is, laying out the contents of a page using tables. Float allowed developers to group content in div elements and then float those block elements into position. It is a very powerful tool, but on a mobile device, the limited screen size would hamper the ability for the user to view the content. Instead, they would be constantly scrolling left and right or up and down to find all the content. A better way of handling this would be to utilize float on the desktop version of the site and then leave the div elements in block display allowing the IE Mobile browser to handle the content layout. Along these same lines, the CSS attributes, padding and margin, work great for precise positioning of elements on a desktop browser. However, the limited screen real-estate of a Mobile browser limits the usefulness of this positioning power. Try to limit the use of these attributes on the mobile device and only use them to highlight useful information. Finally, because pixels are absolute values, a pixel is a precise defined scale of measurement with no room for interpretation; the phone has to work more to display those elements that are positioned using pixel measurements. Using points, em, or percentage measurements instead, allow the phone to be more fluid with the layout. Be sure to test the site on Windows Phone 7 devices to ensure the content is legible and the display is fine. JavaScript JavaScript, otherwise known as ECMAScript, is the scripting language that is used to create dynamic user interfaces and allow a page to update "on the fly". Users have come to expect a certain fluidity to their web experiences, and now with the power of Internet Explorer Mobile for Windows Phone 7, they can have that same power in the palm of their hand. Remember that the user is probably looking at a 3.5 inch screen, has fingers that are roughly 40-80 pixels square, and those fingers are incapable of registering a hover command to the browser. If your navigation, for example, requires the user to hover over something, this will not work in Internet Explorer Mobile. Instead, make the navigation an easy to use, unordered list of hyperlinks Putting HTML, CSS, and JavaScript together Windows Phone 7 is about getting the relevant information viewable with minimal fuss. The following are some tips for creating a website for Windows Phone 7's Internet Explorer Mobile: Show only the content that is relevant for the page requested Reduce the use of images and colors Remove the extra-large hero images Hero images are those large images usually at the top of the main content section, but usually used as a graphic headline. Usually, they don't contain any content and only serve to enhance the design of the site. Rearrange the navigation to take up a minimum amount of space Move the navigation to the bottom of the page if possible Remove flashy loading screens Utilizing HTML, CSS, and JavaScript with proper discipline will result in more satisfied customers. Developing websites is not a trivial task. Mastering each of these three components is a great task. It is important, while developing websites, to try and minimize as much duplication as possible, not only in the JavaScript code that so many developers tended to focus on, but also in the CSS and the HTML content. Reducing duplication will allow for maintainable, upgradable, and understandable code. Also, by reducing duplication, the amount of data sent to the browser is also reduced. This is helpful when dealing with a browser that is connecting from a patchy cellular network. Historically, building a mobile version of a website meant a completely different team of designers and web developers built a totally separate web application from the desktop version of the site. Then, using the server side code, the mobile browsers were detected and redirected to the mobile version. SharePoint does this by redirecting mobile browsers to {server}/_layout/mobile/mblwiki.aspx?Url=%2FSitePages%2FHome%2Easpx as an example. When starting a new web application, a general rule of thumb is to use content adaptation techniques for the application. However, for a baseline you must have at least: ECMAScript 3 W3C DOM Level 1 W3C standard box model support CSS2 rendering Client-side cookies support XMLHttpRequest object support By targeting this lowest common denominator of browser, we will ensure that our web applications will run well on most browsers on the web. Remember that common practices on desktop browsers may end up being annoyances on a mobile device. Try not to open modal dialog boxes, or even open pop-ups. Opening a pop-up window will cause a whole new tab to appear. This may even close a tab that the user had previously opened if they already had six tabs open. When designing the user interaction for a website, always keep the user in mind. They are busy people coming to your website. Be kind to them. Give them the information they are looking for without hassle.   Internet Explorer Mobile Windows Phone 7 comes with a new browser that is based on the rendering engine of Internet Explorer 7 and some JavaScript improvements from Internet Explorer 8. Additionally, it includes some enhancements that aren't found in either of those desktop browsers. Internet Explorer Mobile User Agent The Internet Explorer Mobile User Agent string is as follows: Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; <DeviceManufacturer>; <DeviceModel>) This UA String allows the device manufacturer to insert their name and the model of the phone in the string. Knowing the User Agent string is helpful when reviewing server logs to determine what browsers are coming to your website. This will help you optimize your site for the people who actually are viewing your content. Like previous versions of Internet Explorer Mobile, the user can select either a Mobile version or a Desktop version display engine. When the Desktop version is selected, the User Agent string changes to the following: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; XBLWP7; ZuneWP7) Changing the display engine mode can be accomplished on the Internet Explorer SETTINGS screen, as shown in the following screenshot: Although this choice could complicate things, as we develop our sites, we should make careful consideration of how we are going to treat the mobile version, but try not to detect the desktop version. If the user makes a conscious choice to view the desktop version, we should not force them to view something different from what they would see on a real desktop browser. Client side browser detection Many people use the user agent string to detect at runtime what to display on the browser. Although this works, there are better techniques to find out if the browser is mobile. Those techniques should be used instead of User Agent detection. Using property detection instead of browser detection will allow your site to be forward compatible. Forward compatibility isn't a very complex idea. It is just thinking about programming so that as new browsers come along with new capabilities, we won't have to rewrite our applications to take advantage of these capabilities. The application just takes advantage of whatever functionality is available to it in whatever browser in which it is currently running. An example of property detection is as follows: function hasAdvancedDOM() { // check for a feature that is known to be advanced if(document.getElementsByClassName) return true; return false } Downloading the example code You can download the example code files from here The preceding code simply detects if the DOM function document.getElementsByClassName() exists or not. Internet Explorer Mobile has this function, as does Firefox 2+, Safari, Chrome, and Internet Explorer 9. However, previous versions of Internet Explorer Mobile did not have this function. If we had this in a previous version of a website, we wouldn't have to do anything special to get this to work in Windows Phone 7's Internet Explorer Mobile. Although, the code we would actually write in a web page would be much more complicated, this example demonstrates a starting point. Server-side detection Server-side detection usually uses the User Agent string along with a large list of mobile device User Agent strings to determine the capabilities of the browsers requesting a page. This list of mobile devices and their capabilities are kept in a .browser file. There are some projects on the web to keep and maintain this .browser file. The best known of these, "Mobile Device Browser File", available at http://mdbf.codeplex.com, lost funding from Microsoft. There is another one that can be found at http://aspnet.codeplex.com/releases/view/41420. The main topic of this article is SharePoint 2010 development for Windows Phone 7. However, ASP.NET 3.5 SP1 is the framework that SharePoint 2010 development is based on. This framework has a smaller list of browsers in the .browser file than the more current ASP.NET 4. One of the omissions is IEMobile. What this means is that in ASP.NET 4, you can use the following code to detect a mobile browser: Request.Browser.IsMobileDevice This code will work in ASP.NET 3.5 SP1, but it will not return true for Windows Phone 7's Internet Explorer Mobile by default. The simplest solution is to use code like this to detect the IE Mobile browser: Request.UserAgent.ToString().Contains("IEMobile") We could probably do better here. In the first place, we could update SharePoint's compat.browser file to include Windows Phone 7. The compat.browser can be found here: <drive>:inetpubwwwrootwssVirtualDirectories<site>80App_Browserscompat.browser The structure of this file can be found at the following URL: http://msdn.microsoft.com/en-us/library/ms228122.aspx If you look at SharePoint's compat.browser file, the fourth browser listed looks like it might be for the Windows Phone 7 Internet Explorer Mobile. However, a closer examination will show that this browser is actually for the Office Hub in Windows Phone 7. To add the Internet Explorer Mobile browser, copy the browser elements for Internet Explorer Mobile for Windows Mobile 6.5 and edit it like this: <browser id="IE7MobileDesktopMode" parentID="IE6to9"> <identification> <userAgent match="XBLWP7" /> </identification> <capabilities> <capability name="supportsTouchScreen" value="true" /> </capabilities> </browser> <browser id=”IE7MobileMobileMode” parentID=”Mozilla”> <identification> <userAgent match="(?i)Windows Mobile OSs7.d.*IEMobile/ (?'version'd+).(?'minor'd+)" /> </identification> <capabilities> <capability name="browser" value="IE Mobile" /> <capability name="canInitiateVoiceCall" value="true" /> <capability name="isMobileDevice" value="true" /> <capability name="javascript" value="true" /> <capability name="optimumPageWeight" value="1500" /> <capability name="tables" value="true" /> <capability name="version" value="${version}" /> <capability name="supportsTouchScreen" value="true" /> </capabilities> </browser> This will make our code easier to manage later by allowing us to use the Request.Browser.IsMobileDevice property. The change here, besides changing the browser ID, is in the regular expression which is used to detect the browser. In the desktop mode, we look for the text, XBLWP7, as this is a very obvious change in the User Agent in this state. For the mobile mode, we copied the IE Mobile 6 plus browser section. Microsoft changed the User Agent slightly between IE Mobile 6 and IE Mobile 7. The change comes in the User Agent, IE Mobile 7 doesn't have a space between the browser name IEMobile and the start of the version number. Instead, it has a forward slash. IE Mobile 6 had a space between the browser name and the version number.  
Read more
  • 0
  • 0
  • 2521

article-image-using-nginx-reverse-proxy
Packt
23 May 2011
7 min read
Save for later

Using Nginx as a Reverse Proxy

Packt
23 May 2011
7 min read
  Nginx 1 Web Server Implementation Cookbook Over 100 recipes to master using the Nginx HTTP server and reverse proxy         Read more about this book       (For more resources on Nginx, see here.) Introduction Nginx has found most applications acting as a reverse proxy for many sites. A reverse proxy is a type of proxy server that retrieves resources for a client from one or more servers. These resources are returned to the client as though they originated from the proxy server itself. Due to its event driven architecture and C codebase, it consumes significantly lower CPU power and memory than many other better known solutions out there. This article will deal with the usage of Nginx as a reverse proxy in various common scenarios. We will have a look at how we can set up a rail application, set up load balancing, and also look at a caching setup using Nginx, which will potentially enhance the performance of your existing site without any codebase changes.   Using Nginx as a simple reverse proxy Nginx in its simplest form can be used as a reverse proxy for any site; it acts as an intermediary layer for security, load distribution, caching, and compression purposes. In effect, it can potentially enhance the overall quality of the site for the end user without any change of application source code by distributing the load from incoming requests to multiple backend servers, and also caching static, as well as dynamic content. How to do it... You will need to first define proxy.conf, which will be later included in the main configuration of the reverse proxy that we are setting up: proxy_redirect off;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;client_max_body_size 10m;client_body_buffer_size 128k;proxy_connect_timeout 90;proxy_send_timeout 90;proxy_read_timeout 90;sproxy_buffers 32 4k To use Nginx as a reverse proxy for a site running on a local port of the server, the following configuration will suffice: server { listen 80; server_name example1.com; access_log /var/www/example1.com/log/nginx.access.log; error_log /var/www/example1.com/log/nginx_error.log debug;location / { include proxy.conf; proxy_pass http://127.0.0.1:8080; }} How it works... In this recipe, Nginx simply acts as a proxy for the defined backend server which is running on the 8080 port of the server, which can be any HTTP web application. Later in this article, other advanced recipes will have a look at how one can define more backend servers, and how we can set them up to respond to requests.   Setting up a rails site using Nginx as a reverse proxy In this recipe, we will set up a working rails site and set up Nginx working on top of the application. This will assume that the reader has some knowledge of rails and thin. There are other ways of running Nginx and rails, as well, like using Passenger Phusion. How to do it... This will require you to set up thin first, then to configure thin for your application, and then to configure Nginx. If you already have gems installed then the following command will install thin, otherwise you will need to install it from source: sudo gem install thin Now you need to generate the thin configuration. This will create a configuration in the /etc/thin directory: sudo thin config -C /etc/thin/myapp.yml -c /var/rails/myapp--servers 5 -e production Now you can start the thin service. Depending on your operating system the start up command will vary. Assuming that you have Nginx installed, you will need to add the following to the configuration file: upstream thin_cluster { server unix:/tmp/thin.0.sock; server unix:/tmp/thin.1.sock; server unix:/tmp/thin.2.sock; server unix:/tmp/thin.3.sock; server unix:/tmp/thin.4.sock;} server { listen 80; server_name www.example1.com; root /var/www.example1.com/public; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect false; try_files $uri $uri/index.html $uri.html @thin; location @thin { include proxy.conf; proxy_pass http://thin_cluster; } } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }} How it works... This is a fairly simple rails stack, where we basically configure and run five upstream thin threads which interact with Nginx through socket connections. There are a few rewrites that ensure that Nginx serves the static files, and all dynamic requests are processed by the rails backend. It can also be seen how we set proxy headers correctly to ensure that the client IP is forwarded correctly to the rails application. It is important for a lot of applications to be able to access the client IP to show geo-located information, and logging this IP can be useful in identifying if geography is a problem when the site is not working properly for specific clients.   Setting up correct reverse proxy timeouts In this section we will set up correct reverse proxy timeouts which will affect your user's interaction when your backend application is unable to respond to the client's request. In such a case, it is advisable to set up some sensible timeout pages so that the user can understand that further refreshing may only aggravate the issues on the web application. How to do it... You will first need to set up proxy.conf which will later be included in the configuration: proxy_redirect off;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;client_max_body_size 10m;client_body_buffer_size 128k;proxy_connect_timeout 90;proxy_send_timeout 90;proxy_read_timeout 90;sproxy_buffers 32 4k Reverse proxy timeouts are some fairly simple flags that we need to set up in the Nginx configuration like in the following example: server { listen 80; server_name example1.com; access_log /var/www/example1.com/log/nginx.access.log; error_log /var/www/example1.com/log/nginx_error.log debug; #set your default location location / { include proxy.conf; proxy_read_timeout 120; proxy_connect_timeout 120; proxy_pass http://127.0.0.1:8080; }} How it works... In the preceding configuration we have set the following variables, it is fairly clear what these variables achieve in the context of the configurations:   Setting up caching on the reverse proxy In a setup where Nginx acts as the layer between the client and the backend web application, it is clear that caching can be one of the benefits that can be achieved. In this recipe, we will have a look at setting up caching for any site to which Nginx is acting as a reverse proxy. Due to extremely small footprint and modular architecture, Nginx has become quite the Swiss knife of the modern web stack. How to do it... This example configuration shows how we can use caching when utilizing Nginx as a reverse proxy web server: http { proxy_cache_path /var/www/cache levels=1:2 keys_zone=my-cache:8mmax_size=1000m inactive=600m; proxy_temp_path /var/www/cache/tmp;...server { listen 80; server_name example1.com; access_log /var/www/example1.com/log/nginx.access.log; error_log /var/www/example1.com/log/nginx_error.log debug; #set your default location location / { include proxy.conf; proxy_pass http://127.0.0.1:8080/; proxy_cache my-cache; proxy_cache_valid 200 302 60m; proxy_cache_valid 404 1m; }}} How it works... This configuration implements a simple cache with 1000MB maximum size, and keeps all HTTP response 200 pages in the cache for 60 minutes and HTTP response 404 pages in cache for 1 minute. There is an initial directive that creates the cache file on initialization, in further directives we basically configure the location that is going to be cached. It is possible to actually set up more than one cache path for multiple locations. There's more... This was a relatively small show of what can be achieved with the caching aspect of the proxy module. Here are some more directives that can be really useful in optimizing and making your stack faster and more efficient:  
Read more
  • 0
  • 0
  • 15590

article-image-high-availability-oracle-11g-r1-r2-real-application-clusters-rac
Packt
20 May 2011
12 min read
Save for later

High Availability: Oracle 11g R1 R2 Real Application Clusters (RAC)

Packt
20 May 2011
12 min read
High availability is a discipline within database technology that provides a solution to protect against data loss and against downtime, which is costly to mission-critical database systems. As such, we will provide details on what constitutes high availability and what does not. By having the proper framework, you will understand how to leverage Oracle RAC and auxiliary technologies including Oracle Data Guard to maximize the Return On Investment (ROI) for your data center environment. High availability concepts High availability provides data center environments that run mission-critical database applications with the resiliency to withstand failures that may occur due to natural, human, or environmental conditions. For example, if a hurricane wipes out the production data center that hosts a financial application's production database, high availability would provide the much-needed protection to avoid data loss, minimize downtime, and maximize the availability of the firm's resources and database applications. Let's now move to the high availability concepts. Planned versus unplanned downtime The distinction needs to be made between planned downtime and unplanned downtime. In most cases, planned downtime is the result of maintenance that is disruptive to system operations and cannot be avoided with current system designs for a data center. An example of planned downtime would be a DBA maintenance activity such as database patching to an Oracle database, which would require taking an outage to take the system offline for a period of time. From the database administrator's perspective, planned downtime situations usually are the result of management-initiated events. On the other hand, unplanned downtime issues frequently occur due to a physical event caused by a hardware, software, or environmental failure or caused by human error. A few examples of unplanned downtime events include hardware server component failures such as CPU, disk, or power outages. Most data centers will exclude planned downtime from the high availability factor in terms of calculating the current total availability percentage. Even so, both planned and unplanned maintenance windows affect high availability. For instance, database upgrades require a few hours of downtime. Another example would be a SAN replacement. Such items make comprehensive four nine solutions nigh impossible to implement without additional considerations. The fact is that implementing a true 100% high availability is nearly impossible without exorbitant costs. To have complete high availability for all components within the data center requires an architecture for all systems and databases that eliminates any Single Point of Failure (SPOF) and allows for total online availability for all server hardware, network, operating systems, applications, and database systems. Service Level Agreements for high availability When it comes to determining high availability ratios, this is often expressed as the percentage of uptime in a given year. The following table shows the approximate downtime that is allowed for a specific percentage of high availability, granted that the system is required to operate continuously. Service Level Agreements (SLAs) usually refer to monthly downtime or availability in order to calculate service levels to match monthly financial cycles. The following table from the International Organization for Standardization (ISO) illustrates the correlation between a given availability percentage and the relevant amount of time a system would be unavailable per year, month, or week: For monthly calculations, a 30-day month is used. It should be noted that availability and uptimes are not the same thing. For instance, a database system may be online but not available, as in the case of application outages such as when a user's SQL script cannot be executed. In most cases, the number of nines is not often used by the database or system professional when measuring high availability for data center environments because it is difficult to extrapolate such hard numbers without a large test environment. For practical purposes, availability is calculated more as a probability or average downtime given per annual basis. High availability interpretations When it comes to discussing how availability is measured, there is a debate on the correct method of interpretation for high availability ratios. For instance, an Oracle database server that has been online for 365 days in a given non-leap year might have been eclipsed by an application failure that lasted for nine hours during a peak usage period. As a consequence, the users will see the complete system as unavailable, whereas the Oracle database administrator will claim 100% "uptime." However, given the true definition of availability, the Oracle database will be approximately 99.897% available (8751 hours of available timeout of 8760 hours per non-leap year). Furthermore, Oracle database systems experiencing performance problems are often deemed partially or entirely unavailable by users, while in the eyes of the database administrator the system is fine and available. Another situation that presents a challenge in terms of what constitutes availability would be the scenario in which the availability of a mission-critical application might go offline yet is not viewed as unavailable by the Oracle DBA, as the database instance could still be online and thus available. However, the application in question is offline to the end user, thus presenting a status of unavailable from the perspective of the end user. This illustrates the key point that a true availability measure must be from a holistic perspective and not strictly from the database's point of view. Availability should be measured with comprehensive monitoring tools that are themselves highly available and present the proper instrumentation. If there is a lack of instrumentation, systems supporting high-volume transaction processing frequently during the day and night, such as credit-card-processing database servers, are often inherently better monitored than systems that experience a periodic lull in demand. Currently, custom scripts can be developed in conjunction with third-party tools to provide a measure of availability. One such tool that we recommend for monitoring database, server, and application availability is that provided by Oracle Grid Control, which also includes Oracle Enterprise Manager. Oracle Grid Control provides instrumentation via agents and plugin modules to measure availability and performance on a system-wide enterprise level, thereby greatly aiding the Oracle database professional to measure, track, and report to management and users on the status of availability with all mission-critical applications and system components. However, the current version of Oracle Enterprise Manager will not provide a true picture of availability until 11g Grid Control is released in the future. Recovery time and high availability Recovery time is closely related to the concept of high availability. Recovery time varies based on system design and failure experienced, in that a full recovery may well be impossible if the system design prevents such recovery options. For example, if the data center is not designed correctly with the required system and database backups and a standby disaster recovery site in place, then a major catastrophe such as a fire or earthquake will almost always result in complete unavailability until a complete MAA solution is implemented. In this case, only a partial recovery may be possible. This drives home the point that for all major data center operations, you should always have a backup plan with an offsite secondary disaster-recovery data center to protect against losing all critical systems and data. In terms of database administration for Oracle data centers, the concept of data availability is essential when dealing with recovery time and planning for highly available options. Data availability references the degree to which databases such as Oracle record and report transactions. Data management professionals often focus just on data availability in order to judge what constitutes an acceptable data loss with different types of failure events. While application service interruptions are inconvenient and sometimes permitted, data loss is not to be tolerated. As one Chief Information Officer (CIO) and executive once told us while working for a large financial brokerage, you can have the system down to perform maintenance but never ever lose my data! The next item related to high availability and recovery standards is that of Service Level Agreements or SLAs for data center operations. The purpose of the Service Level Agreement is to actualize the availability objectives and requirements for a data center environment per business requirements into a standard corporate information technology (IT) policy. System design for high availability Ironically, by adding further components to the overall system and database architecture design, you may actually undermine your efforts to achieve true high availability for your Oracle data center environment. The reason for this is by their very nature, complex systems inherently have more potential failure points and thus are more difficult to implement properly. The most highly available systems for Oracle adhere to a simple design pattern that makes use of a single, high quality, multipurpose physical system with comprehensive internal redundancy running all interdependent functions, paired with a second like system at a separate physical location. An example would be to have a primary Oracle RAC clustered site with a second Disaster Recovery site at another location with Oracle Data Guard and perhaps dual Oracle RAC clusters at both sites connected by stretch clusters. The best possible way to implement an active standby site with Oracle would be to have Oracle Streams and Oracle Data Guard. Large commercial banking and insurance institutions would benefit from this model for Oracle data center design to maximize system availability. Business Continuity and high availability Business Continuity Planning (BCP) refers to the creation and validation of a rehearsed operations plan for the IT organization that explains the procedures of how the data center and business unit will recover and restore, partially or completely, interrupted business functions within a predetermined time after a major disaster. In its simplest terms, BCP is the foundation for the IT data center operations team to maintain critical systems in the event of disaster. Major incidents could include events such as fires, earthquakes, or national acts of terrorism. BCP may also encompass corporate training efforts to help reduce operational risk factors associated with the lack of information technology (IT) management controls. These BCP processes may also be integrated with IT standards and practices to improve security and corporate risk management practices. An example would be to implement BCP controls as part of Sarbanes-Oxley (SOX) compliance requirements for publicly traded corporations. The origins for BCP standards arose from the British Standards Institution (BSI) in 2006 when the BSI released a new independent standard for business continuity named BS 25999-1. Prior to the introduction of this standard for BCP, IT professionals had to rely on the previous BSI information security standard, BS 7799, which provided only limited standards for business continuity compliance procedures. One of the key benefits of these new standards was to extend additional practices for business continuity to a wider variety of organizations, to cover needs for public sector, government, non-profit, and private corporations. Disaster Recovery Disaster Recovery (DR) is the process, policies, and procedures related to preparing for recovery or continuation of technology infrastructure critical to an organization after either a natural or human-caused disaster. Disaster Recovery Planning (DRP) is a subset of larger processes such as Business Continuity and should include planning for resumption of applications, databases, hardware, networking, and other IT infrastructure components. A Business Continuity Plan includes planning for non-IT-related aspects, such as staff member activities, during a major disaster as well as site facility operations, and it should reference the Disaster Recovery Plan for IT-related infrastructure recovery and business continuity procedures and guidelines. Business Continuity and Disaster Recovery guidelines The following recommendations will provide you with a blueprint to formulate your requirements and implementation for a robust Business Continuity and Disaster Recovery plan: Identifying the scope and boundaries of your Business Continuity Plan:The first step enables you to define the scope of your new Business Continuity Plan. It provides you with an idea of the limitations and boundaries of the Business Continuity Plan. It also includes important audit and risk analysis reports for corporate assets. Conducting a Business Impact Analysis session:Business Impact Analysis (BIA) is the assessment of financial losses to institutions, which usually results as the consequence of destructive events such as the loss or unavailability of mission-critical business services. Obtaining support for your business continuity plans and goals from the executive management team:You will need to convince senior management to approve your business continuity plan, so that you can flawlessly execute your disaster recovery planning. Assign stakeholders as representatives on the project planning committee team, once approval is obtained from the corporate executive team. Understanding its specific role:In the possible event of a major disaster, each of your departments must be prepared to take immediate action. In order to successfully recover your mission-critical database systems with minimal loss, each team must understand the BCP and DRP plans, as well as follow them correctly. Furthermore, it is also important to maintain your DRP and BCP plans, as well as conduct periodic training of your IT staff members on a regular basis to have successful response time for emergencies. Such "smoke tests" to train and keep your IT staff members up to date on the correct procedures and communications will pay major dividends in the event of an unforeseen disaster. One useful tool for creating and managing BCP plans is available from the National Institute of Standards and Technologies (NIST). The NIST documentation can be used to generate templates that can be used as an excellent starting point for your Business Continuity and Disaster Recovery planning. We highly recommend that you download and review the following NIST publication for creating and evaluating BCP plans, Contingency Planning Guide for Information Technology Systems, which is available online at http://csrc.nist.gov/publications/nistpubs/800-34/sp800-34.pdf. Additional NIST documents may also provide insight into how best to manage new or current BCP or DRP plans. A complete listing of NIST publications is available online at http://csrc.nist.gov/publications/PubsSPs.html.
Read more
  • 0
  • 0
  • 3828

article-image-python-3-building-wiki-application
Packt
19 May 2011
17 min read
Save for later

Python 3: Building a Wiki Application

Packt
19 May 2011
17 min read
Python 3 Web Development Beginner's Guide Nowadays, a wiki is a well-known tool to enable people to maintain a body of knowledge in a cooperative way. Wikipedia (http://wikipedia.org) might be the most famous example of a wiki today, but countless numbers of forums use some sort of wiki and many tools and libraries exist to implement a wiki application. In this article, we will develop a wiki of our own, and in doing so, we will focus on two important concepts in building web applications. The first one is the design of the data layer. The second one is input validation. A wiki is normally a very public application that might not even employ a basic authentication scheme to identify users. This makes contributing to a wiki very simple, yet also makes a wiki vulnerable in the sense that anyone can put anything on a wiki page. It's therefore a good idea to verify the content of any submitted change. You may, for example, strip out any HTML markup or disallow external links. Enhancing user interactions in a meaningful way is often closely related with input validation. Client-side input validation helps prevent the user from entering unwanted input and is therefore a valuable addition to any application but is not a substitute for server-side input validation as we cannot trust the outside world not to try and access our server in unintended ways. The data layer A wiki consists of quite a number of distinct entities we can indentify. We will implement these entities and the relations that exist between them by reusing the Entity/Relation framework developed earlier. Time for action – designing the wiki data model As with any application, when we start developing our wiki application we must first take a few steps to create a data model that can act as a starting point for the development: Identify each entity that plays a role in the application. This might depend on the requirements. For example, because we want the user to be able to change the title of a topic and we want to archive revisions of the content, we define separate Topic and Page entities. Identify direct relations between entities. Our decision to define separate Topic and Page entities imply a relation between them, but there are more relations that can be identified, for example, between Topic and Tag. Do not specify indirect relations: All topics marked with the same tag are in a sense related, but in general, it is not necessary to record these indirect relations as they can easily be inferred from the recorded relation between topics and tags. The image shows the different entities and relations we can identify in our wiki application. In the diagram, we have illustrated the fact that a Topic may have more than one Page while a Page refers to a single User in a rather informal way by representing Page as a stack of rectangles and User as a single rectangle. In this manner, we can grasp the most relevant aspects of the relations at a glance. When we want to show more relations or relations with different characteristics, it might be a good idea to use more formal methods and tools. A good starting point is the Wikipedia entry on UML: http://en.wikipedia.org/wiki/Unified_Modelling_Language. What just happened? With the entities and relations in our data model identified, we can have a look at their specific qualities. The basic entity in a wiki is a Topic. A topic, in this context, is basically a title that describes what this topic is about. A topic has any number of associated Pages. Each instance of a Page represents a revision; the most recent revision is the current version of a topic. Each time a topic is edited, a new revision is stored in the database. This way, we can simply revert to an earlier version if we made a mistake or compare the contents of two revisions. To simplify identifying revisions, each revision has a modification date. We also maintain a relation between the Page and the User that modified that Page. In the wiki application that we will develop, it is also possible to associate any number of tags with a topic. A Tag entity consists simply of a tag attribute. The important part is the relation that exists between the Topic entity and the Tag entity. Like a Tag, a Word entity consists of a single attribute. Again, the important bit is the relation, this time, between a Topic and any number of Words. We will maintain this relation to reflect the words used in the current versions (that is, the last revision of a Page) of a Topic. This will allow for fairly responsive full text search facilities. The final entity we encounter is the Image entity. We will use this to store images alongside the pages with text. We do not define any relation between topics and images. Images might be referred to in the text of the topic, but besides this textual reference, we do not maintain a formal relation. If we would like to maintain such a relation, we would be forced to scan for image references each time a new revision of a page was stored, and probably we would need to signal something if a reference attempt was made to a non-existing image. In this case, we choose to ignore this: references to images that do not exist in the database will simply show nothing: Chapter6/wikidb.py from entity import Entity from relation import Relation class User(Entity): pass class Topic(Entity): pass class Page(Entity): pass class Tag(Entity): pass class Word(Entity): pass class Image(Entity): pass class UserPage(Relation): pass class TopicPage(Relation): pass class TopicTag(Relation): pass class ImagePage(Relation): pass class TopicWord(Relation): pass def threadinit(db): User.threadinit(db) Topic.threadinit(db) Page.threadinit(db) Tag.threadinit(db) Word.threadinit(db) Image.threadinit(db) UserPage.threadinit(db) TopicPage.threadinit(db) TopicTag.threadinit(db) ImagePage.threadinit(db) TopicWord.threadinit(db) def inittable(): User.inittable(userid="unique not null") Topic.inittable(title="unique not null") Page.inittable(content="", modified="not null default CURRENT_TIMESTAMP") Tag.inittable(tag="unique not null") Word.inittable(word="unique not null") Image.inittable(type="",data="blob",title="", modified="not null default CURRENT_TIMESTAMP", description="") UserPage.inittable(User,Page) TopicPage.inittable(Topic,Page) TopicTag.inittable(Topic,Tag) TopicWord.inittable(Topic,Word) Because we can reuse the entity and relation modules we developed earlier, the actual implementation of the database layer is straightforward (full code is available as wikidb.py). After importing both modules, we first define a subclass of Entity for each entity we identified in our data model. All these classes are used as is, so they have only a pass statement as their body. Likewise, we define a subclass of Relation for each relation we need to implement in our wiki application. All these Entity and Relation subclasses still need the initialization code to be called once each time the application starts and that is where the convenience function initdb() comes in. It bundles the initialization code for each entity and relation (highlighted). Many entities we define here are simple but a few warrant a closer inspection. The Page entity contains a modified column that has a non null constraint. It also has a default: CURRENT_TIMESTAMP (highlighted). This default is SQLite specific (other database engines will have other ways of specifying such a default) and will initialize the modified column to the current date and time if we create a new Page record without explicitly setting a value. The Image entity also has a definition that is a little bit different: its data column is explicitly defined to have a blob affinity. This will enable us to store binary data without any problem in this table, something we need to store and retrieve the binary data contained in an image. Of course, SQLite will happily store anything we pass it in this column, but if we pass it an array of bytes (not a string that is), that array is stored as is. The delivery layer With the foundation, that is, the data layer in place, we build on it when we develop the delivery layer. Between the delivery layer and the database layer, there is an additional layer that encapsulates the domain-specific knowledge (that is, it knows how to verify that the title of a new Topic entity conforms to the requirements we set for it before it stores it in the database): Each different layer in our application is implemented in its own file or files. It is easy to get confused, so before we delve further into these files, have a look at the following table. It lists the different files that together make up the wiki application and refers to the names of the layers. We'll focus on the main CherryPy application first to get a feel for the behavior of the application. Time for action – implementing the opening screen The opening screen of the wiki application shows a list of all defined topics on the right and several ways to locate topics on the left. Note that it still looks quite rough because, at this point, we haven't applied any style sheets: Let us first take a few steps to identify the underlying structure. This structure is what we would like to represent in the HTML markup: Identify related pieces of information that are grouped together. These form the backbone of a structured web page. In this case, the search features on the left form a group of elements distinct from the list of topics on the right. Identify distinct pieces of functionality within these larger groups. For example, the elements (input field and search button) that together make up the word search are such a piece of functionality, as are the tag search and the tag cloud. Try to identify any hidden functionality, that is, necessary pieces of information that will have to be part of the HTML markup, but are not directly visible on a page. In our case, we have links to the jQuery and JQuery UI JavaScript libraries and links to CSS style sheets. Identifying these distinct pieces will not only help to put together HTML markup that reflects the structure of a page, but also help to identify necessary functionality in the delivery layer because each of these functional pieces is concerned with specific information processed and produced by the server. What just happened? Let us look in somewhat more detail at the structure of the opening page that we identified. Most notable are three search input fields to locate topics based on words occurring in their bodies, based on their actual title or based on tags associated with a topic. These search fields feature auto complete functionality that allows for comma-separated lists. In the same column, there is also room for a tag cloud, an alphabetical list of tags with font sizes dependent on the number of topics marked with that tag. The structural components The HTML markup for this opening page is shown next. It is available as the file basepage.html and the contents of this file are served by several methods in the Wiki class implementing the delivery layer, each with a suitable content segment. Also, some of the content will be filled in by AJAX calls, as we will see in a moment: Chapter6/basepage.html <html> <head> <title>Wiki</title> <script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"> </script> <script src= "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/jquery-ui.min.js" type="text/javascript"> </script> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/ jqueryui/1.8.3/themes/smoothness/jquery-ui.css" type="text/css" media="all" /> <link rel="stylesheet" href="/wiki.css" type="text/css" media="all" /> </head> <body> <div id="navigation"> <div class="navitem"> <a href="./">Wiki Home</a> </div> <div class="navitem"> <span class="label">Search topic</span> <form id="topicsearch"> <input type="text" > <button type="submit" >Search</button> </form> </div> <div class="navitem"> <span class="label">Search word</span> <form id="wordsearch"> <input type="text" > <button type="submit" >Search</button> </form> </div> <div class="navitem"> <span class="label">Search tag</span> <form id="tagsearch"> <input type="text" > <button type="submit" >Search</button> </form> </div> <div class="navitem"> <p id="tagcloud">Tag cloud</p> </div> </div> <div id="content">%s</div> <script src="/wikiweb.js" type="text/javascript"></script> </body> </html> The <head> element contains both links to CSS style sheets and <script> elements that refer to the jQuery libraries. This time, we choose again to retrieve these libraries from a public content delivery network. The highlighted lines show the top-level <div> elements that define the structure of the page. In this case, we have identified a navigation part and a content part and this is reflected in the HTML markup. Enclosed in the navigation part are the search functions, each in their own <div> element. The content part contains just an interpolation placeholder %s for now, that will be filled in by the method that serves this markup. Just before the end of the body of the markup is a final <script> element that refers to a JavaScript file that will perform actions specific to our application and we will examine those later. The application methods The markup from the previous section is served by methods of the Wiki class, an instance of which class can be mounted as a CherryPy application. The index() method, for example, is where we produce the markup for the opening screen (the complete file is available as wikiweb.py and contains several other methods that we will examine in the following sections): Chapter6/wikiweb.py @cherrypy.expose def index(self): item = '<li><a href="show?topic=%s">%s</a></li>' topiclist = "n".join( [item%(t,t)for t in wiki.gettopiclist()]) content = '<div id="wikihome"><ul>%s</ul></div>'%( topiclist,) return basepage % content First, we define the markup for every topic we will display in the main area of the opening page (highlighted). The markup consists of a list item that contains an anchor element that refers to a URL relative to the page showing the opening screen. Using relative URLs allows us to mount the class that implements this part of the application anywhere in the tree that serves the CherryPy application. The show() method that will serve this URL takes a topic parameter whose value is interpolated in the next line for each topic that is present in the database. The result is joined to a single string that is interpolated into yet another string that encapsulates all the list items we just generated in an unordered list (a <ul> element in the markup) and this is finally returned as the interpolated content of the basepage variable. In the definition of the index() method, we see a pattern that will be repeated often in the wiki application: methods in the delivery layer, like index(), concern themselves with constructing and serving markup to the client and delegate the actual retrieval of information to a module that knows all about the wiki itself. Here the list of topics is produced by the wiki.gettopiclist() function, while index() converts this information to markup. Separation of these activities helps to keep the code readable and therefore maintainable. Time for action – implementing a wiki topic screen When we request a URL of the form show?topic=value, this will result in calling the show() method. If value equals an existing topic, the following (as yet unstyled) screen is the result: Just as for the opening screen, we take steps to: Identify the main areas on screen Identify specific functionality Identify any hidden functionality The page structure is very similar to the opening screen, with the same navigational items, but instead of a list of topics, we see the content of the requested topic together with some additional information like the tags associated with this subject and a button that may be clicked to edit the contents of this topic. After all, collaboratively editing content is what a Wiki is all about. We deliberately made the choice not to refresh the contents of just a part of the opening screen with an AJAX call, but opted instead for a simple link that replaces the whole page. This way, there will be an unambiguous URL in the address bar of the browser that will point at the topic. This allows for easy bookmarking. An AJAX call would have left the URL of the opening screen that is visible in the address bar of the browser unaltered and although there are ways to alleviate this problem, we settle for this simple solution here. What just happened? As the main structure we identified is almost identical to the one for the opening page, the show() method will reuse the markup in basepage.html. Chapter6/wikiweb.py @cherrypy.expose def show(self,topic): topic = topic.capitalize() currentcontent,tags = wiki.gettopic(topic) currentcontent = "".join(wiki.render(currentcontent)) tags = ['<li><a href="searchtags?tags=%s">%s</a></li>'%( t,t) for t in tags] content = ''' <div> <h1>%s</h1><a href="edit?topic=%s">Edit</a> </div> <div id="wikitopic">%s</div> <div id="wikitags"><ul>%s</ul></div> <div id="revisions">revisions</div> ''' % ( topic, topic, currentcontent,"n".join(tags)) return basepage % content The show() method delegates most of the work to the wiki.gettopic() method (highlighted) that we will examine in the next section and concentrates on creating the markup it will deliver to the client. wiki.gettopic() will return a tuple that consists of both the current content of the topic and a list of tags. Those tags are converted to <li> elements with anchors that point to the searchtags URL. This list of tags provides a simple way for the reader to find related topics with a single click. The searchtags URL takes a tags argument so a single <li> element constructed this way may look like this: <li><a href="searchtags?tags=Python">Python</a></li>. The content and the clickable list of tags are embedded in the markup of the basepage together with an anchor that points to the edit URL. Later, we will style this anchor to look like a button and when the user clicks it, it will present a page where the content may be edited.  
Read more
  • 0
  • 0
  • 22449
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-html5-developing-rich-media-applications-using-canvas
Packt
19 May 2011
10 min read
Save for later

HTML5: Developing Rich Media Applications using Canvas

Packt
19 May 2011
10 min read
HTML5 Multimedia Development Cookbook Recipes for practical, real-world HTML5 multimedia driven development. The cool thing with the new open-source canvas element is that not only can you create dynamic images on the fly, but the users' actions can create new images in real time as well—all without requiring a plugin. Sounds great, right? In many ways it is, but it also leaves our friends using assistive technologies out in the cold. What will happen if you're using a browser that doesn't support the new canvas element? Pretty much nothing. The browser just won't display it. That's why you'll need to be especially careful with this technology and not place anything inside the new canvas element on which your site or application absolutely depends. You must also consider fallback content. Browsers that support canvas include: Before proceeding with developing with the new canvas element, make sure you have a good foundation of skills with HTML and JavaScript. Being comfortable with object-oriented programming sure wouldn't hurt either. Now, let's get cooking! Setting up the canvas environment Creating the new canvas element is easy. How to do it... Check out how simple this is: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> How it works... Of course, we can use whatever height and width dimensions we need, but that simple set of tags is what we need to start. You're probably thinking we could use CSS to control the height and width, but resist that temptation. Because the new canvas element contains a 2d rendering context, that approach can cause unpredictable behavior. There's more... Next, we'll call the new canvas element JavaScript API while calling jQuery: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); }); </script> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> He's smart "Let me make one thing completely clear: When you use canvas, you're not drawing on the canvas element itself. Instead, you're actually drawing on the 2d rendering context, which you're accessing through the canvas element via the JavaScript API." – Rob Hawkes What am I sayin'? Apple first introduced the new canvas element for the OSX Dashboard years ago. It was later implemented in web browsers Safari and then Chrome, with other browsers following suit. Since then it's become an official part of the HTML5 specification. What's next for <canvas>? Right now, we're barely scratching the surface of what the new canvas element can do. Now and in the future we'll use it to create animations, charts, diagrams, drawing apps, graphs, and user interfaces. What will you dream up? See also Developer Martin Angelov penned a great how-to guide titled, "An HTML5 Slideshow w/Canvas & jQuery" for Tutorial Zine at: http://tutorialzine.com/2010/09/html5-canvas-slideshow-jquery. In it, Martin demonstrates how to combine the new canvas element with jQuery, the most popular JavaScript framework, to create an intensely interactive image slideshow. Understanding the 2d rendering context It's important to understand that the new canvas element is really a "surface" on which to draw bitmapped images in the browser. How to do it... Defining a canvas tag like this only tells half the story: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> How it works... By itself that HTML5 code does nothing. We have to use JavaScript to make the Document Object Model retrieve the 2d rendering context in order to get something to happen: <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); }); </script> To be fair, that bit of JavaScript won't do anything without the canvas tag in the HTML either. There's more... You may be wondering about the name. If there's a 2d rendering context, isn't there probably a 3d rendering context too? The short answer is yes. But the more detailed answer isn't so simple. While a 3d rendering context does exist in theory, at the time of this publication no browser supports it. So if the new canvas element renders in 3d but nobody sees it, did it really do anything? You can master <canvas> The 2d context uses a number of different drawing contexts for the new canvas element that use syntaxes that should look quite familiar if you're experienced with CSS and JavaScript. X, meet Y When drawing, remember the X and Y axis in the top left corner of your browser window. Values increase going down the page. Respect my authority! The World Wide Web Consortium's HTML5 Canvas 2d Context specification is online at: http://dev.w3.org/html5/2dcontext. There we can dig even deeper into information like conformance requirements, the canvas state, transformations, compositing, colors and styles, line styles, shadows, simple shapes, complex shapes, focus management, text, images, pixel manipulation, drawing model, examples, and more. Processing shapes dynamically Let's look at the JavaScript functions that allow the new canvas element to draw rectangles. How to do it... fillRect(x,y,width,height) strokeRect(x,y,width,height) In order: fillRect(x,y,width,height) draws a filled rectangle. Next, strokeRect(x,y,width,height) draws an outline around the rectangle. Now, let's draw some shapes. How it works... We'll start with our basic canvas code and incorporate our new functions: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeRect(10, 10, 396, 236); ctx.fillStyle = "red"; ctx.fillRect(11, 11, 100, 100); ctx.fillStyle = "white"; ctx.fillRect(111, 11, 34, 100); ctx.fillStyle = "red"; ctx.fillRect(156, 11, 249, 100); ctx.fillStyle = "white"; ctx.fillRect(11, 111, 394, 34); ctx.fillStyle = "red"; ctx.fillRect(11, 145, 100, 100); ctx.fillStyle = "white"; ctx.fillRect(111, 145, 34, 100); ctx.fillStyle = "red"; ctx.fillRect(156, 145, 249, 100); }); </script> </head> <body> <canvas id="FirstCanvas" width="416" height="256"> <p>Flag of Denmark</p> </canvas> </body> </html> What we've created resembles the flag of Denmark! There's more... This example may not seem overwhelming at first, but when you remember that we've created an image with hardly any HTML and no CSS whatsoever, the new canvas element starts to look pretty impressive. Any way you want it Note that while we used color names ("white" and "red") we could also use hexadecimal values or RGB or even HSL! Use whatever makes the most sense for you and your interactive project. Similar to tables? Think of the color and size specifications for this example almost as the old-school tables we used to build back in the day for layout. While certainly not the same, there are definitely similarities to that technique in this case. Be a square first Mastering rectangles is the first canvas technique that's important to have under your belt after the ability to set up the element itself. Understanding the basics of this approach will help you grasp the fundamentals of the next few recipes. Drawing borders for images using canvas Let's take a closer look at the super simple method of drawing borders around images using the new canvas element. How to do it... First, we'll start with our basic canvas code and add one new line to draw a border: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("FirstCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeRect(10, 20, 100, 100); }); </script> </head> <body> <canvas id="FirstCanvas" width="800" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> How it works... That one line of JavaScript tells the browser to create a rectangle starting at 10 pixels from the left and 20 pixels from the top of the new canvas element. It draws the box 100 pixels square. There's more... That's nice, but if we want the border to be any other color than the default, we'll need to specify that: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.strokeStyle = "rgb(0, 128, 0)"; ctx.strokeRect(10, 20, 100, 100); }); </script> </head> <body> <canvas id="myCanvas" width="600" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> In this case we've used strokeStyle to specify an RGB color of pure green. Style first If you plan to style a border, you'll need to specify that before the border is drawn by the browser. If you specify that style afterward, the browser will simply ignore it. Many color values work The style attribute we just used was RGB, but the method also works with colors ("green", for example), hexadecimal values, HSL, and RGBA. I like big borders and I cannot lie If no border width is specified, the browser will automatically draw a one-pixel border. Here's how to change that: <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/ jquery.min.js"></script> <script> $(document).ready(function() { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.lineWidth = 10; ctx.strokeStyle = "rgb(0, 128, 0)"; ctx.strokeRect(10, 20, 100, 100); }); </script> </head> <body> <canvas id="myCanvas" width="600" height="600"> <!-- Fallback code goes here --> </canvas> </body> </html> It's just this easy:  
Read more
  • 0
  • 0
  • 3048

article-image-sql-query-basics-sap-business-one
Packt
18 May 2011
7 min read
Save for later

SQL Query Basics in SAP Business One

Packt
18 May 2011
7 min read
  Mastering SQL Queries for SAP Business One Utilize the power of SQL queries to bring Business Intelligence to your small to medium-sized business Who can benefit from using SQL Queries in SAP Business One? There are many different groups of SAP Business One users who may need this tool. To my knowledge, there is no standard organization chart for Small and Midsized enterprises. Most of them are different. You may often find one person that handles more than one role. You may check the following list to see if anything applies to you: Do you need to check specific sales results over certain time periods, for certain areas or certain customers? Do you want to know who the top vendors from certain locations for certain materials are? Do you have dynamic updated version of your sales force performance in real time? Do you often check if approval procedures are exactly matching your expectations? Have you tried to start building your SQL query but could not get it done properly? Have you experienced writing SQL query but the results are not always correct or up to your expectations? Consultant If you are an SAP Business One consultant, you have probably mastered SQL query already. However, if that is not the case, this would be a great help to extend your consulting power. It will probably become a mandatory skill in the future that any SAP Business One consultant should be able to use SQL query. Developer If you are an SAP Business One add-on developer, these skills will be good additions to your capabilities. You may find this useful even in some other development work like coding or programming. Very often you need to embed SQL query to your codes to complete your Software Development Kit (SDK) project. SAP Business One end user If you are simply a normal SAP Business One end user, you may need this more. This is because SQL query usage is best applied for the companies who have SAP Business One live data. Only you as the end users know better than anyone else what you are looking for to make Business Intelligence a daily routine job. It is very important for you to have an ability to create a query report so that you can map your requirement by query in a timely manner. SQL query and related terms Before going into the details of SQL query, I would like to briefly introduce some basic database concepts because SQL is a database language for managing data in Relational Database Management Systems (RDBMS). RDBMS RDBMS is a Database Management System that is based on the relation model. Relational here is a key word for RDBMS. You will find that data is stored in the form of Tables and the relationship among the data is also stored in the form of tables for RDBMS. Table Table is a key component within a database. One table or a group of tables represent one kind of data. For example, table OSLP within SAP Business One holds all Sales Employee Data. Tables are two-dimensional data storage place holders. You need to be familiar with their usage and their relationships with each other. If you are familiar with Microsoft Excel, the worksheet in Excel is a kind of two-dimensional table. Table is also one of the most often used concepts. Relationships between each table may be more important than tables themselves because without relation, nothing could be of any value. One important function within SAP Business One is allowing User Defined Table (UDT). All UDTs start with "@". Field A field is the lowest unit holding data within a table. A table can have many fields. It is also called a column. Field and column are interchangeable. A table is comprised of records, and all records have the same structure with specific fields. One important concept in SAP Business One is User Defined Field (UDF). All UDFs start with U_. SQL SQL is often referred to as Structured Query Language. It is pronounced as S-Q-L or as the word "Sequel". There are many different revisions and extensions of SQL. The current revision is SQL: 2008, and the first major revision is SQL-92. Most of SQL extensions are built on top of SQL-92. T-SQL Since SAP Business One is built on Microsoft SQL Server database, SQL here means Transact-SQL or T-SQL in brief. It is a Microsoft's/Sybase's extension of general meaning for SQL. Subsets of SQL There are three main subsets of the SQL language: Data Control Language (DCL) Data Definition Language (DDL) Data Manipulation Language (DML) Each set of the SQL language has a special purpose: DCL is used to control access to data in a database such as to grant or revoke specified users' rights to perform specified tasks. DDL is used to define data structures such as to create, alter, or drop tables. DML is used to retrieve and manipulate data in the table such as to insert, delete, and update data. Select, however, becomes a special statement belonging to this subset even though it is a read-only command that will not manipulate data at all. Query Query is the most common operation in SQL. It could refer to all three SQL subsets. You have to understand the risks of running any Add, Delete, or Update queries that could potentially alter system tables even if they are User Defined Fields. Only SELECT query is legitimate for SAP Business One system table. Data dictionary In order to create working SQL queries, you not only need to know how to write it, but also need to have a clear view regarding the relationship between tables and where to find the information required. As you know, SAP Business One is built on Microsoft SQL Server. Data dictionary is a great tool for creating SQL queries. Before we start, a good Data Dictionary is essential for the database. Fortunately, there is a very good reference called SAP Business One Database Tables Reference readily available through SAP Business One SDK help Centre. You can find the details in the following section. SAP Business One—Database tables reference The database tables reference file named REFDB.CHM is the one we are looking for. SDK is usually installed on the same server as the SAP Business One database server. Normally, the file path is: X:Program FilesSAPSAP Business One SDKHelp. Here, "X" means the drive where your SAP Business One SDK is installed. The help file looks like this: In this help file, we will find the same categories as the SAP Business One menu with all 11 modules. The tables related to each module are listed one by one. There are tree structures in the help file if the header tables have row tables. Each table provides a list of all the fields in the table along with their description, type, size, related tables, default value, and constraints. Naming convention of tables for SAP Business One To help you understand the previous mentioned data dictionary quickly, we will be going through the naming conventions for the table in SAP Business One. Three letter words Most tables for SAP Business One have four letters. The only exceptions are numberending tables, if the numbers are greater than nine. Those tables will have five letters. To understand table names easily, there is a three letter abbreviation in SAP Business One. Some of the commonly used abbreviations are listed as follows: ADM: Administration ATC: Attachments CPR: Contact Persons CRD: Business Partners DLN: Delivery Notes HEM: Employees INV: Sales Invoices ITM: Items ITT: Product Trees (Bill of Materials) OPR: Sales Opportunities PCH: Purchase Invoices PDN: Goods Receipt PO POR: Purchase Orders QUT: Sales Quotations RDR: Sales Orders RIN: Sales Credit Notes RPC: Purchase Credit Notes SLP: Sales Employees USR: Users WOR: Production Orders WTR: Stock Transfers  
Read more
  • 0
  • 1
  • 16555

article-image-sage-tips-and-tricks
Packt
17 May 2011
6 min read
Save for later

Sage: Tips and Tricks

Packt
17 May 2011
6 min read
  Sage Beginner's Guide Unlock the full potential of Sage for simplifying and automating mathematical computing         Read more about this book       (For more resources related to this topic, see here.) Calling the reset() function Tip: If you start getting strange results from your calculations, you may have accidentally re-defined a built-in function or constant. Try calling the reset() function and running the calculation again. Remember that reset will delete any variables or functions that you may have defined, so your calculation will have to start over from the beginning.   The value of variable i Tip: Although the variable i is often used as a loop counter, the default value of i in Sage is the square root of negative one. Remember that you can use the command restore('i') to restore i to its default value.   Calling Maxima directly Tip: Sage uses Maxima, an open-source computer algebra system, to handle many symbolic calculations. You can interact directly with Maxima from a Sage worksheet or the interactive shell by using the maxima object. For example, the following command will factor an expression using Maxima: F = maxima.factor('x^5 - y^5')   The factor function Tip: The factor function in Sage is used to factor both polynomials and integers. This behaviour is different from Mathematica, where Factor[] is used to factor polynomials and FactorInteger[] is used to factorize integers.   Logarithms in Sage Tip: The log function in Sage assumes the base of the logarithm is e. If you want to use a different base (such as 10), use the optional argument with keyword base to specify the base. For example: log(x, base=10)   Specifying colors in Sage Tip: There are several ways to specify a color in Sage. For basic colors, you can use a string containing the name of the color, such as red or blue. You can also use a tuple of three floating-point values between 0 and 1.0. The first value is the amount of red, the second is the amount of green, and the third is the amount of blue. For example, the tuple (0.5, 0.0, 0.5) represents a medium purple color.   Organizing code blocks Tip: If you find a block of code occurring more than once in your program, stop and move that block of code to a function. Duplicate blocks of code will make your programs harder to read and more prone to bugs.   The for statement Tip: Don't forget to put a colon at the end of the for statement! Remember to consistently indent every statement in the loop body.   Manipulating the data in an object Tip: As you start using objects, you may be frustrated by the lack of direct access to the data. You may find yourself tempted to avoid using the methods defined by the object, and directly manipulate the data in the object. This defeats the purpose of using objects! If the methods seem to be hindering your use of the object, you probably aren't using them right. Take another look at the documentation and examples, and re-think your approach.   Items of different types in a list Tip: The items in a list usually have the same type. Technically, it is possible to mix types in a list, but this is generally not a good idea for keeping your code organized and readable. If the need arises to use items of different types, it may be better to use a dictionary.   Ordered dictionaries Tip: Python 2.7 and versions above 3.1.3 contain a new class called OrderedDict, which works just like an ordinary dictionary except that it remembers the order in which items were inserted. This class is not available in Sage 4.6.1 because Sage is still using Python 2.6, but it should be available soon.   Runtime errors Tip: if statements are not ideal for catching runtime errors. Exceptions are a much more elegant way to deal with runtime errors.   Using exceptions correctly Tip: The whole idea of using exceptions is to make it easier to identify and handle specific runtime errors in your programs. You defeat the purpose of using exceptions if you place too many lines of code in a try block, because then it's hard to tell which statement raised the exception. It's also a bad idea to have a bare except: statement that doesn't specify the exception type that is being caught. This syntax will catch any type of exception, including SystemExit and KeyboardInterrupt exceptions, making it hard to terminate a misbehaving program. It's also considered bad practice to catch an exception without properly handling it, as this practice can mask errors.   reload a module after making changes Tip: Let's say you created a module called tank.py and used import tank to make its names available in a Sage script, or on the Sage command line. During testing, you found and fixed a bug, and saved the module file. However, Sage won't recognize that you changed anything unless you use the command reload(tank) to force it to reload the module. When working with multiple modules in a package, you may need to import a module on the command line (or in a worksheet cell) before reloading it.   SAGE_BROWSER settings Tip: Sage can be used with LaTeX to typeset complex mathematical formulae and save the results as PDF or DVI files. If you have set the SAGE_BROWSER environment variable to force Sage to use a particular web browser, you might have trouble viewing PDF or DVI files in an external viewer. If this occurs, unset SAGE_BROWSER, and change the default web browser for your operating system so that Sage will use the correct browser.   Optimizing innermost loops Tip: Many numerical algorithms consist of nested loops. The statements in the innermost loop are executed more times than statements in the outer loops, so you will get the most "bang for your buck" by focusing your optimization efforts on the innermost loop. When loops are nested, the code in the innermost loop executes most often. When a calculation needs to run fast, you will get the greatest speed increase by optimizing the code in the innermost loop.   Summary In this article we took a look at some tips and tricks for working with Sage and using Python more effectively. Further resources on this subject: Sage: 3D Data Plotting [Article] Plotting Data with Sage [Article] Creating Line Graphs in R [Article] What Can You Do with Sage Math? [Article] Python Multimedia: Enhancing Images [Article] Python Multimedia: Fun with Animations using Pyglet [Article]
Read more
  • 0
  • 0
  • 2012

article-image-foreword-microsoft-dynamics-sure-step-practitioners
Packt
17 May 2011
1 min read
Save for later

Foreword by Microsoft Dynamics Sure Step Practitioners

Packt
17 May 2011
1 min read
  Microsoft Dynamics Sure Step 2010 The smart guide to the successful delivery of Microsoft Dynamics Business Solutions         Read more about this book       (For more resources on this subject, see here.) "Investing in a business application—be it managing one's customers, tracking inventory, coordinating global resources, or just being able to get real-time visibility to cash flow—has never been so important. Gone are the days when companies invested in business applications, such as CRM and ERP, to simply streamline their supply chain or manage their sales pipeline. And gone are the days when these business applications were selected, implemented, and deployed by the IT organizations alone. Companies, and individuals within them, are relying on these business solutions to provide them a competitive advantage—an advantage that includes not only using the facts and data to generate information, but also to transform it to the knowledge that can be applied to gain a deeper understanding of the environment and provide a reliable business operating system for enabled intuition. This intuition of where to invest, how to plan, and when to execute in a well-planned, analysis-rich, and coordinated manner is what provides a competitive advantage to today's organizations. The expectations of business transformation that business solutions can provide through product or service innovation, customer delight, and operational efficiency are making it even more critical to "get it right" and "provide the business backbone". Sales, marketing, operations, and services are joining the finance and IT organizations to enable this collaborative change. We need to ask ourselves what we can do to not only provide this competitive advantage to our customers, but also to provide a solution to our customers, for them to be able to manage their own customers and businesses with better decision making. When Microsoft decided to invest in a methodology for Microsoft Dynamics solutions, there was one goal in mind—provide our customers with a Microsoft Dynamics purchase, implementation, and an ongoing experience that is unparalleled in the business solutions industry. We determined that we needed a Sure Step way to achieve this customer experience—an experience that is predicated on learning from successful implementations, and equally from the ones that went sideways due to a lack of integrated due diligence and execution approach. Sure Step provides our partners, our value-added resellers (VARs), our independent software vendors (ISVs), and Microsoft Consulting Services and field teams, with valuable guidance on people, process, and technology aspects that need to come together in a timely, predictable, and disciplined manner to help our prospects and eventual customers "get it right". Microsoft Dynamics Sure Step is the culmination and ongoing journey to make this vision and experience real. Are we indeed investing in the success of our customers, and through that the success of the Microsoft eco-systems of partners and ISVs, keeping these principles in mind? I have always believed (and known from first-hand experience!) that getting into college is only the first part of the arduous life-changing experience. Getting through college with the right skills, social temperament, informed career choices, and maybe, having fun through the experience, is often the most critical success factor for sustainable lifestyle. Investing in a business application such as Microsoft Dynamics CRM or one of the Microsoft Dynamics ERP products is not dissimilar. Making that right license purchase of software or signing up for the subscription of one of our online solutions is the key; making sure that the software indeed helps guide our customers to ensure their business success and meet their business goals is more critical. Understanding whether the solution is being analyzed, designed, developed, deployed, and eventually adopted and operated in context of the specific industry, with the right level of individual empowerment, in a relevant yet scalable manner to grow with the company, and eventually feel enamored and positively transformed by the experience, is what ensures success. Are we thinking about the customer investment and relationship we develop as transactional events, or as a strategic relationship we wish to develop and watch our customers graduate successfully from the implementation of the solution to reaping the rewards of their due diligence and implementation? For our partners, Microsoft Services, and IT organizations of our customers, understanding the fundamental principles of any methodology, applying that framework to one's business, and driving adoption of a familiar albeit new way of managing customer expectations requires de-mystifying the method behind the perceived madness! It also becomes critical for each of you to understand how you can use the power and persuasion of Sure Step to not only adapt it to the needs of your organization, but also for the specifics of the customer engagement that you are managing, and as a result help provide you a competitive advantage against the other business applications that may provide the capabilities but may not provide the "customer-focused" approach to lifecycle management. Are you willing to invest time and effort in putting more discipline and accountability into the commitment that you are making for your customers' successes? Chandru Shankar and Vincent Bellefroid have been loyal thought-leaders, advocates, and evangelists of Microsoft Dynamics Sure Step from the day we embarked on this journey of on-time, on-spec, on-budget Microsoft Dynamics engagements. Chandru Shankar has tapped into his extensive experience working in the partner channel implementing business solutions, and through the architecture of Microsoft Dynamics Sure Step, the deep insights, best-practice values, and the easy-to-comprehend guidance on why Microsoft Dynamics Sure Step recommends what to be done by whom, when, and how. He delves into the details and helps understand the value proposition of Sure Step not only from a sales or implementation perspective, but also ensuring that our customers are getting the most out of their investment now, and forever. The "brain behind the brawn" makes it an enjoyable journey (yes, for a methodology read!) through self discovery and relevant research that will hit close to home for many of you. Vincent Bellefroid has extensive experience dealing with the accolades and brickbats associated with going fearlessly where only the best and bravest readiness, adoption, and training experts can venture. He demystifies how you can embark on a journey of Sure Step adoption, and eventual excellence, within your organizations, by applying some time-tested techniques including Project and Change Management, real-life sales and deployment scenarios, and a roadmap of your success through structured roadmaps. It is hard for me think of a more qualified team to land the message, value, and approach of Microsoft Dynamics Sure Step for our business solutions-focused, business-savvy audiences. Business-ready organizations are looking to unleash the power of their Microsoft Dynamics investments as they look to drive better decisions, based on operationally efficient business solutions. These organizations have managed their businesses to date. Can they now measure and improve? Do they have the solutions, people, and processes adopted, deployed, and executed in a manner that helps them drive the shift towards integrated end-to-end business management? This book will provide the understanding and approach you need to measure your success through the success of your customers and their business solutions." Aditya Mohan - Director, Product Management, Microsoft Dynamics Sure Step   "One of the most important avenues to a partner's business success—both short and long term—is their ability to manage customer expectations and deliver high quality solutions on time, on budget, and on spec. Sure Step encompasses a number of tools and guidance that enable partners to do just that—helping them drive profitable projects along with customer satisfaction and loyalty at the same time. Partners with a proven methodology have a distinct competitive advantage, by offering customers peace-of-mind. We have been observing an increasing number of prospects asking for Sure Step-capable partners, so we absolutely recommend that existing as well as prospective Microsoft Dynamics partners adopt Sure Step. As an added benefit, partners will, instead of spending valuable resources developing and maintaining their own methodology, take full advantage of Microsoft's ongoing investments to make Sure Step even more comprehensive and robust. Partners who want to add their own flavor to Sure Step have the opportunity to do exactly that, by treating Sure Step as a methodology platform and developing "the last mile" themselves, much like ISVs build differentiating solutions on top of our ERP and CRM applications. No matter how a partner plans to leverage Sure Step, this book should help not only explain what Sure Step is about, but also how to get it implemented and adopted within the partner's organization." Anders Spatzek - Director, Microsoft Dynamics Services & Partner Readiness   "Global organizations are typically geographically dispersed, and possess cross-functional teams with varying skill sets in different regions. Business solutions delivery for such organizations requires the ability to manage requirements and schedules, dictated by multiple forces. Also, influencers and power brokers can easily create scope creep and other issues to derail these important initiatives. A consistent methodology and taxonomy is an absolute must for dealing with the pulls and demands across these organizations, to ensure that the project stays on course. Global delivery typically necessitates the involvement of multiple delivery teams, from the customer, to Microsoft, to partner organizations. Regardless of who owns the delivery of these engagements, it is of paramount importance that all the delivery resources are performing to the "same sheet of music". This is also where it is essential to have a common and consistent framework of delivery. For our practice, Microsoft Dynamics Sure Step is the tool to ensure success not only for our global practice, but more importantly for our customers and partners. We require that our consulting organization is adept with the methodology, advocating certification on the methodology, and also selecting partners who can work well within these parameters. This book will be an additional asset to help our delivery resources understand the core principles behind the methodology." Kundan Prakash - Director Business Solutions, Microsoft Services Global Delivery   "Providing Microsoft's entrepreneurial partners and customers with industry best practices is vital for ensuring successful business growth. Microsoft Dynamics Sure Step is one of those tools that save time on implementations with the added benefit of bringing together the communication between a sales team and a consulting practice! Stocked with a multitude of templates aligned to a phased implementation process, you can find the right tools to use at each stage of a customer engagement. In delivering the best knowledge to a global group of partners, Microsoft seeks out top business partners to provide insight and create new content that aligns to Microsoft product releases and industry direction. The result is a tool that brings over 800 pages of project management based guidance along with more than 700 templates, samples, and links to Microsoft resources. As Sure Step can fit to any size of project, product line, a number of industry solutions, as well as both pre- and post-implementation activities, a new Dynamics team will benefit from guidance that will get them started down the right path to adopting Sure Step and applying it to their customer's lifecycles. This book is sure to find its way to the front of many consultants' bookshelves as the go-to reference for optimizing their use of Microsoft Dynamics Sure Step." Lori Thalmann Pytlik - Sure Step R&D Manager   "Successful ERP and CRM implementations are dependent as much on the product itself, as they are on the people and processes used to implement them. Accordingly, ERP and CRM sales processes are successful when, besides proving ease-of-use and showing relevant product feature sets, they help build confidence in the minds of the customers that a well-defined path exists to get their vision and objectives materialized. Simply put, Microsoft Dynamics Sure Step is the tool that provides the confidence in the pre-sales cycle and assurance during the delivery, which makes a difference. For our Microsoft Dynamics practice in Microsoft Consulting Services (MCS), we require all our consultants and project managers to be fully proficient and certified in Microsoft Dynamics Sure Step methodology. This helps us in maintaining the high rate of customer satisfaction that we have in this business, as well as providing for an agile and responsive workforce that speaks the same language regardless of the project they are on, or at what point in the lifecycle of a project they were introduced. This book does a great job in not only detailing out what Sure Step is, but how to best use it in various pre-sales and delivery situations to provide the confidence, consistency, and predictability in execution, so that it becomes one of the core differentiators." Muhammad Alam - Dynamics US CTO, Microsoft Consulting Services Further resources on this subject: Installing Microsoft Dynamics NAV [Article] Planning: Microsoft Dynamics GP System [Article] Microsoft Dynamics GP: Data Management [Article] Securing Dynamics NAV Applications [Article] Installing the Dynamics AX Base Server Components for Microsoft [Article] Fine-tuning the SQL Server database for Dynamics NAV [Article]
Read more
  • 0
  • 0
  • 1397
article-image-sop-module-setup-microsoft-dynamics-gp
Packt
17 May 2011
14 min read
Save for later

SOP Module Setup in Microsoft Dynamics GP

Packt
17 May 2011
14 min read
All module settings are company specific. If you have multiple companies in Dynamics GP, you will need to set up each module in each company separately. This is often advantageous, as different companies may require different settings for various features. If you would like to copy setup from one company to another, Microsoft Dynamics GP KnowledgeBase article 872709?9? 9? 9? 9? 9? describes how to do this: https://mbs.microsoft.com/knowledgebase/KBDisplay.aspx?scid=kb;en-us;872709 (CustomerSource or PartnerSource login required). The Sales Order Processing module, also commonly referred to as SOP, bridges the gap between the Inventory and Receivables modules in Dynamics GP. In SOP, you can enter quotes, orders, back orders, invoices, and returns, with detailed inventory and non-inventory items. SOP also integrates to the Purchase Order Processing module with the ability to automatically create purchase orders for sales orders that you do not have stock to fill. Setup for Sales Order Processing consists of the following steps: Sales Order Processing Setup Sales Document Setup User-Defined Fields SOP Document Numbers Sales Order Processing Setup Options E-mail Settings Customer Items Sales Order Processing Setup To begin setting up SOP, navigate to Microsoft Dynamics GP | Tools | Setup | Sales | Sales Order Processing. The following is a list of the fields on the Sales Order Processing Setup window: Display Item Unit Cost: Unmarking this will show the unit cost of items entered on sales order transactions as zero. Some companies prefer to hide item costs from users; however, this option hides them only on the Sales Transaction Entry window, not anywhere else in the system. So, unless a user has extremely limited access in Dynamics GP, this is not as useful as it sounds. Track Voided Transactions in History: It is recommended to leave this option marked, as there may often be a reason to look at voided sales transactions. Calculate Kit Price based on Component Cost: This option applies to pricing methods based on cost, which are not too common. Selecting this option will cause the cost of the kit (and thus the price) to be recalculated based on the cost of each component in the kit. Display Quantity Distribution Warning: Selecting this enables a warning during transaction entry that helps users avoid mistakes when entering quantities for transactions. It is recommended to leave this checked. Search for New Rates During Transfer Process: This setting only applies to Multicurrency transactions. If it is checked, then during the transfer of sales documents (for example from quote to order), Dynamics GP will look for an updated exchange rate. If this setting is not selected, the system will still verify that the exchange rate is valid, but will not update exchange rates unless they are expired. Track Master Numbers and Next Master Number: Dynamics GP offers the ability to track related transactions with a Master Number. For example, a quote, a resulting order, and two partial invoices may all have their own individual numbers but share one master number, thus allowing for easy lookups of all related transactions. It is recommended to leave this option selected, even if you do not foresee a need to use master numbers. The Next Master Number can be anything you would like, although there is typically no reason to change it from the default value of 1. Prices Not Required in Price List: This option works together with the Inventory module and, if selected, allows users to enter items without a price level set up. This may sometimes be needed, but it is better to leave this unchecked and create price lists for all items to keep setup consistent. If this option is selected and no Password is supplied, any user can enter an item without a price level on a transaction. With a Password selected, a user will be prompted to enter the password before they can continue. Convert Functional Price: This option is only available if Prices Not Required in Price List is selected. With this checked, if a price cannot be found for the item in the currency that is being used on the transaction, the functional currency price will be converted as needed, using the current exchange rate. Data Entry Defaults: These are defaults to help speed up data entry: Quantity Shortage: Choose what users will see as the default option when they enter a quantity that is greater than what is in stock. Document Date: When entering a new SOP transaction, the Document Date will default to either the User Date (this is at the top of every window next to the User ID and Company Name) or the date of the previously saved transaction. For companies that typically enter all invoices with the same date (for example, the end of the previous month), it is best to default this to the Previous Doc. Date. For companies that want to have the current date defaulted for new transactions, choose User Date. Price Warning: You can decide whether to warn users if the price being used on a transaction they are entering is a default price for an item because a price has not been set up for the customer's price level. This may be useful if there should be a price set up on the item price list for each customer price level and can help avoid mistakes. If you choose to give a warning, using the Message option is recommended, as it will give users an indication of what the problem is; the Beep option may not be enough to catch a user's attention when you consider the typical noise level in an office and the number of beeps various applications generate. Requested Ship Date: When SOP orders are entered into Dynamics GP, a Requested Ship Date automatically populates to help determine when orders should be shipped and when purchase orders may need to be placed. A user can change the requested ship date on each line item for an order; however, if there is a typical default you can use this setting to help speed up data entry. Choices are either Document Date (order date) or number of Days After Doc. Date. If the latter is chosen, a box will appear next to this option where you can fill in the number of days (up to 999). Document Defaults: Similar to a customer with multiple Address IDs, each transaction type in SOP can have multiple document types set up to follow different rules. During transaction entry, users select which transaction type and document type to use for the proper set of rules to be followed. This section allows you to optionally set up a default for each transaction type, as well as the Site ID and Checkbook ID, to help speed up data entry. If you decide to set these up, you will need to come back to this section after you have created the various document types for each transaction type. If there is a transaction type you will not be using, or that you want to make sure users have to proactively select during transaction entry, you can leave it blank. Posting Accounts From: If Item is chosen, the system will first look at the item's accounts, then at the Inventory series of the company posting accounts to determine what GL accounts to use for SOP transactions. If Customer is chosen, the system will first look at the customer's accounts, then at the Sales series of the company posting accounts to determine what GL accounts to use for SOP transactions. Maintain History: It is recommended to keep all history and leave all of these selections checked. Decimal Places for Non-Inventoried Items: If non-inventory items are entered on SOP transactions, these settings will determine how many decimal places to use for Quantities and Currency. If Multicurrency is enabled, use the expansion button (blue arrow) next to the Currency field to enter these for each currency. The following screenshot shows a typical Sales Order Processing Setup window: Sales Document Setup You can set up as many document types as you need for each Sales Order Processing transaction type. One reason to set up different document types is to set up different transaction rules. Another reason is to use different numbering schemes or be able to segregate transactions for reporting purposes. Dynamics GP has two types of transactions that are basically the same—a fulfillment order and an invoice. In most places you will see these listed together as Fulfillment Order/Invoice. When using Workflow with the SOP module, a fulfillment order becomes a separate transaction type that, once completed, turns into an invoice automatically. To start setting up document types, click the Sales Document Setup button at the bottom of the Sales Order Processing Setup window. You will see a list of the available transaction types: The sections below will go over the setup for each transaction type. Quote Quotes are typically the start of the sales process and can be entered for customers or prospects. Prospects can be created "on the fly", as they are needed in Dynamics GP, and then transferred to customers if they accept a quote and place an order. The following list explains the fields on the Sales Quote Setup window: Quote ID: An ID for this quote document type—up to 15 characters. This ID is what users will need to type or select on a sales transaction when using this quote document type. Quote ID Next Number: If you are setting up multiple Quote IDs and would like for each to have its own numbering scheme, you can enter the next quote number here. Otherwise, if all quotes share one numbering scheme that can be entered during SOP Document Numbers setup, and you can leave this blank. Days to Expire: The default number of days a quote is valid for. After expiration, the user will not be able to transfer quotes to orders. Users can change this as needed on individual quotes. Comment ID: This is the default Comment ID for a quote. For example, if all quotes are set to expire in 30 days, you could create a comment that says Prices are guaranteed for 30 days from quote date and enter the corresponding Comment ID here. The comment would automatically populate on every quote created with this Quote ID. Format: Dynamics GP has four report formats available for each SOP transaction type: Blank Paper, Short Form, Long Form, and Other Form. If you need to set up multiple Quote IDs that show different information when printed, each Quote ID can be defaulted to use a different report format. Transfer Quote to Order: If this quote can be transferred to an order, check the box and enter an Order ID. Transfer Quote to Fulfillment Order/Invoice: If this quote can be transferred to a fulfillment order or invoice, check the box and enter a Fulfillment Order/Invoice ID. Default Quantities: This determines whether the item quantities for the quote default to Quantity to Invoice or Quantity to Order. This setting will depend on whether you plan to typically transfer a quote to an order or an invoice. Use Prospects: Leave this checked if you want to allow prospects to be used on quotes, otherwise only customers will be allowed. Allow Repeating Documents: A quote can be set up to repeat. This is more typical for orders, but may be needed at times for quotes. This setting determines whether this Quote ID will be allowed to repeat. Options and Password scrolling list: each of the Options listed has an optional Password, saved in clear text. Delete Documents: With this unchecked, once saved, a quote cannot be deleted. Edit Printed Documents: With this unchecked, once a quote is printed, it cannot be changed. Override Document Numbers: If users can change the quote numbers when they are creating them, check this option (once created a quote number cannot be changed). Void Documents: Select this if users are allowed to void quotes. If so, make sure that you have selected Track Voided Transactions in History on the Sales Order Processing Setup window. Order In Dynamics GP, a sales transaction can start out as an order, or quotes can be transferred to orders. Depending on setup, orders can allocate inventory items, thus making them unavailable for other orders or invoices. The following is a list of the fields on the Sales Order Setup window: Order ID: An ID for the order document type—the maximum length allowed is 15 characters. This is what users will need to type or select when using this order document type. Order ID Next Number: If you are setting up multiple Order IDs and would like for each to have its own numbering scheme, you can enter the Next Number here. Otherwise, if all orders will share one numbering scheme, that numbering scheme can be entered during SOP Document Numbers setup. Comment ID: The default Comment ID for an order. Format: Dynamics GP has four report formats available for each SOP transaction type: Blank Paper, Short Form, Long Form, and Other Form. If you need to set up multiple Order IDs that show different information when printed, each Order ID can be defaulted to use a different report format. Allocate by: This setting determines how (or if) inventory is allocated for the Order ID. Allocated inventory is still considered On Hand stock, but it is not available for other orders or invoices. Line Item: Select this if you want to allocate inventory as each line is entered. Users will need to choose an action on each line with a quantity shortage, which could significantly slow down order entry if most of the orders being entered do not have inventory in stock. Document/Batch: Inventory is not allocated as orders are entered and a separate allocation process is run either for each order or batch of orders. This gives less visibility of inventory availability during order entry; however, this can greatly speed it up because each line item is not checked and dealt with individually. None: Orders are not allocated at all and only after an order is transferred to an invoice or fulfillment order is inventory allocated. Transfer Order to Back Order: If this order type can be transferred to a back order, check this selection and enter a Back Order ID. Many companies do not use back orders, and simply use the back ordered quantity on orders to track back ordered items. Transfer Order to Fulfillment Order/Invoice: There is no checkbox here, as the basic functionality of an order is to transfer to an invoice. The only choice is what Fulfillment Order/Invoice ID to use. Options section: Allow Repeating Documents: If this Order ID can be set up to be repeated, mark this checkbox. Allocate by has to be set to Document/Batch or None to enable this option. Use Separate Fulfillment Process: If this option is checked, a separate step to fulfill orders will be needed prior to being able to transfer them to invoices. Allow all Back Ordered Items to Print on Invoice: If this is selected, all back ordered items will be transferred to an invoice with a fulfilled quantity of zero, allowing them to print on the invoice. Most companies like to show only items that are being billed on invoices, so they would leave this option unchecked. Credit Limit Hold ID: Holds can offer an additional level of control in Sales Order Processing. Override Quantity to Invoice with Quantity Fulfilled: Marking this option will set the Quantity to Invoice to be the same as Quantity Fulfilled, if Quantity Fulfilled is not zero. If this option is checked, Enable Quantity Cancelled in Sales Order Fulfillment becomes available. If Transfer Order to Back Order is selected, Enable Quantity to Back Order in Sales Order Fulfillment will also be enabled. Options and Password scrolling list: Each of these Options has an optional Password, saved in clear text. Allow Invoicing of Unfulfilled or Partially Fulfilled Orders: This option is activated only when the Use Separate Fulfillment Process option is selected. Otherwise, if Use Separate Fulfillment Process is not selected, invoicing an unfulfilled or partially fulfilled order will not be allowed, even though you can select this option. Delete Documents: With this unchecked, a saved order cannot be deleted. Edit Printed Documents: With this unchecked, once an order is printed, it cannot be changed. Override Document Numbers: If users can change the order numbers when they are creating them, check this option (once created, an order number cannot be changed). Void Documents: Select this option if users are allowed to void orders. If so, make sure that you have selected Track Voided Transactions in History in the Sales Order Processing Setup window. The following screenshot shows a typical Sales Order Setup window:
Read more
  • 0
  • 0
  • 10443

article-image-oracle-enterprise-manager-11g-r1-overview-business-service-management
Packt
16 May 2011
12 min read
Save for later

Oracle Enterprise Manager 11g R1: An Overview of Business Service Management

Packt
16 May 2011
12 min read
  Oracle Enterprise Manager Grid Control 11g R1: Business Service Management A Hands-on guide to modeling and managing business services using Oracle Enterprise Manager 11g R1. Business Service Management (BSM) is a key area in today's IT management arena. In the context of IT infrastructure management, there has been a major shift in the decision making process. The questions driving these decisions have moved from why do we need this to how can we achieve this. The answer to this question requires IT management to be viewed as a business enabler as opposed to a support function. Complexity in data centers IT infrastructure has transformed itself from being a necessary evil to that of a key business enabler, helping companies develop solutions to differentiate them from their competitors. IT infrastructure in modern day enterprises is the backbone that helps them stand straight with their head above the competition. To this effect, the data center landscape, which hosts this infrastructure, has evolved from a few servers in an obscure corner room of a building to that of thousands of servers in different buildings spread across various geographies. The technologies deployed in these data centers also have transformed from Mainframe and Unix systems, running e-mail and legacy applications to heterogeneous, distributed solutions involving database, middleware servers, Commercial off the Shelf (COTS), packaged, and custom applications. Further, these products and solutions interact among themselves to provide external facing business services and enable day-to-day internal business operations. The advent of Web 2.0 and cloud computing and niche features such as Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) have further complicated the landscape. The following image shows a functional view of a typical enterprise IT infrastructure: The infrastructure consists of both external and internal applications serving various classes of users. These users access various applications through different access points and devices. Even though actual IT infrastructures are far more intricate depending on the business domain of the enterprise, the above minimalist view clearly demonstrates the complexities involved. To this view, if we add the collaborations among the various entities, the topology becomes almost unmanageable. The following is a very simplistic illustration of the physical topology of the infrastructure that supports the earlier functional view: It can be seen how, IT impacts every aspect of the business operations—ranging from customer care to end user interactions to accounting to employee self service. Needless to say, the performance of the IT infrastructure is a key driver towards the success of the enterprise business. This complexity in the IT landscape necessitates deployment of a highly sophisticated management solution across the enterprise. Such a solution must be able to manage all aspects of the IT infrastructure, starting from physical hosts and devices to packaged applications. While the solution should definitely cater to managing disparate components individually, it must also provide visibility into the complex business processes and usage of the underlying infrastructure. The former view is required as a tool for day-to-day IT operations by system administrators and support personnel who know the physical topology very well. The latter view provides the CXO-level senior management with invaluable insight into the effectiveness of the underlying infrastructure in driving business operations. Many of the applications and business processes interact with each other and come together, to provide meaningful services to both external and internal users. Such interactions are achieved using diverse technologies and architectures such as SOA, web services, cloud computing, Web 2.0, and so on. These services must also cater to the availability and performance expectations of customers and internal users. These expectations are formally referred to as service-levels. The commitment on availability and performance of these services, commonly referred to as business services by the service provider, is defined formally using Service-Level Agreements or SLAs. Enterprise-wide management of these business services including their service levels requires technology-independent perspectives that provide the CXOs with the big picture. The above management concepts fall under the broad category of BSM. Modeling Prior to discussing the various modeling options, it is important to understand the necessity of modeling the IT infrastructure. As discussed in the previous section, a typical data center consists of numerous heterogeneous hardware and software components. The hardware components present in a data center are as varied as network routers, switches, machines ranging from servers to desktops, Mainframes, storage devices, load balancers, and so on. The software components deployed on such hardware are significantly more diverse such as operating systems, databases, application servers, middleware, and so on. In an enterprise data center, both hardware and software will be sourced from multiple vendors. To further add another layer of complexity, it is very likely that multiple versions of the same software product, from the same vendor, could be deployed across the enterprise. As an example, the data center of a large commercial bank could contain network switches and routers from Cisco, Mainframes from IBM, and industry standard servers from HP. This hardware will be utilized to run mission-critical CRM applications from Oracle running on Oracle middleware and Oracle Real Application Cluster (RAC) databases running a Solaris operating system. These applications would interact with Enterprise Resource Planning (ERP) systems from SAP. There will also be custom applications built in-house, running on Oracle WebLogic Application Server. In the previous topology, although the database used by both CRM and ERP systems could be supplied by Oracle, their versions could be different, that is, Oracle Database 10g and Oracle Database 11g. In a large enterprise, the CTO staff will comprise various teams of administrators having focused responsibilities on managing different components within the data center. For instance, network engineers will be assigned network router operations whereas DBAs will be responsible for database maintenance. In addition, there will be a set of administrators who maintain the enterprise applications such as CRM, Siebel, and so on. Such administrators are responsible for regular operational tasks of different components in the data center. The DBAs will need to perform regular tasks such as re-indexing, performing backup and recovery, managing table spaces, and so on. The application administrators will be handling configuration of middleware, deployment of applications, provisioning users, and so on. In addition to the regular tasks, these administrators will also be responsible for the stability and health of their respective areas. These operational teams will be complemented by a strategy team that will be responsible for IT budgeting and planning. These teams will be responsible for driving the efficiency of IT infrastructure and operations. As an example, the CTO strategy team might have a goal of increasing the IT hardware utilization by 10 percent for a fiscal year. Another goal may be to project the additional hardware requirements to support an upcoming business strategy. In order to achieve such goals, the team will require data such as usage, operational efficiency, capacity, and so on. The data requirements will be both current and historical. The strategy and the operations team need to work together to meet the compliance requirements. These requirements touch areas such as security, configuration, and storage. While the strategy team is responsible for setting compliance standards and goals, the administrators are entrusted with the responsibility of ensuring that these compliance levels are adhered to. To illustrate this, let us consider the security requirements on a CRM On-Demand application. In order to meet a specific customer security requirement around passwords, the administrator will have to configure the applications accordingly. It is clear from the above explanation that the different responsibilities require focused perspectives of the IT infrastructure. The focused perspectives must enable the administrators to view their components of interest. They must also include other components that are dependent on these as well as the areas on which a component is dependent on. Since the different components in a data center do not operate in isolation and interact with one another, it is imperative that the IT staff get a holistic view of the enterprise IT topology. DBA perspective: An example To simplify the previous explanation with an example, let's consider the perspective required by the DBA. The DBA will require a database-centric view, which shows all the databases in the enterprise. This perspective must allow the DBA to also figure out the host on which a specific database instance runs. It is equally important to understand the applications that use a specific database instance. These perspectives allow the administrators to view the dependencies between components. Let's consider a DBA of an Oracle database running on a Solaris operating system and servicing a travel portal. Due to security requirements, the Oracle database needs to be patched. As a prerequisite to this, the DBA needs to figure out the underlying operating system details so as to ensure that all the mandatory operating patches have been applied to the host. Moreover, the DBA needs to work with the administrators of all travel applications using this database instance to schedule a maintenance window when this patch can be applied. In the absence of the above holistic view, the DBA will not be able to project the business impact of this IT maintenance. The following image provides a perspective of a component-centric view of the database used in the travel portal and primarily caters to the database administrators. The previous image is an illustration of the database-centric view of the travel portal. This view is centered on the database and shows both the physical infrastructure used by the database and the travel portal application that depends on the database. Composite view: An example A different perspective is required by the strategy team. The strategy team will require a view that maps a specific business function to the IT infrastructure. This perspective will detail out the various components in the data centered that collaborate with each other to provide a certain business function. This view will also highlight the relationship among the different components. Continuing with the same travel portal example in the previous section, the strategy team responsible for the portal will need a view of all the components such as hosts, databases, middleware, and applications required by the travel portal. This view will enable them to identify the IT usage in providing the business functions to project the capacity requirements so as to meet the business goals. In the above scenario, this translates to the strategy team being able to project the additional hardware requirement correctly in order to meet a 20 percent surge in user traffic forecasted by the business teams. The following image provides such a holistic view of all the components used in travel portal: Such a view provides the necessary visibility to the strategy team in determining the infrastructure utilized to provide the business service. This mapping between the business functions and the underlying IT infrastructure comes in handy, not only in identifying the components providing a specific business function, but also by enabling to project the impact of a component on the business functions. Business view: An example In addition to these two perspectives, business strategy demands yet another paradigm to view the IT infrastructure. The data center provides numerous business services through its IT infrastructure. While the two views discussed in the previous sections provide insight into the components that are part of a business service, they clearly lack the ability to depict the business service itself. However, the above views are the first key steps towards representing the actual business service. It is important to visualize each of these business services as an entity by themselves. Such a business service-centric perspective will provide vital information at a service level. Such a business-centric view is a key enabler in representing the services for both the service provider as well as the service consumer. The service-level assurance will vary depending on the category of consumers. These business services might be provided for external users such as partners, sales channels, or end customers. For example, the travel portal will be used by end users to book their regular travel. It will also be utilized by airline and hotel partners. The consumers of the above business services can also be internal. For example, the sales teams in the travel portal business would like to use the portal for booking tickets for their own travel. The service consumers may also be categorized based on geographical location. For instance, the travel portal will have dedicated data centers for specific user locations such as U.S., Europe, and Asia Pacific. During U.S. holidays, the U.S. data center for the travel portal must be geared to meet additional customer traffic. Needless to say, the service provider must monitor the services as well as their respective service levels for each category of users. In the absence of a business-centric view, it will be cumbersome for the IT staff to translate the business priorities to the required IT configurations. This outlook allows the service provider to gather key data, such as the general health of the business service that is provided, as well as quantitative and qualitative descriptions of the service levels. The general health of the service is measured as availability of the business service. The quantitative measure of a service is described using usage metrics while performance metrics indicate the quality of the service. This perspective also enables the IT staff in determining if their service-level assurances with each category of consumers are met. Each of these different perspectives helps in visualizing different aspects of the same IT infrastructure. Such perspectives are therefore termed as models. The individual components within the data center are modeled as targets or manageable entities. The holistic view of the infrastructure that combines the functional interactions between various targets is defined as a system model. The perspective that facilitates the service provider in getting the business view of the infrastructure is termed as a service model.
Read more
  • 0
  • 0
  • 1421

article-image-installation-silverstripe-24
Packt
13 May 2011
11 min read
Save for later

Installation of SilverStripe 2.4

Packt
13 May 2011
11 min read
  SilverStripe 2.4 Module Extension, Themes, and Widgets: Beginner's Guide Create smashing SilverStripe applications by extending modules, creating themes, and adding widgets         Read more about this book       (For more resources on SilverStripe, see here.) Setting up the environment There are many possible scenarios and environments you might require, depending on the complexity of your project. However, we'll keep this short and simple: We'll set up a development environment, which is based on Windows (Windows XP or newer) as it is the most common operating system on desktops and laptops. We'll also set up one live or deployment environment, which is based on Linux as it is the most common operating system for web servers. We'll use Ubuntu in our example as it is freely available and widely used. If you prefer a different distribution some paths and commands will vary, but the general approach should be very similar. In case you want to use a testing or staging environment as well, we'll assume that you simply reuse the previous setup—so we don't need to configure another system. Now that we've decided on the general purpose of the systems and their operating systems, we'll need to choose between different implementations for setting up the web server and database. Specifically, whether to use prebuilt packages or select the components ourselves. To demonstrate both approaches we'll use a prebuilt package on our development machine (as we want to get up and running quickly) and handpick the components on our live site, where we want to have maximum control. To keep our development and live environments closely related, we'll use the same applications for both—disqualifying Windows-only solutions: For the web server we'll use the Apache HTTP Server (http://httpd.apache.org) as it's the most widely used, cross-platform server. Alternatives would be Microsoft's Internet Information Services (http://www.iis.net), which are only available on Windows, and Lighttpd (http://www.lighttpd.net) or Nginx (http://nginx.org), which are both fast, but not as widely used as the Apache web server, and are a little trickier to set up. For the database we'll use the popular MySQL (http://www.mysql.com). Alternatively you could use Microsoft SQL Server (https://www.microsoft.com/sqlserver/2008/en/us/default.aspx), which requires Windows; PostgreSQL (http://www.postgresql.org), SQLite (http://www.sqlite.org), or an Oracle database (http://www.oracle.com/us/products/database/index.html). However, each of these alternatives requires an additional SilverStripe module to support its specific SQL dialect, which generally receive less attention than MySQL. Unless you have a good reason for changing the database, like you're already using MS SQL for everything else, stick with MySQL. For a change the programming language PHP (http://www.php.net) doesn't require any decisions as there are no alternative implementations. For the prebuilt package we'll use XAMPP (http://www.apachefriends.org/en/xampp.html), which matches our requirements. It uses the Apache HTTP Server and MySQL and is available on Windows, Linux, Mac OS X, and Solaris. If your development machine doesn't use Windows, you should still be able to follow the installation steps with minor variations. On Windows there's also Microsoft's Web Platform Installer (http://www.microsoft.com/web/downloads/platform.aspx). It doesn't only include the web server, database and PHP, but also SilverStripe itself (http://www.microsoft.com/web/gallery/silverstripecms.aspx)—which can be downloaded on demand among many other web applications. However, as this is very different to our live site, we won't cover it. If you're looking for a, Windows-only solution this is nevertheless an interesting option as it is very easy to set up. The Windows development system Let's start off by setting up our development system, based on the freely available XAMPP package. Time for action - installing XAMPP We'll assume that the operating system is Windows XP or newer—for Linux, Mac OS X, and Solaris you should only need to get a different download file and do some minor variations of the steps described: Download the XAMPP package at http://www.apachefriends.org/en/xampp-windows.html. We're using the 7zip package as it doesn't require an installation, is compact to download and also portable: you can copy it to a USB drive and use the environment on any Windows computer. Extract the archive to a top-level folder on your internal drive (C: for example), or your portable external drive (U: for example). To do this, you'll need the free 7zip archive utility, which you can download at http://www.7-zip.org. Open up the file xampp/mysql/bin/my.ini and add the following line in the [mysqld] section: lower_case_table_names=2 This setting is important for exchanging database dumps between Windows and Linux systems. As Windows paths are case insensitive, MySQL lowercases database and table names by default (as they are internally stored as folders and files), but only on Windows. On Linux proper cases are preserved, which leads to problems when using dumps on different platforms. The previous statement forces MySQL on Windows to behave like on Linux. Inside the XAMPP folder, start the file xampp-control.exe and use it to Start Apache, MySql and Mercury. XAMPP's control panel should look like this after starting the three applications: If a service doesn't start, check that its port is not already in use—this is the main reason for problems. To do this, open the command line tool and enter netstat-ao. This will show you the ports currently in use and the process IDs (PIDs) of the processes using them. Using Window's Task-Manager you can then find out the name of the process causing the problem, and stop or reconfigure it. The following screenshot illustrates this scenario—the web server cannot be started as Skype is already using port 80: After successfully starting all three services, navigate to http://localhost in your browser. This should redirect you to XAMPP's welcome page. In case you need to send e-mails for testing purposes, you'll need to perform two additional steps to configure your SMTP server: Enable SMTP relaying of non-local mail. However, ensure that no one can access your mail server from outside or you might be abused as a spam relay (your router or firewall will protect you). In XAMPP's control panel, click on Admin... next to the Mercury label. Next go to Configuration, MercuryS SMTP Server and on the Connection control tab uncheck Do not permit SMTP relaying of non-local mail. Provide a DNS server so domain names can be looked up: Under Configuration, MercuryE SMTP Client fill in the field Name server with your provider's DNS server. That's it for our general purpose development machine. In case you want to run automatic tests or generate translation files, you'll also need to install PHPUnit through PEAR: While XAMPP includes PEAR and PHPUnit, the bundled versions are hopelessly outdated. Furthermore the update process doesn't work reliably, so we'll better start anew. First remove xampp/php/PEAR/, xampp/php/pear.bat, xampp/php/pear.ini, xampp/php/peardev.bat and xampp/php/pear-update.bat. Next enable PHP's cURL extension: Open xampp/php/php.ini, find the line ;extension=php_curl.dll and remove the leading semicolon. Then download http://pear.php.net/go-pear.phar into xampp/php/. Next install PEAR on the command line (start it as an admin user). Note that you must be in the folder xampp/php/ for the following commands to work: php go-pear.phar Now we can use PEAR to update its channels and upgrade all packages: pear update-channelspear upgrade --alldeps Finally you can install PHPUnit and all of its dependencies: pear channel-discover pear.phpunit.depear channel-discover components.ez.nopear channel-discover pear.symfony-project.compear install phpunit/PHPUnit That's it, you've successfully installed PHPUnit! The Linux live system Next we'll set up our live system. Thanks to package managers this isn't much harder—you just shouldn't be afraid of the shell. Time for action - installing the requirements by hand In our example we're using Ubuntu, so we'll rely on its package manager Apt, abbreviation of Advanced Package Tool. Note that we won't only install the bare necessities, but also some more tools to make our system ready for production. Open the terminal and install the Apache HTTP Server together with PHP and PHP's GD library (needed for image manipulation) through the following commands. Note that all required dependencies are added automatically, though you may need to manually accept them: sudo apt-get install apache2 php5 php5-gd Next we'll install MySQL and its binding to PHP, again through the terminal. You'll be prompted for a password, which we'll need again later on. sudo apt-get install mysql-server php5-mysql Enable Apache's rewrite module, which SilverStripe requires to use pretty URLs: sudo a2enmod rewrite Edit the file /etc/apache/sites-available/default and replace the line AllowOverride None with AllowOverride All inside the <Directory /var/www/> block. This enables the rewrite module inside the /var/www/ folder. Install Alternative PHP Cache (APC), which will accelerate PHP programs—SilverStripe benefits a lot from this. While there are some alternatives, it is currently planned that APC will be included in PHP 6, which makes it sound like a future-proof decision for our installation: sudo apt-get install php-apc If you want to see APC in action, you'll need its management tool. By default it is located in the file /usr/share/doc/php-apc/apc.php.gz. Unpack and copy it to your web-root to see detailed statistics on how well it's working for you, but protect it against unauthorized access (you can set credentials inside the file). Edit the file /etc/php5/apache2/php.ini, using whatever text-editor you prefer (this can be quite a sensitive topic with programmers). Replace the line ;date.timezone = with date.timezone = US/New_York or your current location. See http://php.net/manual/en/timezones.php for all possible values. Note that removing the semicolon at the beginning is important, otherwise the line will be considered a comment. Restart the web server to apply all the settings we've just made: sudo /etc/init.d/apache2 reload Now it's time to test our installation. Go to the directory /var/www/ which is the default web-root directory: cd /var/www/ It should already contain a file index.html, which you can view if you visit http://127.0.0.1 in your browser (or whichever IP address you can access your server under). However, this is only a static HTML file. To see if PHP is also working, first set the file permissions, assuming our current user is ubuntu (which we'll use to edit files) and the web server is run as www-data (which is the default). So we'll make our user the owner of the files with full permissions, and set the group to the one of the web server with read and execute permissions only: sudo chown ubuntu:www-data -R /var/www/sudo chmod 0755 -R /var/www/ After adding new files, you'll need to rerun these two commands. Next create a file index.php in /var/www/: touch index.php Add the following code to it: <?php phpinfo();?> In your browser load the page http://127.0.0.1/index.php (again use your specific IP address). The output should look something like this: This shows that PHP is working. Also check that you can find mod_rewrite and a full section on APC in the output to be sure they are enabled. That's it, our live system is now ready for action. We haven't installed PEAR as we'll assume that testing and translating is done in the development environment, not on the live server. We've also left out how to install and configure an SMTP server. Unfortunately this is pretty complicated and beyond the scope of this article—especially since you don't want to become a spam relay. If your provider or distribution hasn't already set this up for you, take a look at a specific SMTP server how-to and documentation—Postfix (http://www.postfix.org) is widely used for example.
Read more
  • 0
  • 0
  • 2235
article-image-testing-python-using-doctest
Packt
13 May 2011
8 min read
Save for later

Testing in Python using doctest

Packt
13 May 2011
8 min read
Python Testing Cookbook Coding a test harness for doctest The doctest module supports creating objects, invoking methods, and checking results. With this recipe, we will explore this in more detail. An important aspect of doctest is that it finds individual instances of docstrings, and runs them in a local context. Variables declared in one docstring cannot be used in another docstring. The reader can benefit from the previous article on Python: Using doctest for Documentation. How to do it... Create a new file called recipe19.py to contain the code from this recipe. Write a simple shopping cart application. class ShoppingCart(object): def __init__(self): self.items = [] def add(self, item, price): self.items.append(Item(item, price)) return self def item(self, index): return self.items[index-1].item def price(self, index): return self.items[index-1].price def total(self, sales_tax): sum_price = sum([item.price for item in self.items]) return sum_price*(1.0 + sales_tax/100.0) def __len__(self): return len(self.items) class Item(object): def __init__(self, item, price): self.item = item self.price = price Insert a docstring at the top of the module, before the ShoppingCart class declaration. """ This is documentation for the this entire recipe. With it, we can demonstrate usage of the code. >>> cart = ShoppingCart().add("tuna sandwich", 15.0) >>> len(cart) 1 >>> cart.item(1) 'tuna sandwich' >>> cart.price(1) 15.0 >>> print round(cart.total(9.25), 2) 16.39 """ class ShoppingCart(object): ... Run the recipe using -m doctest and -v for verbosity. Copy all the code we just wrote from recipe19.py into a new file called recipe19b.py. Inside recipe19b.py add another docstring to item, which attempts to re-use the cart variable defined at the top of the module. def item(self, index): """ >>> cart.item(1) 'tuna sandwich' """ return self.items[index-1].item Run this variant of the recipe. Why does it fail? Wasn't cart declared in the earlier docstring? How it works... The doctest module looks for every docstring. For each docstring it finds, it creates a shallow copy of the module's global variables and then runs the code and checks results. Apart from that, every variable created is locally scoped and then cleaned up when the test is complete. This means that our second docstring that was added later cannot see the cart that was created in our first docstring. That is why the second run failed. There is no equivalent to a setUp method as we used with some of the unittest recipes. If there is no setUp option with doctest, then what value is this recipe? It highlights a key limitation of doctest that all developers must understand before using it. There's more... The doctest module provides an incredibly convenient way to add testability to our documentation. But this is not a substitute for a full-fledged testing framework, like unittest. As noted earlier, there is no equivalent to a setUp. There is also no syntax checking of the Python code embedded in the docstrings. Mixing the right level of doctests with unittest (or other testing framework we pick) is a matter of judgment. Filtering out test noise Various options help doctest ignore noise, such as whitespace, in test cases. This can be useful, because it allows us to structure the expected outcome in a better way, to ease reading for the users. We can also flag some tests that can be skipped. This can be used where we want to document known issues, but haven't yet patched the system. Both of these situations can easily be construed as noise, when we are trying to run comprehensive testing, but are focused on other parts of the system. In this recipe, we will dig in to ease the strict checking done by doctest. We will also look at how to ignore entire tests, whether it's on a temporary or permanent basis. How to do it... With the following steps, we will experiment with filtering out test results and easing certain restrictions of doctest. Create a new file called recipe20.py to contain the code from this recipe. Create a recursive function that converts base10 numbers into other bases. def convert_to_basen(value, base): import math def _convert(remaining_value, base, exp): def stringify(value): if value > 9: return chr(value + ord('a')-10) else: return str(value) if remaining_value >= 0 and exp >= 0: factor = int(math.pow(base, exp)) if factor <= remaining_value: multiple = remaining_value / factor return stringify(multiple) + _convert(remaining_value-multiple*factor, base, exp-1) else: return "0" + _convert(remaining_value, base, exp-1) else: return "" return "%s/%s" % (_convert(value, base, int(math.log(value, base))), base) Add a docstring that includes a test to exercise a range of values as well as documenting a future feature that is not yet implemented. def convert_to_basen(value, base): """Convert a base10 number to basen. >>> [convert_to_basen(i, 16) for i in range(1,16)] #doctest: +NORMALIZE_WHITESPACE ['1/16', '2/16', '3/16', '4/16', '5/16', '6/16', '7/16', '8/16', '9/16', 'a/16', 'b/16', 'c/16', 'd/16', 'e/16', 'f/16'] FUTURE: Binary may support 2's complement in the future, but not now. >>> convert_to_basen(-10, 2) #doctest: +SKIP '0110/2' """ import math Add a test runner. if __name__ == "__main__": import doctest doctest.testmod() Run the test case in verbose mode. Copy the code from recipe20.py into a new file called recipe20b.py. Edit recipe20b.py by updating the docstring to include another test exposing that our function doesn't convert 0. def convert_to_basen(value, base): """Convert a base10 number to basen. >>> [convert_to_basen(i, 16) for i in range(1,16)] #doctest: +NORMALIZE_WHITESPACE ['1/16', '2/16', '3/16', '4/16', '5/16', '6/16', '7/16', '8/16', '9/16', 'a/16', 'b/16', 'c/16', 'd/16', 'e/16', 'f/16'] FUTURE: Binary may support 2's complement in the future, but not now. >>> convert_to_basen(-10, 2) #doctest: +SKIP '0110/2' BUG: Discovered that this algorithm doesn't handle 0. Need to patch it. TODO: Renable this when patched. >>> convert_to_basen(0, 2) '0/2' """ import math Run the test case. Notice what is different about this version of the recipe; and why does it fail? Copy the code from recipe20b.py into a new file called recipe20c.py. Edit recipe20c.py and update the docstring indicating that we will skip the test for now. def convert_to_basen(value, base): """Convert a base10 number to basen. >>> [convert_to_basen(i, 16) for i in range(1,16)] #doctest: +NORMALIZE_WHITESPACE ['1/16', '2/16', '3/16', '4/16', '5/16', '6/16', '7/16', '8/16', '9/16', 'a/16', 'b/16', 'c/16', 'd/16', 'e/16', 'f/16'] FUTURE: Binary may support 2's complement in the future, but not now. >>> convert_to_basen(-10, 2) #doctest: +SKIP '0110/2' BUG: Discovered that this algorithm doesn't handle 0. Need to patch it. TODO: Renable this when patched. >>> convert_to_basen(0, 2) #doctest: +SKIP '0/2' """ import math Run the test case. How it works... In this recipe, we revisit the function for converting from base-10 to any base numbers. The first test shows it being run over a range. Normally, Python would fit this array of results on one line. To make it more readable, we spread the output across two lines. We also put some arbitrary spaces between the values to make the columns line up better. This is something that doctest definitely would not support, due to its strict pattern matching nature. By using #doctest: +NORMALIZE_WHITESPACE, we are able to ask doctest to ease this restriction. There are still constraints. For example, the first value in the expected array cannot have any whitespace in front of it. But wrapping the array to the next line no longer breaks the test. We also have a test case that is really meant as documentation only. It indicates a future requirement that shows how our function would handle negative binary values. By adding #doctest: +SKIP, we are able to command doctest to skip this particular instance. Finally, we see the scenario where we discover that our code doesn't handle 0. As the algorithm gets the highest exponent by taking a logarithm, there is a math problem. We capture this edge case with a test. We then confirm that the code fails in classic test driven design (TDD) fashion. The final step would be to fix the code to handle this edge case. But we decide, in a somewhat contrived fashion, that we don't have enough time in the current sprint to fix the code. To avoid breaking our continuous integration (CI) server, we mark the test with a TO-DO statement and add #doctest: +SKIP. There's more... Both the situations that we have marked up with #doctest: +SKIP, are cases where eventually we will want to remove the SKIP tag and have them run. There may be other situations where we will never remove SKIP. Demonstrations of code that have big fluctuations may not be readily testable without making them unreadable. For example, functions that return dictionaries are harder to test, because the order of results varies. We can bend it to pass a test, but we may lose the value of documentation to make it presentable to the reader.  
Read more
  • 0
  • 0
  • 6651

article-image-integrating-yahoo-user-interface-library-yui-moodle
Packt
13 May 2011
6 min read
Save for later

Integrating Yahoo! User Interface Library (YUI) with Moodle

Packt
13 May 2011
6 min read
  Moodle JavaScript Cookbook Over 50 recipes for making your Moodle system more dynamic and responsive with JavaScript In this article, we will cover: Initializing the YUI 3 library Loading YUI 3 modules Loading YUI 2 modules from YUI 3 Attaching basic event handlers Attaching advanced DOM event handlers Implementing Event Delegation Debugging with the YUI console Introduction There are a lot of common tasks that need to be performed when writing JavaScript. A large proportion of this simply involves dealing with differences between web browsers. The need for a way to hide or abstract the specifics of each browser into a standard interface gave rise to sets of tools known as JavaScript libraries. One of the leading libraries in use on the web today is the Yahoo! User Interface Library (YUI). Moodle includes a copy of the YUI as its preferred JavaScript library. YUI provides developers with access to a wide range of tools for enhancing their web applications: The YUI Library is a set of utilities and controls, written with JavaScript and CSS, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX. YUI is available under a BSD license and is free for all uses. YUI is proven, scalable, fast, and robust. Built by frontend engineers at Yahoo! and contributors from around the world, it's an industrial-strength JavaScript library for professionals who love JavaScript. Yahoo! Developer Network http://developer.yahoo.com/yui/ In this article, we will learn the basics of working with YUI. We will learn how to initialize the YUI and make it ready for use within our code and load additional modules from versions 2 and 3 of the YUI. We will also learn how to manage the execution of code by attaching events to our controls, and finally how to debug our code with YUI logging tools. Initializing the YUI 3 library In this recipe, we will learn how to initialize the YUI 3 environment within Moodle, which will get us ready to start using YUI 3 features. Moodle takes care of most of the initial setup, namely loading the required CSS and JavaScript files, so all we need to be concerned with is activating the YUI environment. This example will show how to execute JavaScript code from within the YUI environment. We will set up a small YUI script which will simply display a message including the version number of the active YUI environment in a JavaScript alert box. This provides a simple view of what is required to get YUI up and running that we will build on further in the subsequent recipes. Getting ready We begin by setting up a new PHP file yui_init.php in the cook directory with the following content: <?php require_once(dirname(__FILE__) . '/../config.php'); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->set_url('/cook/yui_init.php'); $PAGE->requires->js('/cook/yui_init.js'); echo $OUTPUT->header(); echo $OUTPUT->footer(); ?> Notice that the preceding code references a JavaScript file yui_init.js, which has the following content: YUI().use ( function(Y) { alert('Hello from YUI ' + Y.version); } ); How to do it... We have created a PHP file that sets up a Moodle programming environment and includes a JavaScript file, in a way now familiar to us from previous recipes. What is new here is the content of the JavaScript file, which is where we will make ready the YUI 3 environment. Moodle has already included all the JavaScript files required for YUI (this happened when we output the value returned from $OUTPUT->header();). This means we now have a global object named YUI available within our JavaScript code. We create a new instance of the YUI object with the statement YUI() and then immediately call the use method. The only parameter we will pass to the use method is an anonymous function. This is just like a regular JavaScript function, except that it has no name specified; hence it is "anonymous". A name is not required, as it is not referred to again, but it is simply passed directly to the use method. This function itself accepts a single input parameter Y, which will be a reference to the new instance of the YUI object. (Note that the use method is also used to load additional YUI modules; this is the subject of the next recipe.) The anonymous function just created is the most important part of the code to take note of as this is where we will be putting our entire code that will be making use of the YUI features. In this example, you can see that we are just creating a JavaScript alert with a short message including the value of Y.version, which is simply a string containing the version number of YUI that has been loaded as seen in the following screenshot: Here, we can see that our code has successfully initialized the YUI 3.2.0 environment and is ready for us to start using the features available within the YUI and its additional modules. How it works... We have created a new instance of the global object YUI, and called the use method, passing in an anonymous function that contains the code we wish to run. When the new instance of the YUI object is fully loaded, it makes a call to our anonymous function, and our code is executed. In this example, our code displays a short message containing the version number of the YUI instance we created, confirming that we have a fully functional YUI 3 environment as a basis to implement further YUI features. Loading additional YUI modules YUI has a whole host of additional modules providing a very wide range of functionalities. Some examples of commonly used functionalities provided by additional modules include: Animation Drag and drop Manipulating DOM elements Handling DOM events (that is an input button's "click" event) Handling data (JSON/XML) For a current list of all the modules available, please refer to the Yahoo! Developer Network website for YUI 3 at the URL: http://developer.yahoo.com/yui/3/ How to do it... The loading of additional modules is achieved via the use method of the YUI object. In the previous recipe we learned how to run code via the use method with the following syntax: YUI().use ( function(Y) { /* <code to execute> */ } ); Note that the use method takes an arbitrarily long number of arguments (one or more) and only the last argument must be the anonymous function described in the previous recipe. The preceding arguments are a list of one or more modules you wish to load. So for example, to load the Animation module (anim) and the DOM Event Utility module (event), we would use the following syntax in place of the preceding one: YUI().use ( "anim", "event", function(Y) { /* <code to execute> */ } ); Now all of the features of these two additional modules (anim and event) will be available within the anonymous function that contains the code we want to execute. This technique will be used to load the modules we require in the examples contained in the subsequent recipes.
Read more
  • 0
  • 0
  • 2262
Modal Close icon
Modal Close icon