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
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Web Development

1797 Articles
article-image-moodle-20-faqs
Packt
14 Oct 2010
8 min read
Save for later

Moodle 2.0 FAQs

Packt
14 Oct 2010
8 min read
Moodle 2.0 First Look Discover what's new in Moodle 2.0, how the new features work, and how it will impact you Get an insight into the new features of Moodle 2.0 Discover the benefits of brand new additions such as Comments and Conditional Activities Master the changes in administration with Moodle 2.0 The first and only book that covers all of the fantastic new features of Moodle 2.0         Read more about this book       (For more resources on Moodle, see here.)   Question: What are the basic requirements for Moodle 2.0 to function? Answer: It's important that either you (if you're doing this yourself) or your Moodle admin or webhost are aware of the requirements for Moodle 2.0. It needs: PHP must be 5.2.8 or later One of the following databases: MySQL 5.0.25 or later (InnoDB storage engine highly recommended) PostgreSQL 8.3 or later Oracle 10.2 or later MS SQL 2005 or later One of the following browsers: Firefox 3 or later Safari 3 or later Google Chrome 4 or later Opera 9 or later MS Internet Explorer 7 or later   Question: How can I upgrade to Moodle 2.0? Answer: If you already have an installation of Moodle, you will find instructions for upgrading in the docs on the main Moodle site here http://docs.moodle.org/en/Upgrading_to_Moodle_2.0. If you are upgrading from an earlier version of Moodle (such as 1.8) then you should upgrade to Moodle 1.9 first before going to 2.0. You must update incrementally; shortcuts – for example. updating from 1.7 directly to 2.0 -- are simply not possible. Read the docs carefully if you are planning on upgrading from very early versions such as 1.5 or 1.6.   Question: What are the potential problems with upgrading? Answer: There are a few challenges that one may come across while upgrading from Moodle 1.9 to 2.0 which are listed below: Themes: The way themes work has changed completely. While this allows for more flexible coding and templating, it does mean that if you had a customized theme it will not transfer over to Moodle 2 without some redesigning beforehand. Third party add-ons and custom code: The same applies to third party add-ons and custom code: it is highly unlikely they will work without significant alterations. Backup and Restore: Making courses from 1.9 or earlier restore into Moodle 2. 0 has proved very problematic and is still not entirely achievable. Although this is a priority for the Moodle developers, there is at the time of writing only a workaround involving restoring your course to a 1.9 site and then upgrading it to 2.0.   Question: How can teachers and students manage their learning? Answer: The two new features of Moodle 2.0 help teacher and students manage their learning: Conditional activities: A way to organize a course so that tasks are only available dependent on certain grades being obtained or criteria being met beforehand. Completion tracking: A way for students to have checkboxes next to their tasks that are either automatically marked as complete or which students themselves can manually mark if they feel they've finished the exercise – or alternatively a way for whole courses to be checked off as finished.   Question: What are the changes in the Themes structure for Moodle 2.0? Answer: The themes structure has been completely rewritten for Moodle 2.0. Themes that worked in 1.9 needed to be updated to work in 2.0. There is a wide variety of attractive new themes available. If you need to update your own theme or would like information on Moodle 2.0 theming, you will find the documentation at http://docs.moodle.org/en/Development:Themes_2.0 helpful. New to Moodle 2.0 are the following: Designer Mode: Turn this on so you're not served cached versions of themes, if you are designing themes or developing code. Allow theme changes in the URL: Enabling this will let users alter their theme via their Moodle URL using the syntax Allow blocks to use the dock: Enabling this will allow users to dock blocks if the theme supports it.   Question: Can we customize the MyMoodle page in Moodle 2.0? Answer: Yes, we can customize the default MyMoodle page. It's worth noting that on the MyMoodle page we can add blocks to the middle as well as the sides. With editing turned on, we're given the option to move a block to a central location.   Question: Can we Comment on the Moodle blog? Answer: Commenting on the Moodle blog is a bit of a workaround really; the Moodle blog doesn't really have a built-in commenting facility like, say WordPress. Rather, Moodle is making use of the new Comments feature which ordinarily appears as a block anywhere you want to add it.   Question: What are the improvements in the Blog option in Moodle 2.0 as compared to the previous version? Answer: There has always been a blogging option in a standard Moodle install. However, some users have found it unsatisfactory because of the following reasons: The blog is attached to the user profile so you can only have one blog There is no way to attach a blog or blog entry to a particular course There is no way for other people to comment on your blog For this reason, alternative blog systems (such as the contributed OU blog module) have become popular as they give users a wider range of options. The standard blog in Moodle 2.0 has changed, and now: A blog entry can optionally be associated with a course It is possible to comment on a blog entry Blog entries from outside of Moodle can be copied in It is now possible to search blog entries   Question: How to enable/disable the docking facility in Moodle 2.0? Answer: The docking facility can be managed in Moodle 2.0 as follows: The "docking" facility may be enabled or disabled for themes in Site Administration | Appearance | Themes | Theme settings. If we click the icon shown in the following screenshot, we also have the option of "docking" this over to the far left as a narrow tab.   Question: Has the HTML editor been replaced by some other editing tool? What is its advantage? Answer: In Moodle 2.0, the HTML editor has been replaced with a version known as Tiny MCE, a very popular Open Source editor you might have encountered in content management systems or blogging software such as WordPress. Along with Internet Explorer and Firefox, it will work with web browsers such as Safari, Chrome, and Opera, unlike Moodle's previous HTML editor. The following screenshot shows the new editor (on the bottom) with the original editor (on the top): There are many more options available to us when adding descriptions of our materials or summaries of our courses. However, one of the most powerful new features is the ability to add and embed media directly from within this new HTML editor.   Question: What have been the improvements related to Moodle Quiz? Answer: The following are the improvements to Moodle Quiz: The set up page has been simplified Creating questions has been simplified It's possible to flag questions for later referral Questions can be accessed with one click in the post-quiz review and correct/ incorrect questions are color-coded in an easy-to access navigation block   Question: What are Cohorts? Answer: Cohort is Moodle 2.0's take on the long wished for site-wide groups. When we click on the link we're taken to the following screen where we click on Add to enter details of the cohort we want to create:   Question: Has there been any modification in the Filters menu as compared to the previous versions On/Off options? Answer: The Manage Filters in Moodle 2.0 equates to the Filters menu in Moodle 1.9. The Manage Filters screen looks like the following screenshot (note—the screenshot only displays the first three filters): Previously, filters were either On or Off. Now we have three choices: Disabled: Nobody, in any course, can enable a filter. On: A filter is enabled by default and teachers can disable if they wish to. Off but available: A filter is off but teachers can enable it in their own courses.   Question: What are the changes in Site Administration? Answer: Perhaps the simplest way to explore this is to look at how this menu has altered since Moodle 1.9: Notifications/Registrations: A small but important change in Moodle 1.9, the Notifications screen contained a button you could click to register your site with http://moodle.org/. The page this took you to now has its own billing in Moodle 2.0, as the Registration link. Community hubs: The main Moodle community hub is known as MOOCH and you register with it here. You can also register your site with other community hubs. If you register with hubs, then teachers can add a Community block in their courses where users can search for a suitable course to enroll in or download. Summary In this article we took a look at the queries regarding what Moodle 2.0 has to offer with the exciting new modules and enhanced features, and the major overhauls in the file uploading and navigation system. Further resources on this subject: Moodle 1.9 Math [Book] Moodle Administration [Book] Moodle 1.9 for Teaching Special Education Children (5-10): Beginner's Guide [Book] Moodle 2.0: What's New in Add a Resource [Article] What's New in Moodle 2.0 [Article]
Read more
  • 0
  • 0
  • 1438

article-image-administrating-mysql-server-phpmyadmin
Packt
13 Oct 2010
8 min read
Save for later

Administrating the MySQL Server with phpMyAdmin

Packt
13 Oct 2010
8 min read
  Mastering phpMyAdmin 3.3.x for Effective MySQL Management A complete guide to get started with phpMyAdmin 3.3 and master its features The best introduction to phpMyAdmin available Written by the project leader of phpMyAdmin, and improved over several editions A step-by-step tutorial for manipulating data with phpMyAdmin Learn to do things with your MySQL database and phpMyAdmin that you didn't know were possible! Managing users and their privileges The Privileges subpage (visible only if we are logged in as a privileged user) contains dialogs to manage MySQL user accounts. It also contains dialogs to manage privileges on the global, database, and table levels. This subpage is hierarchical. For example, when editing a user's privileges, we can see the global privileges as well as the database-specific privileges. We can then go deeper to see the table-specific privileges for this database-user combination. The user overview The first page displayed when we enter the Privileges subpage is called User verview. This shows all user accounts and a summary of their global privileges, as shown in the next screenshot: From this page, we can: Edit a user's privileges, via the Edit link for this user Use the checkboxes to remove users, via the Remove selected users dialog Access the page when the Add a new User dialog is available The displayed users' list has columns with the following characteristics: Privileges reload At the bottom of User Overview, the following message is displayed: Note: phpMyAdmin gets the users' privileges directly from MySQL's privilege tables. The content of these tables may differ from the privileges the server uses, if they have been changed manually. In this case, you should reload the privileges before you continue. Here, the text reload the privileges is clickable. The effective privileges (the ones against which the server bases its access decisions) are the privileges that are located in the server's memory. Privilege modifications that are made from the User overview page are made both in memory and on disk, in the mysql database. Modifications made directly to the mysql database do not have immediate effect. The reload the privileges operation reads the privileges from the database and makes them effective in memory. Adding a user The Add a new User link opens a dialog for user account creation. First, we see the panel where we'll describe the account itself: The second part of the Add a new User dialog is where we'll specify the user's global privileges, which apply to the server as a whole. Entering the username The User name menu offers two choices. Firstly, we can choose Use text field and enter a username in the box, or we can choose Any user to create an anonymous user (the blank user). Let's choose Use text field and enter bill. Assigning a host value By default, this menu is set to Any host, with % as the host value. The Local choice means "localhost". The Use host table choice (which creates a blank value in the host field) means to look in the mysql.hosts table for database-specific privileges. Choosing Use text field allows us to enter the exact host value we want. Let's choose Local. Setting passwords Even though it's possible to create a user without a password (by selecting the No password option), it's best to have a password. We have to enter it twice (as we cannot see what is entered) to confirm the intended password. A secure password should have more than eight characters, and should contain a mixture of uppercase and lowercase characters, digits, and special characters. Therefore, it's recommended to have phpMyAdmin generate a password—this is possible in JavaScript-enabled browsers. In the Generate Password dialog, clicking on Generate enters a random password (in clear text) on the screen and fills the Password and Re-type input fields with the generated password. At this point, we should note the password so that we can pass it on to the user. Understanding rights for database creation A frequent convention is to assign a user the rights to a database having the same name as this user. To accomplish this, the Database for user section offers the checkbox Create database with same name and grant all privileges. Selecting this checkbox automates the process by creating both the database (if it does not already exist) and the corresponding rights. Please note that, with this method, each user would be limited to one database (user bill, database bill). Another possibility is to allow users to create databases that have the same prefix as their usernames. Therefore, the other choice, Grant all privileges on wildcard name (username_%), performs this function by assigning a wildcard privilege. With this in place, user bill could create the databases bill_test, bill_2, bill_payroll, and so on; phpMyAdmin does not pre-create the databases in this case. Assigning global privileges Global privileges determine the user's access to all databases. Hence, these are sometimes known as "superuser privileges". A normal user should not have any of these privileges unless there is a good reason for this. Of course, if we are really creating a superuser, we will select every global privilege that he or she needs. These privileges are further divided into Data, Structure, and Administration groups. In our example, bill will not have any global privileges. Limiting the resources used We can limit the resources used by this user on this server (for example, the maximum queries per hour). Zero means no limit. We will not impose any resource limits on bill. The following screenshot shows the status of the screen just before hitting Go to create this user's definition (with the remaining fields being set to default): Editing a user profile The page used to edit a user's profile appears after a user's creation, or whenever we click on Edit for a user in the User overview page. There are four sections on this page, each with its own Go button. Hence, each section is operated independently and has a distinct purpose. Editing privileges The section for editing the user's privileges has the same look as the Add a new User dialog, and is used to view and change global privileges. Assigning database-specific privileges In this section, we define the databases to which our user has access, and his or her exact privileges on these databases. As shown in the previous screenshot, we see None because we haven't defined any privileges yet. There are two ways of defining database privileges. First, we can choose one of the existing databases from the drop-down menu: This assigns privileges only for the chosen database. We can also choose Use text field and enter a database name. We could enter a non-existent database name, so that the user can create it later (provided that we give him or her the CREATE privilege in the next panel). We can also use special characters, such as the underscore and the percent sign, for wildcards. For example, entering bill here would enable him to create a bill database, and entering bill% would enable him to create a database with any name that starts with bill. For our example, we will enter bill and then click on Go. The next screen is used to set bill's privileges on the bill database, and create table-specific privileges. To learn more about the meaning of a specific privilege, we can move the mouse over a privilege name (which is always in English), and an explanation about this privilege appears in the current language. We give SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, and DROP privileges to bill on this database. We then click on Go. After the privileges have been assigned, the interface stays at the same place, so that we can refine these privileges further. We cannot assign table-specific privileges for the moment, as the database does not yet exist. To go back to the general privileges page of bill, click on the 'bill'@'localhost' title. This brings us back to the following, familiar page, except for a change in one section: We see the existing privileges (which we can Edit or Revoke) on the bill database for user bill, and we can add privileges for bill on another database. We can also see that bill has no table-specific privileges on the bill database. Changing the password The Change password dialog is part of the Edit user page, and we can use it either to change bill's password or to remove it. Removing the password will enable bill to login without a password. The dialog offers a choice of password hashing options, and it's recommended to keep the default of MySQL 4.1+ hashing. For more details about hashing, please visit http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html
Read more
  • 0
  • 0
  • 7139

article-image-menus-toolbars-and-buttons-ext-js-32
Packt
13 Oct 2010
8 min read
Save for later

Menus, Toolbars, and Buttons in Ext JS 3.2

Packt
13 Oct 2010
8 min read
  Learning Ext JS 3.2 Build dynamic, desktop-style user interfaces for your data-driven web applications using Ext JS Learn to build consistent, attractive web interfaces with the framework components Integrate your existing data and web services with Ext JS data support Enhance your JavaScript skills by using Ext's DOM and AJAX helpers Extend Ext JS through custom components An interactive tutorial packed with loads of example code and illustrative screenshots         What's on the menu? We will begin by introducing the Menu class which will be used in all following examples. We are going to demonstrate usage of the Menu class as both a static component within a page, and as a popup. Both menus will be configured with the same options by using a technique where we define a variable called menuItems to reference an array which specifies the menu's items, and use it in both cases. The Menu class inherits from Container, so any menu options are child Components specified in the items config. It also inherits the usual Component config options such as renderTo, and the width option. The static menu will be rendered to the document body, and in order for it to be rendered as a visible, static element in the document, we configure it with floating: false. So the configuration we end up with is as follows: new Ext.menu.Menu({ renderTo: document.body, width: 150, floating: false, items: menuItems }); The popup menu needs no extra configuring aside from its items. We do need to decide when and where to display it. In this case we will add a contextmenu (right click) event listener to the document, and show the menu at the mouse event's position: var contextMenu = new Ext.menu.Menu({ items: menuItems }); Ext.getDoc().on({ contextmenu: function(eventObj) { contextMenu.showAt(eventObj.getXY()); }, stopEvent: true }); When we run this example, the static menu will be visible. When we right click on the document, the result should be the two menus shown below. Notice how only the second, popup menu has a shadow to indicate that it floats above the document. The menu's items The menuItems variable references an array which should be familiar by now. Just like the items config of a FormPanel, it's a list of child Components or config objects. In a menu, a config object with no xtype creates a MenuItem Component. The MenuItem class accepts the following config options in addition to those it inherits: icon: The URL of an image to display as an icon iconCls: A CSS class name which allows a stylesheet to specify a background image to use as an icon text: The text to display handler: A function to call when the item is clicked menu: A Menu object, or Menu configuration object or an array of menu items to display as a submenu when the item is clicked Because a menu inherits from Container, it can accept other Components as child items. If some complex, menu option dependent input is required, a menu may be configured with a panel as a child item. The menu config of "Menu Option 2" we're creating next contains a FormPanel as its sole child item: { text: 'Menu Option 2', iconCls: 'flag-green', menu: { plain: true, items: { xtype: 'form', border: false, bodyStyle: 'background:transparent;padding:5px', labelWidth: 70, width: 300, defaults: { anchor: '100%' }, items: [{ xtype: 'combo', editable: false, fieldLabel: 'Select', triggerAction: 'all', store: [ [0, 'One or...'], [1 ,'The other']], value: 0, getListParent: function() { return this.el.up('div.x-menu'); } }, { xtype: 'textfield', fieldLabel: 'Title' }], fbar: [{ text: 'Submit' }] } } } The configurations in the above object will mostly be familiar by now. There is one extra config we use for the menu which contains the FormPanel. plain: Specify as true so that the menu does not have to show the incised line for separating icons from text The panel within the menu has the following configs: border: Specify as false to produce a panel with no borders. bodyStyle: A CSS style string to apply to the document body. We want to make it transparent to allow the menu to show, and we apply padding. The ComboBox must render its dropdown list to the menu's element so that clicking on the list does not trigger the menu to hide: GetListParent: This is a function which a ComboBox may be configured with. It must return the HTML element to render the dropdown list into. By default a ComboBox renders its dropdown into the document. We call the up function of the Ext.Element class to find the ancestor node of the combo's element which is a DIV which has the CSS class "x-menu". The FormPanel as a child of a menu will display like this: A toolbar for every occasion An Ext JS Panel, and every Ext JS Component which inherits from the Panel class (This includes Window, TreePanel, and GridPanel) can be configured to render and manage a toolbar docked above, or below the panel's body—or both if really necessary. These are referred to as the top and bottom toolbars, or tbar and bbar for short. Panels and subclasses thereof may also be configured with a footer bar which renders buttons right at the bottom of the panel—below any bottom toolbar. The Toolbar class is also an Ext JS Component in its own way, and may when necessary be used on its own, or as a child Component of any Container. Our second example renders a toolbar standalone into the body of the document. We will use all the main button types to illustrate their usage before moving on to add handlers to react to user interaction. The toolbar will contain the following child components: A basic button A button configured with a menu which is displayed when the button is clicked A SplitButton which will display a menu only when its arrow glyph is clicked A CycleButton which on click, cycles between three different options A pair of mutually exclusive toggle buttons of which only one may be in a "pressed" state at once Ext.onReady(function(){ new Ext.Toolbar({ renderTo: Ext.getBody(), items: [{ xtype: 'button', text: 'Button' },{ xtype: 'button', text: 'Menu Button', menu: [{ text: 'Better' },{ text: 'Good' },{ text: 'Best' }] },{ xtype: 'splitbutton', text: 'Split Button', menu: [{ text: 'Item One' },{ text: 'Item Two' },{ text: 'Item Three' }] }, { xtype: 'cycle', showText: true, minWidth: 100, prependText: 'Quality: ', items: [{ text: 'High', checked: true }, { text: 'Medium' }, { text: 'Low' }] }, { text: 'Horizontal', toggleGroup: 'orientation-selector' }, { text: 'Vertical', toggleGroup: 'orientation-selector' }] }); }); As usual, everything is inside our onReady event handler. The items config holds our toolbar's entire child Components—I say child Components and not buttons because as we now know, the toolbar can accept many different types of Ext JS Components including entire forms or just form fields—which we will be implementing later on in this article. The result of the above code looks like this: The default xtype for each element in the items config is button. We can leave out the xtype config element if button is the type we want, but I like to include it just for clarity. Button configuration In addition to inherited config options, a button accepts the following configurations which we will be using in the following examples for this article: icon: The URL of an image to display as an icon iconCls: A CSS class name which allows a stylesheet to specify a background image to use as an icon text: The text to display handler: A function to call when the button is clicked menu: A Menu object, or Menu configuration object, or an array of menu items to display as a submenu when the button is clicked enableToggle: Specify as true to make a single button toggleable between pressed and unpressed state toggleGroup: A mnemonic string identifying a group of buttons of which only one may be in a "pressed" state at one time toggleHandler: A function to be called when a button's "pressed" state is changed A basic button Creating a button is fairly straightforward; the main config option is the text that is displayed on the button. We can also add an icon to be used alongside the text if we want to. A handler function is called when the button is clicked. Here is the most basic configuration of a button: { xtype: 'button', text: 'Button', handler: functionReference } The following screenshot shows what happens when the mouse is hovered over the Button button: Button with a menu A button may be configured to act as a trigger for showing a dropdown menu. If configured with a menu option, clicking the button displays a menu below the button. The alignment of the menu is configurable, but defaults to being shown below the button. Each option within the menu may itself be configured with a menu option allowing a familiar cascading menu system to be built very easily. The following is a config for a button which displays a dropdown menu upon click: { xtype: 'button', text: 'Button', menu: [{ text: 'Better' },{ text: 'Good' },{ text: 'Best' }] } The following screenshot shows what happens when the Menu Button is clicked on, and the mouse is hovered over the Best option:
Read more
  • 0
  • 0
  • 3613
Visually different images

article-image-importing-structure-and-data-phpmyadmin-33x-effective-mysql-management
Packt
12 Oct 2010
11 min read
Save for later

Importing Structure and Data in phpMyAdmin 3.3.x for MySQL Management

Packt
12 Oct 2010
11 min read
In general, an exported file can be imported either to the same database it came from or to any other database; the XML format is an exception to this and a workaround is given in the XML section later in this chapter. Also, a file generated from an older phpMyAdmin version should have no problem being imported by the current version, but the difference between the MySQL version at the time of export and the one at the time of import might play a bigger role regarding compatibility. It's difficult to evaluate how future MySQL releases will change the language's syntax, which could result in import challenges. The import feature can be accessed from several panels: The Import menu available from the homepage, the Database view, or the Table view The Import files menu offered inside the Query window An import file may contain the DELIMITER keyword. This enables phpMyAdmin to mimic the mysql command-line interpreter. The DELIMITER separator is used to delineate the part of the file containing a stored procedure, as these procedures can themselves contain semicolons. The default values for the Import interface are defned in $cfg['Import']. Before examining the actual import dialog, let's discuss some limits issues. Limits for the transfer When we import, the source file is usually on our client machine and therefore must travel to the server via HTTP. This transfer takes time and uses resources that may be limited in the web server's PHP configuration. Instead of using HTTP, we can upload our file to the server by using a protocol such as FTP, as described in the Reading files from a web server upload directory section. This method circumvents the web server's PHP upload limits. Time limits First, let's consider the time limit. In config.inc.php, the $cfg['ExecTimeLimit'] configuration directive assigns, by default, a maximum execution time of 300 seconds (five minutes) for any phpMyAdmin script, including the scripts that process data after the file has been uploaded. A value of 0 removes the limit, and in theory, gives us infinite time to complete the import operation. If the PHP server is running in safe mode, modifying $cfg['ExecTimeLimit'] will have no effect. This is because the limits set in php.ini or the user-related web server configuration file, (such as .htaccess or the virtual host configuration files) take precedence over this parameter. Of course, the time it effectively takes depends on two key factors: Web server load MySQL server load The time taken by the file, as it travels between the client and the server does not count as execution time because the PHP script only starts to execute after the file has been received on the server. Therefore, the $cfg['ExecTimeLimit'] parameter has an impact only on the time used to process data (like decompression or sending it to the MySQL server). Other limits The system administrator can use the php.ini file or the web server's virtual host configuration file to control uploads on the server. The upload_max_filesize parameter specifies the upper limit or maximum file size that can be uploaded via HTTP. This one is obvious, but another less obvious parameter is post_max_size. As HTTP uploading is done via the POST method, this parameter may limit our transfers. For more details about the POST method, please refer to http://en.wikipedia.org/wiki/Http#Request_methods. The memory_limit parameter is provided to prevent web server child processes from grabbing too much of the server's memory—phpMyAdmin runs inside a child process. Thus, the handling of normal file uploads, especially compressed dumps, can be compromised by giving this parameter a small value. Here, no preferred value can be recommended; the value depends on the size of uploaded data we want to handle and on the size of the physical memory. The memory limit can also be tuned via the $cfg['MemoryLimit'] parameter in config.inc.php, as seen in Chapter 6, Exporting Structure and Data (Backup). Finally, file uploads must be allowed by setting file_uploads to On; otherwise, phpMyAdmin won't even show the Location of the textfile dialog. It would be useless to display this dialog as the connection would be refused later by the PHP component of the web server. Handling big export files If the file is too big, there are ways in which we can resolve the situation. If the original data is still accessible via phpMyAdmin, we could use phpMyAdmin to generate smaller CSV export files, choosing the Dump n rows starting at record # n dialog. If this were not possible, we could use a spreadsheet program or a text editor to split the file into smaller sections. Another possibility is to use the upload directory mechanism, which accesses the directory defined in $cfg['UploadDir']. In recent phpMyAdmin versions, the Partial import feature can also solve this file size problem. By selecting the Allow interrupt... checkbox, the import process will interrupt itself if it detects that it's close to the time limit. We can also specify a number of queries to skip from the start, in case we successfully import a number of rows and wish to continue from that point. Uploading into a temporary directory On a server, a PHP security feature called open_basedir (which limits the files that can be opened by PHP to the specified directory tree) can impede the upload mechanism. In this case, or if uploads are problematic for any other reason, the $cfg['TempDir'] parameter can be set with the value of a temporary directory. This is probably a subdirectory of phpMyAdmin's main directory, into which the web server is allowed to put the uploaded file. Importing SQL files Any file containing MySQL statements can be imported via this mechanism. This format is more commonly used for backup/restore purposes. The relevant dialog is available in the Database view or the Table view, via the Import subpage, or in the Query window. There is no relation between the currently-selected table (here author) and the actual contents of the SQL file that will be importeAll of the contents of the SQL file will be imported, and it's those contents that determine which tables or databases are affected. However, if the imported file does not contain any SQL statementsto select a database, all statements in the imported file will be executed on the currently selected database. Let's try an import exercise. First, we make sure that we have a current SQL export of the book table (as explained in Chapter 6, Exporting Structure and Data (Backup)). This export file must contain the structure and the data. Then we drop the book table—yes, really! We could also simply rename it. (See Chapter 9, Performing Table and Database Operations, for the procedure.) Now it's time to import the file back. We should be on the Import subpage, where we can see the Location of the text file dialog. We just have to hit the Browse button and choose our file. phpMyAdmin is able to detect which compression method (if any) has been applied to the file. Depending on the phpMyAdmin version, and the extensions that are available in the PHP component of the web server, there is variation in the format that the program can decompress. However, to import successfully, phpMyAdmin must be informed of the character set of the file to be imported. The default value is utf8. However, if we know that the import file was created with another character set, we should specify it here. A SQL compatibility mode selector is available at import time. This mode should be adjusted to match the actual data that we are about to import, according to the type of the server where the data was previously exported. Another option, Do not use AUTO_INCREMENT for zero values, is selected by default. If we have a value of zero in a primary key and we want it to stay zero instead of being auto-incremented, we should use this option. To start the import, we click on Go. The import procedure continues and we receive a message: Import has been successfully finished, 2 queries executed. We can browse our newly-created tables to confirm the success of the import operation. The file could be imported for testing in a different database or even on another MySQL server. Importing CSV files In this section, we will examine how to import CSV files. There are two possible methods—CSV and CSV using LOAD DATA. The first method is implemented internally by phpMyAdmin and is the recommended one for its simplicity. With the second method, phpMyAdmin receives the file to be loaded and passes it to MySQL. In theory, this method should be faster. However, it has more requirements due to MySQL itself (see the Requirements subsection of the CSV using LOAD DATA section). Differences between SQL and CSV formats There are some differences between the SQL and CSV formats. The CSV file format contains data only, so we must already have an existing table in place. This table does not need to have the same structure as the original table (from which the data comes); the Column names dialog enables us to choose which columns are affected in the target table. Because the table must exist prior to the import, the CSV import dialog is available only from the Import subpage in the Table view, and not in the Database view. Exporting a test file Before trying an import, let's generate an author.csv export file from the author table. We use the default values in the CSV export options. We can then Empty the author table—we should avoid dropping this table because we still need the table structure. CSV From the author table menu, we select Import and then CSV: We can influence the behavior of the import in a number of ways. By default, importing does not modify existing data (based on primary or unique keys). However, the Replace table data with file option instructs phpMyAdmin to use the REPLACE statement instead of the INSERT statement, so that existing rows are replaced with the imported data. Using Ignore duplicate rows, INSERT IGNORE statements are generated. These cause MySQL to ignore any duplicate key problems during insertion. A duplicate key from the import file does not replace existing data, and the procedure continues for the next line of CSV data. We can also specify the character that terminates each field, the character that encloses data, and the character that escapes the enclosing character. Usually, this is. For example, for a double quote enclosing character, if the data field contains a double quote, it must be expressed as "some data " some other data". For Lines terminated by, recent versions of phpMyAdmin offer the auto choice, which should be tried first as it detects the end-of-line character automatically. We can also specify manually which characters terminate the lines. The usual choice is n for UNIX-based systems, rn for DOS or Windows systems, and r for Mac-based system (up to Mac OS 9). If in doubt, we can use a hexadecimal file editor on our client computer (not part of phpMyAdmin) to examine the exact codes. By default, phpMyAdmin expects a CSV file with the same number of fields and the same field order as the target table. However, this can be changed by entering a comma-separated list of column names in Column names, respecting the source file format. For example, let's say our source file contains only the author ID and the author name information: "1","John Smith" "2","Maria Sunshine" We'd have to put id, name in Column names in order to match the source file. When we click on Go, the import is executed and we receive a confirmation. We might also see the actual INSERT queries generated if the total size of the file is not too big. Import has been successfully finished, 2 queries executed. INSERT INTO `author` VALUES ('1', 'John Smith', '+01 445 789-1234')# 1 row(s) affected. INSERT INTO `author` VALUES ('2', 'Maria Sunshine', '333-3333')# 1 row(s) affected.
Read more
  • 0
  • 0
  • 2438

article-image-installing-phpmyadmin
Packt
12 Oct 2010
10 min read
Save for later

Installing phpMyAdmin

Packt
12 Oct 2010
10 min read
  Mastering phpMyAdmin 3.3.x for Effective MySQL Management Intoduction It's time to install the product and configure it minimally for first-time use. Our reason for installing phpMyAdmin could be one of the following: Our host provider did not install a central copy Our provider installed it, but the version installed is not current We are working directly on our enterprise's web server Required information Some host providers offer an integrated web panel where we can manage accounts, including MySQL accounts, and also a file manager that can be used to upload web content. Depending on this, the mechanism that we use to transfer phpMyAdmin source files to our webspace may vary. We will need some specific information (listed below) before starting the installation: The web server's name or address: Here, we will assume it to be www.mydomain.com Our web server's account information (username, password): This information will be used for either FTP or SFTP transfer, SSH login, or web control panel login. The MySQL server's name or IP address: If this information is not available, a good alternative choice is localhost, which means that the MySQL server is located on the same machine as the web server. We will assume this to be localhost. Our MySQL server's account information (username, password). System requirements The up-to-date requirements for a specific phpMyAdmin version are always stated in the accompanying Documentation.html file. For phpMyAdmin 3.3, the minimum PHP version required is PHP 5.2 with session support and the Standard PHP Library (SPL). Moreover, the web server must have access to a MySQL server (version 5.0 or later)—either locally or on a remote machine. It is strongly recommended that the PHP mcrypt extension be present for improved performance in cookie authentication mode. In fact, on a 64-bit server, this extension is required. On the browser side, cookie support must be activated, whatever authentication mode we use. Downloading the files There are various files available in the Download section of http://www.phpmyadmin.net. There might be more than one version offered here, and it is always a good idea to download the latest stable version. We only need to download one file, which works regardless of the platform (browser, web server, MySQL, or PHP version). For version 3.3, there are two groups of files—english and all-languages. If we need only the English interface, we can download a file whose name contains "english"—for example, phpMyAdmin-3.3.2-english.zip. On the other hand, if we have the need for at least one other language, choosing all-languages would be appropriate. If we are using a server supporting only PHP4—for which the PHP team has discontinued support since December 31, 2007—the latest stable version of phpMyAdmin is not a good choice for download. I recommend using version 2.11.x, which is the latest branch that supports PHP4. The files offered have various extensions: .zip, .tar.bz2, .tar.gz, .7z. Download a file having an extension for which you have the corresponding extractor. In the Windows world, .zip is the most universal file format, although the files are bigger than .gz or .bz2 files (which are common in the Linux/Unix world). The .7z extension denotes a 7-Zip file, which is a format that achieves a higher compression ratio than the other formats offered—an extractor is available at http://www.7-zip.org. In the following examples, we will assume that the chosen file was phpMyAdmin-3.3.2-all-languages.zip. After clicking on the appropriate file, the nearest mirror site will be chosen by Sourceforge.net. The file will start to download, and we can save it on our computer. Installing on different platforms The next step depends on the platform you are using. The following sections detail the procedures for some common platforms. You may proceed directly to the relevant section. Installing on a remote server using a Windows machine Using the File explorer, we double-click the phpMyAdmin-3.3.2-all-languages.zip file that we just downloaded on the Windows machine. A file extractor will start, showing us all of the scripts and directories inside a main phpMyAdmin-3.3.2-all-languages directory. Use whatever mechanism your file extractor offers to save all the files, including subdirectories, to some location on your workstation. Here, we have chosen C:. Therefore, a C:phpMyAdmin-3.3.2-all-languages directory has been created for extraction. Now, it's time to transfer the entire directory structure C:phpMyAdmin-3.3.2-alllanguages to the web server in our webspace. We use our favorite SFTP or FTP software, or the web control panel, for the transfer. The exact directory under which we transfer phpMyAdmin may vary. It could be our public_html directory or another directory to which we usually transfer web documents. For further instructions about the exact directory to be used, or the best way to transfer the directory structure, we can consult our host provider's help desk. After the transfer is complete, these files can be removed from our Windows machine as they are no longer needed. Installing on a local Linux server Let's say we chose phpMyAdmin-3.3.2-all-languages.tar.gz and downloaded it directly to some directory on the Linux server. We move it to our web server's document root directory (for example, /var/www/html) or to one of its subdirectories (for example, /var/www/html/utilities). We then extract it by issuing the following shell command or by using any graphical file extractor that our window manager offers: tar -xzvf phpMyAdmin-3.3.2-all-languages.tar.gz We must ensure that the permissions and ownership of the directory and files are appropriate for our web server. The web server user or group must be able to read them. Installing on local Windows servers (Apache, IIS) The procedure here is similar to that described in the Installation on a remote server using a Windows machine section, except that the target directory will be under our DocumentRoot (for Apache) or our wwwroot (for IIS). Of course, we do not need to transfer anything after modifications are made to config.inc.php (described in the next section), as the directory is already on the webspace. Apache is usually run as a service. Hence, we have to ensure that the user under whom the service is running has normal read privileges to access our newly-created directory. The same principle applies to IIS, which uses the IUSR_machinename user. This user must have read access to the directory. You can adjust permissions in the Security/permissions tab of the directory's properties. Configuring phpMyAdmin Here, we will learn how to prepare and use the configuration file containing the parameters to connect to MySQL, and which can be customized as per our requirements. Before configuring, we can rename the directory phpMyAdmin-3.3.2-all-languages to something like phpMyAdmin or just something easier to remember. This way, we and our users can visit an easily-remembered URL to start phpMyAdmin. On most servers, the directory part of URLs is case-sensitive, so we should communicate the exact URL to our users. We can also use a symbolic link if our server supports this feature. The config.inc.php file This file contains valid PHP code that defines the majority of the parameters (expressed by PHP variables) that we can change in order to tune phpMyAdmin to our own needs. There are also normal PHP comments in it, and we can comment our changes. Be careful not to add any blank lines at the beginning or end of the file; doing so would hamper the execution of phpMyAdmin. Note that phpMyAdmin looks for this file in the first level directory—the same one where index.php is located. In versions before 2.8.0, a generic config.inc.php file was included in the downloaded kit. Since 2.8.0, this file is no longer present in the directory structure. Since version 2.9.0, a config.sample.inc.php file is included, and this can be copied and renamed to config.inc.php to act as a starting point. However, it is recommended that you use the web-based setup script instead, for a more comfortable configuration interface. There is another file—layout.inc.php—that contains some configuration information. Because phpMyAdmin offers theme management, this file contains the theme-specific colors and settings. There is one layout.inc.php file per theme, located in themes/themename, for example, themes/original. Avoiding false error messages about permissions on config.inc.php In its normal behavior, phpMyAdmin verifies that the permissions on this file do not allow everyone to modify it. This means that the file should not be writable to the world. Also, it displays a warning if the permissions are not correct. However, in some situations (for example, an NTFS file system mounted on a non-Windows server), the permission detection fails. In these cases, you should set the followingparameter to false: $cfg['CheckConfigurationPermissions'] = false; The following sections explain various methods for adding or changing a parameter in the config.inc.php file. Configuration principles phpMyAdmin's behavior, given that no configuration file is present, has changed in version 3.1.0. In versions 3.0 and earlier, the application used its default settings as defined in libraries/config.default.php and tried to connect to a MySQL server on localhost—the same machine where the web server is running—with user as root and no password. This is the default set-up produced by most MySQL installation procedures, even though it is not really secure. Therefore, if our freshly installed MySQL server were still to have the default root account, we would have logged on automatically and would have seen a warning given by phpMyAdmin about such lack of security. If the notion of a MySQL root user eludes you, now might be the time to browse http://dev.mysql.com/doc/refman/5.1/en/privilege-system.html, in order to learn the basics about MySQL's privilege system. Since version 3.1.0, the development team has wanted to promote a more flexible login panel. This is why, with the lack of a configuration file, phpMyAdmin displays the cookie-based login panel by default We can verify this fact by visiting http://www.mydomain.com/phpMyAdmin and substituting the appropriate values for the domain part and the directory part. If we are able to log in, it means that there is a MySQL server running on the same host as the web server (localhost) and we've just made a connection to it. However, not having created a configuration file means that we would not be able to manage other hosts via our installation of phpMyAdmin. Moreover, many advanced phpMyAdmin features (for example, query bookmarks, full relational support, column transformation, and so on) would not be activated. The cookie-based authentication method uses Blowfish encryption for storing credentials in browser cookies. If no configuration file exists, a Blowfish secret key is generated and stored in session data, which can open the door to security issues. This is why the following warning message is displayed: The configuration file now needs a secret passphrase (blowfish_secret). At this point, we have some choices: Use phpMyAdmin without a configuration file Use the web-based setup script to generate a config.inc.php file Create a config.inc.php file manually These options are presented in the following sections. We should note that even if we use the web-based setup script, we should familiarize ourselves with the config.inc.php file format, because the setup script does not cover all of the possible configuration options.
Read more
  • 0
  • 0
  • 1592

article-image-performing-table-and-database-operations-phpmyadmin-33x-effective-mysql-management
Packt
12 Oct 2010
4 min read
Save for later

Performing Table and Database Operations in phpMyAdmin 3.3.x for Effective MySQL Management

Packt
12 Oct 2010
4 min read
  Mastering phpMyAdmin 3.3.x for Effective MySQL Management A complete guide to get started with phpMyAdmin 3.3 and master its features The best introduction to phpMyAdmin available Written by the project leader of phpMyAdmin, and improved over several editions A step-by-step tutorial for manipulating data with phpMyAdmin Learn to do things with your MySQL database and phpMyAdmin that you didn't know were possible!        Introduction Various links that enable table operations have been put together on the Operations subpage of the Table view. Here is an overview of this subpage: Maintaining a table During its lifetime, a table repeatedly gets modified and is therefore continually growing and shrinking. In addition, outages may occur on the server, leaving some tables in a damaged state. Using the Operations subpage, we can perform various operations, which are listed next. However, not every operation is available for every storage engine: Check table: Scans all rows to verify that deleted links are correct. A checksum is also calculated to verify the integrity of the keys. If everything is alright, we will obtain a message stating OK or Table is already up to date; if any other message shows up, it's time to repair this table (see the third bullet). Analyze table: Analyzes and stores the key distribution; this will be used on subsequent JOIN operations to determine the order in which the tables should be joined. This operation should be performed periodically (in case data has changed in the table), in order to improve JOIN efficiency. Repair table: Repairs any corrupted data for tables in the MyISAM and ARCHIVE engines. Note that a table might be so corrupted that we cannot even go into Table view for it! In such a case, refer to the Multi-table operations section for the procedure to repair it. Optimize table: This is useful when the table contains overheads. After massive deletions of rows or length changes for VARCHAR fields, lost bytes remain in the table. phpMyAdmin warns us in various places (for example, in the Structure view) if it feels the table should be optimized. This operation reclaims unused space in the table. In the case of MySQL 5.x, the relevant tables that can be optimized use the MyISAM, InnoDB, and ARCHIVE engines. Flush table: This must be done when there have been many connection errors and the MySQL server blocks further connections. Flushing will clear some internal caches and allow normal operations to resume. Defragment table: Random insertions or deletions in an InnoDB table fragment its index. The table should be periodically defragmented for faster data retrieval. This operation causes MySQL to rebuild the table, and only applies to InnoDB. The operations are based on the available underlying MySQL queries—phpMyAdmin only calls those queries. Changing table attributes Table attributes are the various properties of a table. This section discusses the settings for some of them. Table storage engine The first attribute that we can change is called Storage Engine. This controls the whole behavior of the table—its location (on-disk or in-memory), the index structure, and whether it supports transactions and foreign keys. The drop-down list varies depending on the storage engines supported by our MySQL server. Changing a table's storage engine may be a long operation if the number of rows is large. Table comments This allows us to enter comments for the table: These comments will be shown at appropriate places—for example, in the navigation panel, next to the table name in the Table view, and in the export file. Here is what the navigation panel looks like when the $cfg['ShowTooltip'] parameter is set to its default value of TRUE: The default value (FALSE) of $cfg['ShowTooltipAliasDB'] and $cfg['ShowTooltipAliasTB'] produces the behavior we saw earlier—the true database and table names are displayed in the navigation panel and in the Database view for the Structure subpage. Comments appear when the cursor is moved over a table name. If one of these parameters is set to TRUE, the corresponding item (database names for DB and table names for TB) will be shown as a tooltip instead of the names. This time, the mouseover box shows the true name for the item. This is convenient when the real table names are not meaningful. There is another possibility for $cfg['ShowTooltipAliasTB']—the 'nested' value. Here is what happens if we use this feature: The true table name is displayed in the navigation panel The table comment (for example project__) is interpreted as the project name and is displayed as it is
Read more
  • 0
  • 0
  • 2259
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 €14.99/month. Cancel anytime
article-image-creating-photo-gallery-expressionengine-2
Packt
11 Oct 2010
12 min read
Save for later

Creating a Photo Gallery with ExpressionEngine 2

Packt
11 Oct 2010
12 min read
  Building Websites with ExpressionEngine 2 A step-by-step guide to ExpressionEngine: the web-publishing system used by top designers and web professionals everywhere Learn all the key concepts and terminology of ExpressionEngine: channels, templates, snippets, and more Use RSS to make your content available in news readers including Google Reader, Outlook, and Thunderbird Manage your ExpressionEngine website, including backups, restores, and version updates Written in an easy-to-follow step-by-step style, with plenty of examples and exercises         Read more about this book      (For more resources on ExpressionEngine, see here.) Designing your photo gallery There are many different ways you can approach creating a photo gallery in ExpressionEngine. At the most basic level, you have a choice between each channel entry containing only one photo (and a description) or each channel entry containing a set of photos. If you allow only one photo per entry, you can use categories to organize the photos into galleries (and you can even include the same photo in more than one gallery). If you allow multiple photos per channel entry, each entry represents a photo gallery by itself.   One way to accommodate multiple photos per entry is to create as many custom fields as the photos you think you will have in a gallery. For example, if you know each gallery will have a maximum of 20 photos, then you could create 20 custom fields for the photos and 20 custom fields for the descriptions. This solution works, but is not the most flexible (that is, to add 21 photos to a gallery, you would have to modify your custom fields and your templates). An alternative approach to accommodate multiple photos per entry without creating an abundance of custom fields is to use a third party add-on such as Matrix by Pixel & Tonic (http://pixelandtonic.com/matrix). This add-on allows for tabular data in channel entries—you define the column headings (such as the photo and the description) and then add a row in the table for each photo. In each channel entry, you can create as many rows as you need. For example, you can create one entry with 12 photos and another entry with 25 photos. Rather than creating lots of custom fields, or using a third party add-on, this article will show you a simple and elegant way to create a photo gallery using the one photo per entry design and then will use categories to organize the photos into galleries. Before you create your photo gallery channel, you first need to define where your photos will be stored. File manager The file manager is where you can upload new photos or crop, resize, rotate, or delete the images you have already uploaded, all from within the ExpressionEngine control panel. For this photo gallery, you will create a new upload destination—this is the directory on your server where ExpressionEngine will store your photos. The first step in creating a new upload destination is to create the new directory on your server. Create a new directory called photos in /images. If you are following along on an actual web server, ensure that the new directory has 777 permissions (usually right-clicking on the directory in your FTP client will allow you to set permissions).If, instead of creating a new sub-directory inside the "/images" directory, you prefer to create a new top-level directory and you are using the ".htaccess" exclude method to remove the "index.php" from ExpressionEngine URLs, then be sure to add the new directory to your ".htaccess" file. Next, you need to tell ExpressionEngine where this directory is. Inside the control panel, select Content and then File Manager. On the left-hand side of the screen, you will see the directory or directories where you can currently upload files to (if any), along with the files currently in each directory. In the toolbar on the right-hand side, underneath File Tools, select Create New Upload Destination. Enter a descriptive name of Photo Gallery. The Server Path and URL may be pre-filled, however, you should make sure it points to the actual directory you just created (/images/photos). If you are following along in a localhost environment, the URL would be http://localhost/images/photos. Leave Allowed File Types as Images only. All the fields that begin with maximum can be left blank. These fields allow you to restrict the size, height, and width of photos. If you do enter values in here, and then later try to upload a file that exceeds these limits, you will see an error message such as The file you are attempting to upload is larger than the permitted size. Set the Image Properties, Image Pre Formatting, and Image Post Formatting to be blank. These fields allow you to enter code that appears inside, before, and after the img tag. However, you will format your img tag as needed inside your template. The File Properties, File Pre, and Post Formatting can be ignored for now as they only apply to non-image files that you upload (and you have specified that you are only allowing images in your photo gallery). If desired, you can allow certain member groups to upload files. The member groups you see listed (if any) will depend on the member groups you have. Set all the member groups to Yes except Members, which should be set as No. Click Submit and your new upload destination will be ready to go. Go back to the file manager and you can see the new photo gallery upload destination with no files. Creating your photo gallery channel Now that you have created a place to store your photos, you can create your photo gallery channel. You will follow the same basic steps—creating custom fields and categories, creating your channel, publishing some entries, and then building your templates. Creating your custom fields Since you are going to have one photo per channel entry, you have a lot of flexibility to create as many custom fields for each photo as you see fit—for example, you could have fields to capture the location of the photograph, the subject of the photo, the type of camera that was used, the name of the photographer, and so forth. However, to keep things simple, you will only create two custom fields right now—one for the photo itself and one for the description. From the main menu of the control panel, select Admin, Channel Administration, and then Custom Fields. Select Create a New Channel Field Group and call the new group photos. Click Submit. Next to the new group, select Add/Edit Custom Fields and then select Create a New Custom Field. The field type will be File. The field label will be Photo and the field name will be photos_photo (the first part representing the field group name). In the field instructions, indicate that photos in the photo gallery should be no more than 600x800 pixels (so that they fit on a typical computer screen without scrolling).You could also prevent photos that are bigger than 600x800 pixels from being uploaded by specifying the maximum width and height in the File Upload Preferences for the photo gallery upload destination. You have not done this here because it would prevent you from being able to upload a larger photo and then re-sizing it using file manager. The field should be required, but not searchable, and should be shown by default. The field display order should be 1 and the file type should be Image. Click Submit. Click Create a New Custom Field again. This time, the field type should be Textarea, the field label Caption, and the field name photos_caption. The field instructions can be left blank. Answer Yes to it being a required field, being searchable and being shown by default. The Field Display Order should be 2. The number of rows can be left as 6 and the default text formatting should be set to Auto <br /> (this will prevent unwanted whitespace in your captions due to extra paragraph tags being added, but will also allow multi-line captions). Say No to allowing an override on the Publish page. The text direction can also be left as left-to-right. Finally, say Yes to Formatting Buttons, Spellcheck, and Write mode. Say No to Smileys, Glossary, and the File Chooser. Click Submit to create the new field. Now that you have your custom fields, you can define your categories. Creating your categories As discussed at the beginning of this article, you are going to use categories to distinguish between photo galleries. To start with, you are going to create two photo galleries—one for vacation photos and one for local photos. You can always come back and add more galleries later. Still in the control panel, select Admin, Channel Administration, and then Categories. Select Create a New Category Group and name it Photo Categories. Select Allow All HTML in the category field formatting and check the boxes to allow other member groups to edit (or delete) categories as appropriate. (If you see a message saying that there are no member groups allowed to edit/delete categories, this is fine too). Click Submit. Back on the Category Management screen, select Add/Edit Categories for the Photo Categories category group. Click Create a New Category. The first category will be called Local Photos. The Category URL will default to local_photos. Type in a category description (you will later display this on your website), leave the Category Image URL blank, leave the Category Parent as None, and click Submit. Select Create a New Category again. This time call the new category Vacation Photos, with a URL of vacation_photos. Type in a category description such as A selection of vacation photos taken by Ed & Eg. Leave the category image URL blank and the category parent as None. Click Submit. Now that you have your category group and custom field group defined, you can go ahead and create your channel. Creating your channel The actual creating of your channel is very straightforward. Select Admin | Channel Administration | Channels. Select Create a New Channel. Call the new channel Photos with a short name of photos. Do not duplicate an existing channel's preferences. Select Yes to Edit Group Preferences and select Photo Categories for the category group, Statuses for the status group, and photos for the field group. Select No to creating new templates and then click Submit. Your channel is created! Now you can start creating some content and displaying the photos on your website. Uploading your first photos There are three ways to upload photos to your website. Your first option is to go to File Manager (under the Content menu) and select File Upload on the right-hand toolbar. Alternatively, you can go to publish an entry in the Photos channel, click on Add File, and upload a file. Both of these options are convenient since they use the built-in ExpressionEngine file manager to upload your file—you never have to leave the control panel. However, you can only upload one photo at a time and you may run into issues if you try and upload very large photos (greater than 2 MB). The third option for uploading photos is to do so directly, using FTP, just as you would upload any files to your website. Since this requires another tool, it is less convenient than uploading a single photo from within ExpressionEngine, but if you are uploading lots of photos, then using FTP is a lot faster to do. This is the method we will use here. The built-in file manager also allows you to crop, resize, and rotate images (although you can take advantage of these tools even if you do not use file manager to upload the files).   Download the example photos (local1.jpg through local8.jpg and vacation1.jpg through vacation8.jpg) from either the Packtpub support page at http://www.packtpub.com/support or from http://www.leonardmurphy.com/book2/chapter8. (Or you can substitute your own photos). Copy or FTP the photos into the /images/photos directory that you created earlier in the article. Back in the ExpressionEngine control panel, select Content | Publish and then select the Photos channel. Type in a title of Fireworks and a caption Fireworks exploding with a bang. Then select Add File. The first screen to appear in the Upload File screen. Since you have already uploaded the files, you can simply select the photo gallery option in the left-hand menu.If no photos appear under the photo gallery, or the files appear but no thumbnails appear, try logging out of the control panel and logging back in. (This helps to refresh ExpressionEngine so it recognizes the new files—the first time you access the files after uploading via FTP, ExpressionEngine has to create the thumbnails). Select local1.jpg. On the Categories tab, select Local Photos. Then click Submit. Now, repeat the same steps to create entries for the rest of the photos, using appropriate captions that describe the photos. Be sure to select a category for each photo. There are 16 example photos (eight local and eight vacation photos). Having several example photos in each category will demonstrate how the photo gallery works better.
Read more
  • 0
  • 0
  • 3413

article-image-adding-web-controls-custom-modules-dotnetnuke
Packt
08 Oct 2010
10 min read
Save for later

Adding Web Controls to Custom Modules in DotNetNuke

Packt
08 Oct 2010
10 min read
DotNetNuke 5.4 Cookbook Over 100 recipes for installing, configuring, and customizing your own website with the DotNetNuke CMS Create and customize your own DotNetNuke website with blog, forums, newsletters, wikis and many more popular website features Learn custom module development and rich content management with sample code and tips Provides samples of styling and skinning a DotNetNuke portal Offers advanced programming tips combining DNN with AJAX and JQuery Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible Read more about this book (For more resources on DotNetNuke, see here.) Showing data in a Treeview A Treeview control is used when you have information arranged in a hierarchy like the organizational chart of a company. The Treeview control will show each level in the hierarchy with an icon to drill-down or expand to the next level. Getting ready To follow along with this recipe you must have completed the following recipes: Deploying a module as a standalone package Displaying a Datagrid with filter controls Adding web controls to your Toolbox The Treeview control requires that the employees in the Employee table have been assigned to managers. Here is the data that was used in this recipe: In this example, the employees are arranged in a simple two-level hierarchy. If your ManagerNo is 0 it means you are a manager. Otherwise the manager number on your record is the ItemID of your manager. So John Smith is a manager (his ManagerNo=0) and he manages Kevin Jones and Amy Roe (as their ManagerNo is John Smith's ItemID). How to do it... Launch the Development Tool and load the Employee project. In the Solution Explorer, look under the references and make sure your project includes a reference to DotNetNuke.WebUtility.dll. Double-click to open the ViewEmployee.ascx file. Start by adding a new register directive at the top of the file: <%@ Register tagprefix="DNN" assembly="DotNetNuke.WebControls" namespace="DotNetNuke.UI.WebControls" %> Next, we'll create a simple tree control by placing the following code at the bottom of the file, right after the paging control: <dnn:PagingControl ID="ctlPagingControl" runat="server"></dnn:PagingControl><br /><DNN:DnnTree ID="treeManager" runat="server" CollapsedNodeImage="~imagesplus.gif" ExpandedNodeImage="~imagesminus.gif"></DNN:DnnTree> Next, open the ViewEmployee.ascx.vb file. Look at the top of the file and make sure the following imports are there: Imports System.Data.SqlClient Imports DotNetNuke.UI.WebControls We must create a procedure to populate the tree control with records from the database. Find the Private Methods region at the top of the file and add the following new procedures: #Region "Private Methods"Private Sub PopulateTreeControl() ' set the images to use for the nodes treeManager.ImageList.Add("..imagesicon_hostusers_16px.gif") treeManager.ImageList.Add("..imagesicon_users_16px.gif") ' reset the tree control treeManager.TreeNodes.Clear() Dim objParentNode As TreeNode ' get the list of all managers and create a parent node for each one Dim objEmployeeController As New EmployeeController Dim drMgr As SqlDataReader drMgr = objEmployeeController.GetManagersDR(ModuleId) If drMgr.HasRows Then Do While drMgr.Read() objParentNode = New TreeNode() objParentNode.Text = drMgr("EmpLastName") + ", " + drMgr("EmpFirstName") objParentNode.ImageIndex = 0 ' manager image objParentNode.ClickAction = eClickAction.Expand ' when click on a manager, expand objParentNode.HasNodes = True treeManager.TreeNodes.Add(objParentNode) PopulateEmployeeNodes(objParentNode, drMgr("ItemId")) Loop End If drMgr.Close()End SubPrivate Sub PopulateEmployeeNodes(ByRef objParentNode As TreeNode, ByVal ParentItemId As Integer) Dim objChildNode As TreeNode ' get the list of all employee with the given manager Dim objEmployeeController As New EmployeeController Dim colEmployees As ArrayList Dim objEmployeeInfo As EmployeeInfo Dim TotalRecords As Integer colEmployees = objEmployeeController.GetEmployeesByFilter (ModuleId, ParentItemId, -1, 0, 1000, TotalRecords) If colEmployees.Count > 0 Then ' add a node to the parent that was passed For intEmp = 0 To colEmployees.Count - 1 objEmployeeInfo = CType(colEmployees(intEmp), EmployeeInfo) objChildNode = New TreeNode(objEmployeeInfo.EmpLastName + ", " + objEmployeeInfo.EmpFirstName) objChildNode.ImageIndex = 1 ' employee image objParentNode.TreeNodes.Add(objChildNode) Next intEmp End IfEnd Sub#End Region What we are doing here is calling a new GetManagersDR function for the first level of the tree, then calling the GetEmployeesByFilter function to get the list of employees for each manager. Next, we need to call these new procedures when the page loads, so scroll down to the Page_Load procedure and add the following code inside the IsPostBack check: If Page.IsPostBack = False Then If Not Request.QueryString("PageRecords") Is Nothing Then ddlRecordsPerPage.SelectedValue = Request.QueryString("PageRecords") End If BindManagerDropDown() BindSalaryDropDown() BindData() PopulateTreeControl()End If Next, open the EmployeeController.vb file. The last step is to create the new GetManagersDR function. This is just like the GetManagers function, but this the function returns the list of managers as a DataReader. Add the following code to the bottom of the Public Methods region: Public Function GetManagersDR(ByVal ModuleId As Integer) As SqlDataReader Return DataProvider.Instance().GetManagers(ModuleId)End Function#End Region Select Save All from the File menu. To check the results, build and deploy the module to a development portal for testing. Go to the ACME Employee page to see the list of employees in a tree control. How it works... In this recipe we saw the tasks to organize database records in a hierarchy tree control: We placed the control in the .ascx file We defined the images to use for the expand and collapse indicators In the code behind file we changed the Page_Load procedure to populate the tree We created a PopulateTreeControl procedure with two parts: Query the database for the employee managers For each manager add them to the tree and query the database for the employees they manage Using a TabStrip to separate content There are many times when you have a lot of information to display, but not enough space on the page. The TabStrip control maximizes the available space by separating the content into tabs and displaying one tab at a time. To demonstrate this control we're going to take the five fields of the Edit Employee page and split them onto two different tabs. Getting ready To follow along with this recipe you must have completed the following recipes: Adding web controls to your Toolbox Deploying a module as a standalone package How to do it... Launch the Development Tool and load the Employee project. In the Solution Explorer, look under the references and make sure your project includes a reference to DotNetNuke.WebUtility.dll. Double-click to open the EditEmployee.ascx file. Make sure the following register directive is at the top of the file: <%@ Register tagprefix="DNN" assembly="DotNetNuke.WebControls" namespace="DotNetNuke.UI.WebControls" %> We will replace the existing HTML table containing the employee fields with a TabStrip control table holding the name fields under the first tab and the information fields under the second tab. Replace the existing HTML table with the following highlighted code: <%@ Control language="vb" Inherits="ACME.Modules.Employee.EditEmployee" AutoEventWireup="false Explicit="True" Codebehind="EditEmployee.ascx.vb" %><%@ Register TagPrefix="dnn" TagName="Label" Src="~/controls/LabelControl.ascx" %><%@ Register TagPrefix="dnn" TagName="TextEditor" Src="~/controls/TextEditor.ascx"%><%@ Register TagPrefix="dnn" TagName="Audit" Src="~/controls/ModuleAuditControl.ascx" %><%@ Register tagprefix="DNN" assembly="DotNetNuke.WebControls" namespace="DotNetNuke.UI.WebControls" %> <DNN:DNNTabStrip ID="tsEmployee" runat="server" TabRenderMode="All" CssTabContainer="LoginTabGroup" CssContentContainer="LoginContainerGroup" DefaultContainerCssClass="LoginContainer" DefaultLabel-CssClass="LoginTab" DefaultLabel-CssClassHover="LoginTabHover" DefaultLabel-CssClassSelected="LoginTabSelected" visible="true" > <dnn:DNNTab Label-Text="Employee Name" ID="tab1"> <table width="650" cellspacing="0" cellpadding="0" border="0" summary="Edit Table"> <tr valign="top"> <td class="SubHead" width="125"><dnn:label id="lblEmpFirstName" runat="server" controlname="lblEmpFirstName" suffix=":"> </dnn:label> </td> <td> <asp:TextBox ID="txtEmpFirstName" runat="server"> </asp:TextBox> <asp:RequiredFieldValidator ID="valEmpFirstName" resourcekey="valEmpFirstName.ErrorMessage" ControlToValidate="txtEmpFirstName" CssClass="NormalRed" Display="Dynamic" ErrorMessage="<br>EmpFirstName is required" Runat="server" /> </td> </tr> <tr valign="top"> <td class="SubHead" width="125"><dnn:label id="lblEmpLastName" runat="server" controlname="lblEmpLastName" suffix=":"> </dnn:label> </td> <td> <asp:TextBox ID="txtEmpLastName" runat="server"> </asp:TextBox> <asp:RequiredFieldValidator ID="valEmpLastName" resourcekey="valEmpLastName.ErrorMessage" ControlToValidate="txtEmpLastName" CssClass="NormalRed" Display="Dynamic" ErrorMessage="<br>EmpLastName is required" Runat="server" /> </td> </tr> </table> </dnn:DNNTab> <dnn:DNNTab Label-Text="Information" ID="tab2"> <table width="650" cellspacing="0" cellpadding="0" border="0" summary="Edit Table"> <tr valign="top"> <td class="SubHead" width="125"><dnn:label id="lblManagerNo" runat="server" controlname="lblManagerNo" suffix=":"> </dnn:label> </td> <td> <asp:TextBox ID="txtManagerNo" runat="server"> </asp:TextBox> <asp:RequiredFieldValidator ID="valManagerNo" resourcekey="valManagerNo.ErrorMessage" ControlToValidate="txtManagerNo" CssClass="NormalRed" Display="Dynamic" ErrorMessage="<br>ManagerNo is required" Runat="server" /> </td> </tr> <tr valign="top"> <td class="SubHead" width="125"><dnn:label id="lblHireDate" runat="server" controlname="lblHireDate" suffix=":"> </dnn:label> </td> <td> <asp:TextBox ID="txtHireDate" runat="server"> </asp:TextBox> <asp:RequiredFieldValidator ID="valHireDate" resourcekey="valHireDate.ErrorMessage" ControlToValidate="txtHireDate" CssClass="NormalRed" Display="Dynamic" ErrorMessage="<br>HireDate is required" Runat="server" /> </td> </tr> <tr valign="top"> <td class="SubHead" width="125"><dnn:label id="lblSalary" runat="server" controlname="lblSalary" suffix=":"> </dnn:label> </td> <td> <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="valSalary" resourcekey="valSalary.ErrorMessage" ControlToValidate="txtSalary" CssClass="NormalRed" Display="Dynamic" ErrorMessage="<br>Salary is required" Runat="server" /> </td> </tr> </table> </dnn:DNNTab></dnn:DNNTabStrip><br /><br /><p> <asp:linkbutton cssclass="CommandButton" id="cmdUpdate" resourcekey="cmdUpdate" runat="server" borderstyle="none" text="Update"> </asp:linkbutton>&nbsp; <asp:linkbutton cssclass="CommandButton" id="cmdCancel" resourcekey="cmdCancel" runat="server" borderstyle="none" text="Cancel" causesvalidation="False"> </asp:linkbutton>&nbsp; <asp:linkbutton cssclass="CommandButton" id="cmdDelete" resourcekey="cmdDelete" runat="server" borderstyle="none" text="Delete" causesvalidation="False"> </asp:linkbutton>&nbsp;</p><dnn:audit id="ctlAudit" runat="server" /> The appearance of the tab strip is controlled by the styles we apply to it (CssTabContainer, CssContentContainer, DefaultLabel-CssClass, DefaultLabel-CssClassHover, and DefaultLabel-CssClassSelected). In this example we used the same styles as the DNN Login page so we have a similar look and feel. The styles are defined in the /portals/_default/default.css by default. Select Save All from the File menu. To check the results, build and deploy the module to a development portal for testing. Go to the ACME Employee page and click on the edit icon (the little pencil) next to an employee to display the Edit Employee page. When you edit the employee record you will see the fields have been separated into two separate tabs. Clicking on Employee Name displays the first tab with the name fields: Clicking on Information reveals the remaining fields: How it works... In this recipe we saw the tasks to use a TabStrip control: We placed the control in the .ascx file We separated the existing content onto separate tabs  
Read more
  • 0
  • 0
  • 1726

article-image-kentico-cms-5-website-development-managing-site-structure
Packt
08 Oct 2010
6 min read
Save for later

Kentico CMS 5 Website Development: Managing Site Structure

Packt
08 Oct 2010
6 min read
  Kentico CMS 5 Website Development: Beginner's Guide A clear, hands-on guide to build websites that get the most out of Kentico CMS 5's many powerful features Create websites that meet real-life requirements using example sites built with easy-to-follow steps Learn from easy-to-use examples to build a dynamic website Learn best practices to make your site more discoverable Practice your Kentico CMS skills from organizing your content to changing the site's look and feel Get going with example starter sites such as a corporate site, an e-commerce site, and a community-driven website to jumpstart your web development Written by Thom Robbins, the Web Evangelist for Kentico Software LLC Read more about this book (For more resources on CMS, see here.) A great example of visual hierarchy that is used on every website is headings (h1, h2, h3) which indicate the importance of information and are usually styled in such a way that they guide a visitor from h1 (most important) down to least important. Without cues to the relative importance of different elements, the user has to work harder to understand the information provided by the website. A potential buyer or even someone looking for general information will quickly disregard a design with poor visual hierarchy. Z flow is a design principle that is important to keep in mind as you create layouts. The eye naturally moves across the page in a Z formation. The eye starts in the upper left, crosses over to the right, and then moves back down to the left and over to the right, similar to how the eye moves when reading text. You always want to make sure your design helps the Z-Flow. It’s important to think of your web site as a story, and organize the material in a way that enhances the telling of your story. Here are a couple of things to keep in mind. Home pages should be short and quick to loads. The home page should contain key information. This includes website introduction and links to other pages that contain additional details. Detail pages allow the website to be created in several pieces instead of one or two larger pieces. Time for action – page organization The content tree represents the site map of the website and allows you to organize the structure of documents and choose documents that appear on the right side of the screen. The content tree is where we will spend the most of our time managing content and site hierarchy. It provides the central location to see all site content (both published and unpublished). It also provides some basic drag and drop methods that will make it easier to change the location of items within your site. In this example we will look at how we can reorganize our site. Log into CMS Desk select the Content tab, select the Partners page and then the Gold partners page Drag the Gold partners page up to Services folder, as shown in the following screenshot: Release the mouse button and you will see that your page hierarchy has changed, as shown in the following screenshot: Select the Gold partners page, select the CTRL key on the keyboard and copy it to the Services hierarchy, as shown in the following screenshot: Link the Gold partners page while selecting the Control + Shift keys, as shown in the following screenshot: What just happened? Managing content within the Content tree is an essential part of maintaining your site. We have seen that there are three ways that you can maintain pages: A move takes the entire page and copies it another location in the site A copy takes a snapshot of the current deployed page and places it in the new location A link creates a copy of the page in the current location Time for action – viewing the Google sitemap file There are many different ways to provide Search Engine Optimization(SEO) for your website. The most basic is the sitemap. As the name implies it’s a map of you site. On a single page it shows the structure of your site, its sections, and the links between them. Sitemaps make navigating the site easier and having an updated sitemap is important for search engines. Sitemaps are an important way to communicate with search engines. In robots.txt you tell search engines which part of your site to exclude from indexing, in your site map you tell search engines where you you’d like them to go. Sitemaps are part of good web design practice and something you want to make sure that you are aware of. Using sitemaps offer the opportunity to inform search engines immediately about any changes in your site. Of course, you cannot expect that search engines will rush right away to index your changed pages, but certainly the changes will be indexed faster, compared to when you don’t have a sitemap. Also when you have a sitemap you can rely less on external links that will bring traffic to your site. Sitemaps also help to classify your site content. In this example, we will look at the default googlesitemap.xml file that can then be used to submit to Google. Log into Site Manager and select the Settings tab. From the Sites drop-down select (Global), select the URLs and SEO menu option, and validate the name googlesitemap.xml appears, as shown in the following screenshot: Open a new browser and use the url http://<domain>/CMSPages/googlesitemap.aspx to view the current site map, as shown in the following screenshot: What just happened? The system provides automatic support for the Google Sitemap protocol. This is a protocol designed to help search engines in indexing your site. Now that we have set up the system defaults the sitemap is created automatically based on any changes that occur with the content tree and site structure. Physically, as you can see here the sitemap is located at http://<domain>/CMSPages/Googlesitemap.aspx</domain>. When you enter your sitemap into Google you would use this URL name. XML Extension DisplayBy default IIS is configured to not display XML files for security purposed. In order to make the sitemap accessible using an XML extension you need to configure the XML extension within IIS.
Read more
  • 0
  • 0
  • 1353

article-image-web-controls-dotnetnuke
Packt
08 Oct 2010
7 min read
Save for later

Web Controls in DotNetNuke

Packt
08 Oct 2010
7 min read
DotNetNuke 5.4 Cookbook Over 100 recipes for installing, configuring, and customizing your own website with the DotNetNuke CMS Create and customize your own DotNetNuke website with blog, forums, newsletters, wikis and many more popular website features Learn custom module development and rich content management with sample code and tips Provides samples of styling and skinning a DotNetNuke portal Offers advanced programming tips combining DNN with AJAX and JQuery Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible Read more about this book (For more resources on DotNetNuke, see here.) Introduction One of the powerful features of DNN is the variety of flexible and reusable controls that are available for custom module development. These include many of the web controls seen on the core DNN pages. In this article, we will see how to add these web controls to custom modules and tie them to the tables in the database. In general, using these controls requires four simple steps: Adding the control code to the View or Edit .ascx file Adding a new property to the info object that will supply the values for the control Binding the control to the values Capturing the value from the control and saving to the database (if Edit page) Adding web controls to your Toolbox If you frequently use the visual editor in the development tool to layout your pages, this short recipe will show you how to add the DNN web controls to the Toolbox. How to do it… Launch the Development Tool. Change the editor to Design mode. Make sure the toolbox is displayed. Right-click on the toolbox and select Choose Items…. Click on the Browse button. Navigate to the /bin folder within the DNN source (DNNSource/website/bin). Select the DotNetNuke.Webcontrols.dll and click on Open. Make sure the DNN controls are checked and click on OK. The web controls will now appear under the General section of the toolbox when you edit your code. Next, we need to add a reference to DotNetNuke.WebUtility.dll. Right-click on the Employee project in the Solution Explorer and select Add Reference…. In the pop-up dialog, click on the Browse tab and navigate to the folder holding the DNN source files (for example, My DocumentsDNNSourceWebsitebin). Select the file DotNetNuke.WebUtility.dll and click on OK. Showing an e-mail link in a Datagrid The Datagrid control is perfect for showing records from the database in a neatly formatted table. But the Datagrid can show many other types of information and in this recipe we will see how to display an e-mail hyperlink in a column. Getting ready In this recipe, we will extend the Datagrid. In this recipe we are using a function to generate an e-mail address for our example. This keeps the recipe simple, but isn't really practical. In a real production environment you would store this in the database as part of the Employee table. How to do it... Launch the Development Tool and load the Employee project. Double-click to open the ViewEmployee.ascx file. Locate the Datagrid in the code and add a new column just after the Salary column: <dnn:textcolumn datafield="Salary" headertext="Salary"/> <asp:TemplateColumn HeaderText="Email Contact"> <itemtemplate> <asp:HyperLink id="hlEmail" NavigateUrl='<%# "mailto:" & DataBinder.Eval (Container.DataItem,"ContactEmail") %>' Text='<%# DataBinder.Eval (Container.DataItem,"ContactEmail") %>' Target="_new" runat="server" /> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:datagrid> Next, open the EmployeeInfo.vb file. Find the Public Properties section and add the read-only property EmailAddress to provide an e-mail address constructed from the employee name: ' public properties Public ReadOnly Property EmailAddress() As String Get Return _EmpFirstName.Substring(0, 1) + _EmpLastName + "@yourcompany.com" End Get End Property Select Save All from the File menu. To check the results, build and deploy the module to a development portal for testing. Go to the ACME Employee page to see the list of employees. The new e-mail hyperlink will appear on the right-hand side. (Move the mouse over the image to enlarge.) How it works... In this recipe we saw the tasks to show an e-mail hyperlink in a Datagrid control: We took the Datagrid control and added a new template column holding an e-mail hyperlink control We added a new property to the EmployeeInfo object to provide an e-mail address for the Datagrid Showing checkboxes in a Datagrid An element that is useful to display in a Datagrid is a checkbox-like image to indicate the status of the database record. These are not functioning checkboxes but rather a visual indicator showing the data to be true or false. The control works by having two images, one with a checkmark that is shown when the value is true. The other is an unchecked image that is shown when the value is false. This recipe will work with any image indicating true or false. Checkbox-like images are used in other DNN modules so they are familiar to users, but you can experiment with your own images as well. This recipe has two basic steps: We will create a new property of the EmployeeInfo object called NewHire. This property checks the date of hire from the database and returns true if the employee was hired less than 30 days ago. We will add a new column to the Datagrid that evaluates the NewHire property and shows one image if the NewHire is true and another image if the NewHire is false. Getting ready In this recipe we will extend the Datagrid. How to do it... Launch the Development Tool and load the Employee project. Double-click to open the ViewEmployee.ascx file. The first step is to add a new column to the Datagrid that will show the checkbox images. We will use the Eval function to check the NewHire function. Locate the Datagrid and add a new column just after the Salary column: <dnn:textcolumn datafield="Salary" headertext="Salary"/> <asp:TemplateColumn HeaderText="New Hire"> <itemtemplate> <asp:Image Runat="server" ID="imgApproved" ImageUrl="~/images/checked.gif" Visible='<%# DataBinder.Eval (Container.DataItem,"NewHire")="1" %>'/> <asp:Image Runat="server" ID="imgNotApproved" ImageUrl="~/images/unchecked.gif" Visible='<%# DataBinder.Eval (Container.DataItem,"NewHire")="0" %>'/> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:datagrid> Next, open the EmployeeInfo.vb file. Find the Public Properties section and add the read-only property NewHire that returns true or false if the employee was hired in the last 30 days: ' public properties Public ReadOnly Property NewHire() As Boolean Get Return (Today() - _HireDate).Days < 30 End Get End Property Select Save All from the File menu. To check the results, build and deploy the module to a development portal for testing. Go to the ACME Employee page to see the list of employees. The new checkbox will appear on the right-hand side. Although you cannot click on these checkboxes, they do provide a clear and easy to understand visual status for the records. How it works... In this recipe we saw the tasks to show checkbox images in a Datagrid control: We took the Datagrid control and added a new template column holding two image controls, one checked and the other unchecked. We added a new property to the EmployeeInfo object that returns true or false depending on the database record. We bound the property to the control so that if the property was true then the checked image was displayed. If the property was false the unchecked image was displayed.  
Read more
  • 0
  • 0
  • 1826
article-image-kentico-cms-5-website-development-workflow-management
Packt
07 Oct 2010
3 min read
Save for later

Kentico CMS 5 Website Development: Workflow Management

Packt
07 Oct 2010
3 min read
  Kentico CMS 5 Website Development: Beginner's Guide A clear, hands-on guide to build websites that get the most out of Kentico CMS 5's many powerful features Create websites that meet real-life requirements using example sites built with easy-to-follow steps Learn from easy-to-use examples to build a dynamic website Learn best practices to make your site more discoverable Practice your Kentico CMS skills from organizing your content to changing the site's look and feel Get going with example starter sites such as a corporate site, an e-commerce site, and a community-driven website to jumpstart your web development Written by Thom Robbins, the Web Evangelist for Kentico Software LLC Read more about this book (For more resources on CMS, see here.) Workflow management Workflow is a way to automate a business process for publishing content. Using workflow allows you to delegate portions of the business process to different users or groups for approval. Kentico CMS allows you to use workflow for all documents, including uploaded files. The workflow engine organizes the process of content creation, updates, and publishing content. The following diagram shows an example document lifecycle with workflow. It's important to keep in mind that document versioning is tightly bound with workflow and allows document comparison and version rollback. Time for action – configuring workflow The Kentico CMS workflow process is designed as a state machine. This means that workflows are event driven. A workflow contains three or more states, with only one state active at any given time. Based on an event, a transition is made to another state. Once a transition is made to the final state, the workflow is completed. Within each workflow step, members of authorized roles are allowed to modify, approve, or reject a document. Now, let's configure a workflow for the News folder. In CMS Site Manager, select the Development tab, select Workflows, and click New workflow, as shown in the following screenshot: For the New workflow, enter the Display Name as Approval and Code Name as Approval, as shown in the following screenshot: Select the Steps tab and click on the New workflow step link, as shown in the following screenshot: Quick tip The Edit, Published, and Archived steps are automatically created for every workflow and can't be deleted. These steps use the default system security. Enter the following information and select OK. Select the Roles tab and click Add roles, as shown in the following screenshot: Select the CMS Desk Administrators role and select OK. Select the Scope tab and click on the New workflow scope link, as shown in the following screenshot: What is a workflow scope? The workflow scope defines the folder, documents, and languages that are included in the workflow. In the Starting alias path, click the Select button, as shown in the following screenshot: Select News and then click the Select button, as shown in the following screenshot: Select OK, as shown in the following screenshot, to save the workflow scope.
Read more
  • 0
  • 0
  • 1755

article-image-kentico-cms-5-fundamentals-site-security
Packt
07 Oct 2010
4 min read
Save for later

Kentico CMS 5: Fundamentals of Site Security

Packt
07 Oct 2010
4 min read
  Kentico CMS 5 Website Development: Beginner's Guide A clear, hands-on guide to build websites that get the most out of Kentico CMS 5's many powerful features Create websites that meet real-life requirements using example sites built with easy-to-follow steps Learn from easy-to-use examples to build a dynamic website Learn best practices to make your site more discoverable Practice your Kentico CMS skills from organizing your content to changing the site's look and feel Get going with example starter sites such as a corporate site, an e-commerce site, and a community-driven website to jumpstart your web development Written by Thom Robbins, the Web Evangelist for Kentico Software LLC Read more about this book (For more resources on CMS, see here.) Fundamentals of site security I don't think anyone can dispute that security management is an essential part of our daily routine. We need to make sure that we protect customer data and guard the site from any unwanted intruders. Security management is the process that we use to decide who has access to the site, what areas they are able to see, and what documents they can view and interact with. Kentico CMS security is managed using the: Site Manager Administration tab to edit system-wide data CMS Desk Administration tab to edit data related to a specific website The security model that we use to maintain and administer the system is based on the following: Users — This is an individual user who is assigned a system account. Roles — Security groups that contain users. Because a user can belong to multiple roles, their permissions are calculated as a sum of all permissions granted to all roles they belong to. Document permissions — Document permissions are granted to both users and roles. At runtime, document permissions are calculated as a sum of all permissions granted to the user and their assigned roles. UI personalization — UI personalization is used to remove specific portions of the user interface. Don't forget! Security permissions are calculated at runtime. These are a combination of global settings and individual website settings. It's important to remember that if the user or any of their roles are denied access to a resource, they are always denied access to that resource, even if one of their roles is allowed access. Time for action – creating a new role Now, let's create a new role and assign it to a user using these steps: In CMS Site Manager, select the Administration tab, Roles, and New role, as shown in the following screenshot: What roles are there? Roles are one of the easiest ways to apply security to your users. The system contains a variety of pre-defined roles that are available in the Roles menu item, as shown in the previous screenshot. In the New role dialog, enter the following information and select OK. Select the Add users tab, as shown in the following screenshot: Select the user Joe Brown from the list and select OK, as shown in the following screenshot: Have a go hero – mapping roles As we just saw, the system contains a default set of pre-defined user roles that can be found in Site Manager, the Administration tab, and Roles. Spend some time studying the roles contained in the Site Manager Administration Roles and understand how they fit into your website security model. Once that is completed, put together a proposal that defines any additions or changes that may be needed. What just happened? When you clicked the New role button, you first identified the name of the role used across all system management areas. Once the role was created, you then added the user Joe Brown to the role. Time for action – adding a user to another role Users can belong to multiple roles within the system. Let's add our user Joe Brown to another role using the CMS Desk interface using these steps: Log in to CMS Desk as Global Administrator, select the Administration tab, click Users, and select the manage user roles icon ,as shown in the following screenshot: Select CMS Basic users, click the move right (>) button and select Close, as shown in the following screenshot: Select the edit user icon, as shown in the following screenshot: Select the General tab, uncheck the Is global administrator box, and select OK, as shown in the following screenshot: Why are we doing this? If Joe is a Global Administrator, he will automatically have access to all system resources. Select the Log in as this user link, as shown in the following screenshot: Select OK to change the user prompt, as shown in the following screenshot: Verify that you are logged in as the User: Joe Brown, as shown in the following screenshot:
Read more
  • 0
  • 0
  • 1008

article-image-mysql-admin-configuring-innodb-and-installing-mysql-windows-service
Packt
01 Oct 2010
3 min read
Save for later

MySQL Admin: Configuring InnoDB and Installing MySQL as a Windows Service

Packt
01 Oct 2010
3 min read
In order to prevent the transactional nature of InnoDB from completely thwarting its performance, it implements what is called the redo log. In this recipe, we will present the relevant settings to (re-)configure a database server's redo log. Getting ready As the redo log setup is a part of the server configuration, you will need an operating system user account and sufficient rights to modify the server's configuration file. You will also need rights to restart the MySQL service because the redo log cannot be reconfigured on the fly. Moreover, an administrative MySQL user account is required to prepare the server for the shutdown, necessary as part of the procedure. Caution: As this recipe will modify the configuration of parameters critical to data integrity, you should make a backup copy of the configuration file before editing it! How to do it... Connect to the server using your administrative account. Issue the following command: mysql> SET GLOBAL innodb_fast_shutdown=0;Query OK, 0 rows affected (0.00 sec) Verify the setting like this: mysql> SHOW VARIABLES LIKE 'innodb_fast_shutdown'; Log off from MySQL and stop the MySQL server. Locate the MySQL configuration file, usually called my.cnf or my.ini (on Windows) and open it in a text editor. Locate the following parameters in the [mysqld] section (you values will vary, of course): [mysqld]...innodb_log_group_home_dir=/var/lib/mysql/redologinnodb_log_file_size=32Minnodb_log_buffer_size=64Minnodb_log_files_in_group=2... Edit the above configuration settings to their new values. If you require help on how to find suitable values, see the There's more... section of this recipe. Save the configuration file. Navigate to the directory configured for innodb_log_group_home_dir. If there is no such setting in your configuration file, navigate to MySQL's data directory that is then taken as the default. Move the files whose names start with ib_logfile to a backup location. Do not copy them; they must be removed from their original location. Restart the MySQL server. Verify that new files are created as you configured them: $ ls -l /var/lib/mysqld/redolog If you do not see the new files appear and the server does not start up correctly, check the MySQL error log for messages. Usually, the only thing that can go wrong here is that you either mistyped the directory name or did not actually remove the previous ib_logfile files. To restore everything back to the original configuration, restore your configuration file from the backup and restore the ib_logfile files you moved out to the backup to their original location. What just happened... By setting innodb_fast_shutdown to 0, you told the server to finish writing any pending changes to the disk before actually exiting. This makes sure there are no remaining transactions in the current redo logs that could get lost when these files are replaced. After that you could change the configuration to new values, possibly using a different number of files and different sizes. Then, before restarting, you could move the old redo log files out of the way. This is important because otherwise MySQL would complain about a mismatch between the settings file and the actual situation on disk. When it comes up finding no redo log files, it will create new ones with the settings just configured.
Read more
  • 0
  • 0
  • 1410
article-image-advanced-aspects-inserting-and-deleting-data-mysql
Packt
01 Oct 2010
10 min read
Save for later

Advanced aspects of Inserting and Deleting data in MySQL

Packt
01 Oct 2010
10 min read
  MySQL Admin Cookbook 99 great recipes for mastering MySQL configuration and administration Set up MySQL to perform administrative tasks such as efficiently managing data and database schema, improving the performance of MySQL servers, and managing user credentials Deal with typical performance bottlenecks and lock-contention problems Restrict access sensibly and regain access to your database in case of loss of administrative user credentials Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible Read more about this book (For more resources on MySQL, see here.) Inserting new data and updating data if it already exists Manipulating data in a database is part of everyday work and the basic SQL means of INSERT, UPDATE, and DELETE make this a pretty straightforward, almost trivial task—but is this always true? When considering data manipulation, most of the time we think of a situation where we know the content of the database. With this information, it is usually pretty easy to find a way of changing the data the way you intend to. But what if you have to change data in circumstances where you do not know the actual database content beforehand? You might answer: "Well, then look at your data before changing it!" Unfortunately, you do not always have this option. Think of distributed installations of any software that includes a database. If you have to design an update option for this software (and the respective databases), you might easily come to a situation where you simply do not know about the actual database content. One example of a problem arising in these cases is the question of whether to insert or to update data: "Does the data in question already (partially) exist?" Let us assume a database table config that stores configuration settings. It holds key-value pairs, with name being the name (and thus the key) of the setting and value its value. This table exists in different database installations, one for every branch office of your company. Your task is to create an update package to set a uniform upper limit of 25% for the price discount that is allowed in your sales software. If no such limit has been defined yet, there is no respective entry in the config table, and you have to insert a new record. If the limit, however, has been set before (for example by the local manager), the entry does already exist, in which case you have to update it to hold the new value. While the update of a potentially existing entry does not pose a problem, an INSERT statement that violates uniqueness constraints will simply cause an error. This is, however, typically not acceptable in an automated update procedure. The following recipe will show you how to solve this problem with only one SQL command. Getting ready Besides a running MySQL server, a SQL client, and an account with appropriate user rights (INSERT, UPDATE), we need a table to update. In the earlier example, we assumed a table named sample.config with two character columns name and value. The name column is defined as the primary key: CREATE TABLE sample.config ( name VARCHAR(64) PRIMARY KEY, value VARCHAR(64)); How to do it... Connect to your database using your SQL client Execute the following command: mysql> INSERT INTO sample.config VALUES ("maxPriceDiscount","25%") ON DUPLICATE KEY UPDATE value='25%';Query OK, 1 row affected (0.05 sec) How it works... This command is easily explained because it simply does what it says: it inserts a new row in the table using the given values, as long as this does not cause a duplicate entry in either the primary key or another unique index. If a duplicate record exists, the existing row is updated according to the clauses defined after ON DUPLICATE KEY UPDATE. While it is sometimes tedious to enter some of the data and columns two times (once for the INSERT and a second time for the UPDATE), this statement allows for a lot of flexibility when it comes to the manipulation of potentially existing data. Please note that when executing the above statement, the result differs slightly with respect to the number of affected rows, depending on the actual data present in the database: When the record does not exist yet, it is inserted, which results in one affected row. But if the record is updated rather than inserted, it reports two affected rows instead, even if only one row gets updated. There's more... The INSERT INTO … ON DUPLICATE UPDATE construct does not work when there is no UNIQUE or PRIMARY KEY defined on the target table. If you have to provide the same semantics without having appropriate key definitions in place, it is recommended to use the techniques discussed in the next recipe. Inserting data based on existing database content In the previous recipe Inserting new data and updating data if it already exists, we discussed a method to either insert or update records depending on whether the records already exist in the database. A similar problem arises when you need to insert data to your database, but the data to insert depends on the data in your database. As an example, consider a situation in which you need to insert a record with a certain message into a table logMsgs, but the message itself should be different depending on the current system language that is stored in a configuration table (config). It is fairly easy to achieve a similar behavior for an UPDATE statement because this supports a WHERE clause that can be used to only perform an update if a certain precondition is met: UPDATE logMsgs SET message= CONCAT('Last update: ', NOW()) WHERE EXISTS (SELECT value FROM config WHERE name='lang' AND value = 'en');UPDATE logMsgs SET message= CONCAT('Letztes Update: ', NOW()) WHERE EXISTS (SELECT value FROM config WHERE name='lang' AND value = 'de');UPDATE logMsgs SET message= CONCAT('Actualisation derniere: ', NOW()) WHERE EXISTS (SELECT value FROM config WHERE name='lang' AND value = 'fr'); Unfortunately, this approach is not applicable to INSERT commands, as these do not support a WHERE clause. Despite this missing option, the following recipe describes a method to make INSERT statements execute only if an appropriate precondition in the database is met. Getting ready As before, we assume a database, a SQL client (mysql), and a MySQL user with sufficient privileges (INSERT and SELECT in this case). Additionally, we need a table to insert data into (here: logMsgs) and a configuration table config (please refer to the previous recipe for details). How to do it... Connect to your database using your SQL client. Execute the following SQL commands: mysql> INSERT INTO sample.logMsgs(message) -> SELECT CONCAT('Last update: ', NOW()) -> FROM sample.config WHERE name='lang' AND value='en';Query OK, 0 rows affected (0.00 sec)Records: 0 Duplicates: 0 Warnings: 0 How it works... Our goal is to have an INSERT statement take into account the present language stored in the database. The trick to do so is to use a SELECT statement as input for the INSERT. The SELECT command provides a WHERE clause, so you can use a condition that only matches for the respective language. One restriction of this solution is that you can only insert one record at a time, so the size of scripts might grow considerably if you have to insert lots of data and/or have to cover many alternatives. There's more... If you have more than just a few values to insert, it is more convenient to have the data in one place rather than distributed over several individual INSERT statements. In this case, it might make sense to consolidate the data by putting it inside a temporary table; the final INSERT statement uses this temporary table to select the appropriate data rows for insertion into the target table. The downside of this approach is that the user needs the CREATE TEMPORARY TABLES privilege, but it typically compensates with much cleaner scripts: After creating the temporary table with the first statement, we insert data into the table with the following INSERT statement. The next statement inserts the appropriate data into the target table sample.logMsgs by selecting the appropriate data from the temporary data that matches the language entry from the config table. The temporary table is then removed again. The final SELECT statement is solely for checking the results of the operation. Deleting all data from large tables Almost everyone who works with databases experiences the constant growth of the data stored in their database and it is typically well beyond the initial estimates. Because of that you often end up with rather large data sets. Another common observation is that in most databases, there are some tables that have a special tendency to grow especially big. If a table's size reaches a virtual threshold (which is hard to define, as it depends heavily on the access patterns and the data structures), it gets harder and harder to maintain and performance degradation might occur. From a certain point on, it is even difficult to get rid of data in the table again, as the sheer number of records makes deletion a pretty expensive task. This particularly holds true for storage engines with Multi-Version Concurrency Control (MVCC): if you order the database to delete data from the table, it must not be deleted right away because you might still roll back the deletion. So even while the deletion was initiated, a concurrent query on the table still has to be able to see all the records (depending on the transaction isolation level). To achieve this, the storage engine will only mark the records as deleted, but the actual deletion takes place after the operation is committed and all other transactions that access this table are closed as well. If you have to deal with large data sets, the most difficult task is to operate on the production system while other processes concurrently work on the data. In these circumstances, you have to keep the duration of your maintenance operations as low as possible in order to minimize the impact on the running system. As the deletion of data from a large table (typically starting at several millions of rows) might take quite some time, the following recipe shows a way of minimizing the duration of this operation in order to reduce side effects (like locking effects or performance degradation). Getting ready Besides a user account with appropriate privileges (DELETE), you need a sufficiently large table to delete data from. For this recipe, we will use the employees database, which is an example database available from MySQL: http://dev.mysql.com/doc/employee/en/employee.html This database provides some tables with sensible data and some pretty large tables, the largest having more than 2.8 million records. We assume that the Employees database was installed with an InnoDB storage engine enabled. To delete all rows of the largest table employees.salaries in a quick way, please read on. How to do it...
Read more
  • 0
  • 0
  • 3856

article-image-running-multiple-mysql-server-instances-parallel-linux-server
Packt
01 Oct 2010
5 min read
Save for later

Running Multiple MySQL Server Instances in Parallel on a Linux Server

Packt
01 Oct 2010
5 min read
  MySQL Admin Cookbook 99 great recipes for mastering MySQL configuration and administration Set up MySQL to perform administrative tasks such as efficiently managing data and database schema, improving the performance of MySQL servers, and managing user credentials Deal with typical performance bottlenecks and lock-contention problems Restrict access sensibly and regain access to your database in case of loss of administrative user credentials Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible Read more about this book (For more resources on MySQL, see here.) Introduction On most Linux setups, MySQL comes as a readymade installation package, making it easy to get started. It is, however, a little more complicated to run multiple instances in parallel, often a setup handy for development. This is because in contrast to Windows, MySQL is usually not installed in a self-contained directory, but most Linux distribution packages spread it across the appropriate system folders for programs, configuration files, and so on. You can, however, also install MySQL in its own directory, for example, if you need to use a version not available as a prepared package for your Linux distribution. While this gives you the greatest flexibility, as a downside you will have to take care of wiring up your MySQL server with the operating system manually. For example, you will need to hook up the startup and shutdown scripts with the appropriate facilities of your distribution. In more recent distributions, you can make use of a tool called mysqld_multi, a solution that lets you set up multiple instances of MySQL daemons with varying configurations. In this recipe, we will show you how to set up two parallel MySQL servers, listening on different TCP ports and using separate data directories for their respective databases. Getting ready This recipe is based on an Ubuntu Linux machine with the 8.04 LTS version. mysqld_multi comes with the MySQL packages for that operating system. If you are using other distributions, you need to make sure you have mysqld_multi installed to be able to follow along. Refer to your distribution's package repositories for information on which packages you need to install. You will also need an operating system user with sufficient privileges to edit the MySQL configuration file—typically /etc/mysql/my.cnf on Ubuntu—and restart services. As for AppArmor or SELinux, we assume these have been disabled before you start to simplify the process. How to do it... Locate and open the my.cnf configuration file in a text editor. Create the following two sections in the file: # mysqld_multi test, instance 1[mysqld1]server-id=10001socket=/var/run/mysqld/mysqld1.sockport=23306pid-file=/var/run/mysqld/mysqld1.piddatadir=/var/lib/mysql1log_bin=/var/log/mysql1/mysql1-bin.log# mysqld_multi test, instance 2[mysqld2]server-id=10002socket=/var/run/mysqld/mysqld2.sockport=33306pid-file=/var/run/mysqld/mysqld2.piddatadir=/var/lib/mysql2log_bin=/var/log/mysql2/mysql2-bin.log Save the configuration file. Issue the following command to verify the two sections are found by mysqld_multi: $ sudo mysqld_multi report Initialize the data directories: $ sudo mysql_install_db --user=mysql --datadir=/var/lib/mysql1$ sudo mysql_install_db --user=mysql --datadir=/var/lib/mysql2 Start both instances and verify they have been started: $ sudo mysqld_multi start 1$ sudo mysqld_multi report Connect to both instances and verify their settings: $ mysql -S /var/run/mysqld/mysql1.sockmysql> SHOW VARIABLES LIKE 'server_id'; How it works... mysqld_multi uses a single configuration file for all MySQL server instances, but inside that file each instance has its individual [mysqld] section with its specific options. mysqld_multi then takes care of launching the MySQL executable with the correct options to use the options from its corresponding section. The sections are distinguished by a positive number directly appended to the word mysqld in the section header. You can specify all the usual MySQL configuration file options in these sections, just as you would for a single instance. Make sure, however, to specify the minimum set of options as in the recipe steps previously stated, as these are required to be unique for every single instance. There's more... Some special preparation might be needed, depending on the particular operating system you are using. Turning off AppArmor / SELinux for Linux distributions If your system uses the AppArmor or SELinux security features, you will need to make sure these are either turned off while you try this out, or configured (for permanent use once your configuration has been finished) to allow access to the newly defined directories and files. See the documentation for your respective Linux distribution for more details on how to do this. Windows On Windows, running multiple server instances is usually more straightforward. MySQL is normally installed in a separate, self-contained folder. To run two or more independent server instances, you only need to install a Windows service for each of them and point them to an individual configuration file. Considering the alternative MySQL Sandbox project As an alternative to mysqld_multi you might want to have a look at MySQL Sandbox, which offers a different approach to hosting multiple independent MySQL installations on a single operating system. While mysqld_multi manages multiple configurations in a single file, MySQL Sandbox aims at completely separating MySQL installations from each other, easily allowing even several MySQL releases to run side by side. For more details, visit the project's website at http://mysqlsandbox.net Preventing invalid date values from being stored in DATE or DATETIME columns In this recipe, we will show you how to configure MySQL in a way such that invalid dates are rejected when a client attempts to store them in a DATE or DATETIME column using a combination of flags for the SQL mode setting. See the There's more... section of this recipe for some more detailed information on the server mode setting in general and on how to use it on a per-session basis. Getting ready
Read more
  • 0
  • 0
  • 6195