Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7018 Articles
article-image-microsoft-sharepoint-2010-administration-farm-governance
Packt
19 Jan 2011
5 min read
Save for later

Microsoft SharePoint 2010 Administration: Farm Governance

Packt
19 Jan 2011
5 min read
  Microsoft SharePoint 2010 Administration Cookbook Over 90 simple but incredibly effective recipes to administer your SharePoint applications Solutions to the most common problems encountered while administering SharePoint in book and eBook formats Upgrade, configure, secure, and back up your SharePoint applications with ease Packed with many recipes for improving collaboration and content management with SharePoint Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible An administrator's job is akin to being the Marines. They are the first ones to be called when there is an issue with SharePoint. Nothing gets done without their knowledge. Typically, the administrator has to decide who to bring in when an issue needs to be addressed. Additionally, administrators deal with management, end users, developers, and the power users. The recipes in this article teach and expose useful and common functionality found in SharePoint 2010. The intent of the recipes is to create a SharePoint Farm environment that is efficient and monitored. For example, large lists have always been an issue in SharePoint in the past, with little or no support to address it out of the box. This is directly related to the performance of your SharePoint installation. This article has a recipe on a new functionality, throttling large lists. PowerShell is a critical tool for the SharePoint Administrator. While the recipes may only show how to use the commands at a granular level, they may be combined to create powerful administrator scripts. As a result, many of the tasks that are performed today can be automated and collected at a macro level. After reading this chapter, think about how these techniques can be combined. Administering SharePoint Designer SharePoint Designer 2010 is a powerful tool that helps create rapid solutions using SharePoint. As the tool is free, any user can download and access its functionality. By connecting to a SharePoint site, users can freely make significant changes to the site. This includes the look and feel of the site, workflow, and connecting to external sources. The issue with this amount of power is the havoc that can be done by creating customizations that inadvertently tax the SharePoint Server(s). The end result may be a degradation of the responsiveness of the SharePoint farm, adversely affecting the performance of the site. Let's look at the preceding paragraph in terms of a real workflow as an example. Workflows are very popular and can be done out of the box with SharePoint Designer. Zach's trucking company hauls product all over the country. They get their work responding to a Request for Quotation. They can get up to ten RFQs per day. The requirement is that when an RFQ document gets uploaded, several tasks are created in a separate list for multiple people. Using the task list, they can determine when the document is ready to be sent out. The workflow can be created in SharePoint Designer (SPD) out of the box. If the person using SharePoint Designer is not well-versed in creating workflows, it is possible that he/she might create long running tasks and infinite loops. Over time, the farm performance will degrade. This is because at the heart of SharePoint, every call made goes back to the SQL database. An infinite loop could cause a list to become quite large. A different issue has to do with usability and standards. As users with proper permissions can modify look and feel of individual sites, they can deviate from corporate standards. Multiply this capability with the number of users in your organization, and you will realize there is a very real issue with governance of sites in general. SharePoint 2010 has a solution for these problems that can either limit a user's capability in their site or take it away completely. This recipe shows you how and where to do this within SharePoint. Getting ready You must have farm level administrative permissions to the Central Administration site. How to do it... Open up the SharePoint 2010 Central Administration website. Click Application Management. Under the Web Applications section, click Manage Web Applications. The available web applications will be listed. Click to the right of the web application you wish to manage. The entire line will turn blue and the ribbon will light up. If you have installed SharePoint into the default instance, it may look like the following screenshot: On the ribbon, there is a button called General Settings. Click on that button and select the SharePoint Designer option from the drop-down list that appears. The following screenshot appears: Fill in the required information: Allow SharePoint Designer to be used in this Web Application: Unchecking this box will disable SPD for the entire web application. Allow Site Collection Administrators to Detach Pages from the Site Template: Once this option is unchecked, Site Administrators will not be able to detach pages and modify them via SPD. Allow Site Collection Administrators to Customize Master Pages and Layout Pages: If it is unchecked, Site Administrators will not be able to customize pages via SPD. Allow Site Collection Administrators to see the URL Structure of their Web Site: If unchecked, it will not allow Site Collection Administrators to manage the URL structure via SPD. How it works... SharePoint Designer is a client application that is installed on the user's desktop. This recipe shows how to disable SPD from working at a web application level. There's more... The Site Collection Administrator can also modify the way SharePoint Designer works. To accomplish this: Open up the Site Collection screen and click Site Settings. In the section under Site Collection Administration, there is an entry call SharePoint Designer Settings; select that. The following form appears: The sections are self-explanatory. If the Farm Administrator limits SPD access at the Central Administration level (as shown earlier in the recipe), the changes are reflected in red color on the form, with a message as seen in the following screenshot:
Read more
  • 0
  • 0
  • 1686

article-image-introduction-database-mirroring-microsoft-sql-server-2008-high-availability
Packt
19 Jan 2011
5 min read
Save for later

Introduction to Database Mirroring in Microsoft SQL Server 2008 High Availability

Packt
19 Jan 2011
5 min read
Microsoft SQL Server 2008 High Availability Minimize downtime, speed up recovery, and achieve the highest level of availability and reliability for SQL server applications by mastering the concepts of database mirroring,log shipping,clustering, and replication  Install various SQL Server High Availability options in a step-by-step manner  A guide to SQL Server High Availability for DBA aspirants, proficient developers and system administrators  Learn the pre and post installation concepts and common issues you come across while working on SQL Server High Availability  Tips to enhance performance with SQL Server High Availability  External references for further study Introduction Mr. Young, who is the Principal DBA in XY Incorporation, a large manufacturing company, was asked to come up with a solution that could serve his company's needs to make a database server highly available, without a manual or minimal human intervention. He was also asked to keep in mind the limited budget the company has for the financial year. After careful research, he has come up with an idea to go with Database Mirroring as it provides an option of Automatic Failover—a cost effective solution. He has prepared a technical document for the management and peers, in order to make them understand how it works, based on tests he performed on virtual test servers. What is Database Mirroring Database Mirroring is an option that can be used to cater to the business need, in order to increase the availability of SQL Server database as standby, for it to be used as an alternate production server in the case of any emergency. As its name suggests, mirroring stands for making an exact copy of the data. Mirroring can be done onto a disk, website, or somewhere else. Similarly, Microsoft has introduced Database Mirroring with the launch of SQL Server 2005 post SP1, which performs the same function—making an exact copy of the database between two physically separate database servers. As Mirroring is a database-wide feature, it can be implemented per database instead of implementing it server wide. Disk Mirroring is a technology wherein data is stored on physically separate but identical hard disks at the same time called hardware array disk 1 or RAID 1. Different components of the Database Mirroring To install Database Mirroring, there are three components that are required. They are as follows: Principal Server: This is the database server that will send out the data to the participant server (we'll call it secondary/standby server) in the form of transactions. Secondary Server: This is the database server that receives all the transactions that are sent by the Principal Server in order to keep the database identical. Witness Server (optional): This server will continuously monitor the Principal and Secondary Server and will enable automatic failover. This is an optional server. To have the automatic failover feature, the Principal Server should be in the synchronous mode. How Database Mirroring works In Database Mirroring, every server is a known partner and they complement each other as Principal and Mirror. There will be only one Principal and only one Mirror at any given time. In reality, DML operations that are performed on the Principal Server are all re-performed at the Mirror server. As we all know, the data is written into the Log Buffer before it is written into data pages. Database Mirroring sends data that is written into Principal Server's Log Buffer simultaneously to the Mirror database. All these transactions are sent in a sequential manner and as quickly as possible. There are two different operating modes at which Database Mirroring operates—asynchronous and synchronous. Asynchronous a.k.a. High Performance mode The transactions are sent to the Secondary Server as soon as they are written into the Log Buffer. In this mode of operation, the data is first committed at the Principal Server before it actually is written into the Log Buffer of the Secondary Server. Hence this mode is called High Performance mode, but at the same time, it introduces a chance of data loss. Synchronous a.k.a. High Safety mode The transactions are sent to the Secondary Server as soon as they are written to the Log Buffer. These transactions are then committed simultaneously at both the ends. Prerequisites Let's now have a look at the prerequisite to have Database Mirroring in place. Please be cautious with the prerequisites, as a single missed requisite would result in a failure in installation. Recovery Mode: To implement Database Mirroring, the database should be in the Full Recovery mode. Initialization of database: The database on which to install Database Mirroring should be present in the mirror database. To achieve this, we can restore the most recent backup, followed by the transaction log with the NORECOVERY option. Database name: Ensure that the database name is the same for both, the principal as well as the mirror database. Compatibility: Ensure that the partner servers are on the same edition of the SQL Server. Database Mirroring is supported by the Standard and Enterprise edition. Synchronous mode with Automatic failover is an Enterprise-only feature. Disk space: Ensure that we have ample space available for the mirror database. Service accounts: Ensure that the service accounts that we have used are domain accounts and they have the required permission, that is, CONNECT permission to the endpoints. Listener port: These are TCP ports on which a Database Mirroring session is established between the Principal and Mirror server. Endpoints: These are the objects that are dedicated to Database Mirroring and enable the SQL Server to communicate over the network. Authentication: While both the Principal and Mirror servers talk to each other, they should authenticate each other. For this, the accounts that we use—local accounts or domain accounts—should have login and send message permissions. If the accounts we use are using local logins as service accounts, we must use Certificates to authenticate a connection request.
Read more
  • 0
  • 0
  • 3126

article-image-getting-started-audacity
Packt
19 Jan 2011
9 min read
Save for later

Getting started with Audacity

Packt
19 Jan 2011
9 min read
What is Audacity? With the evolution of the Internet there has been a huge boom in personal websites, blogs, photo and music sharing sites, and things called podcasts. Podcasts are simple recordings of interviews, personal recollections, or entire skits, including entire entertainment "acts" that include background music and sound effects. What this change in the Internet culture has offered to the everyday person is the ability to jump into the world of audio recording. Audacity was created with this very basic need in mind. Audacity is a simple audio editor and recorder. It can record live audio, help to convert tapes and records into digital recordings, and edit and mix a number of sound files together. What this means for you, is that you can use it to: Create audiocasts or podcasts that can be uploaded to the Web and shared with others. Podcasts can be interviews with interesting people, simple narrations, or cute snippets of your children talking. Record live events such as lectures and presentations. Of course, you need to have a laptop to bring along with you. Move your old records and cassettes into the digital age and convert them to an MP3 digital audio file. With additional equipment (a cassette or record player with a line-out plug and cable), you can connect this equipment to your computer and use Audacity to make versions of your music that you can play on a digital music player like an iPod. Edit most digital audio files, such as podcasts, to add in music, delete segments, remove unwanted noise, add in some audio effects. Audacity lets you work with audio files to make them better. Record audio from YouTube. Have you ever wanted only the audio portion of a YouTube video? Well, now you can play the video directly from YouTube, but "strip" only the audio portion out for your own use. Create a ringtone for your cell phone. Audacity lets you convert between audio formats. It supports Ogg Vorbis, MP3, WAV, and AIFF formats, and can convert between them. It's also a great tool if you want to e-mail someone a simple audio message. Just plug in your headset, hit record, and start talking. You can have a personalized voice message that can be sent through e-mail! Will it work for me? Audacity was developed by a group of volunteers under the GNU General Public License (GPL), and is open source, or free software. This not only means that it does not cost anything to download, but also that you can use the program, create items with it, and freely distribute these items, modify the program itself, and share your work with others. You can download Audacity for: Mac OS X Microsoft Windows GNU/Linux Other operating systems Let's briefly go over how to download and install Audacity. Windows and Mac OS The installation process for both of these operating systems is similar: Go to the official Audacity website at http://audacity.sourceforge.net/ and download the appropriate version of the software for your computer. Once the installation package has been downloaded to your computer, double-click on it to start the installation. For Mac computers, a DMG file is downloaded. All you need to do is uncompress that file, and drag-and-drop the Audacity package to the Application folder. For any Windows device, an EXE file is downloaded. Double-click on that file to perform the installation. Find the Audacity icon (shown in the next image) in the Application or Programs folder, to open the program. GNU/Linux You can use Audacity with GNU/Linux operating systems (and other similar operating systems), but you should download the correct installation package for it. Currently, there are a number of distributions available for the following types of systems: Alt Linux Debian Fedora Core Fedora Project Mandriva i586 OpenSUSE Red Hat SuSe and packman (suse) Ubuntu (http://packages.ubuntu.com/ and http://www.rpmseek.com/) You can download the installation packages for these and others from the Audacity Linux or Unix web page, at http://audacity.sourceforge.net/download/. In this article, the screenshots are specific to the Mac OS X software. However, don't be concerned if this is not your computer operating system of choice. The software itself is very similar between operating systems, and any notable differences between the Audacity software screens for different operating systems, are noted, so you know what to look for. In the interest of saving you some time, there are some things that Audacity can't do in comparison to more specialized audio editing software. Audacity: Can't play or record files in the MIDI audio file format. Doesn't natively play or export audio in propriety or restricted file audio formats, such as WMA or AAC. Additional plug-ins must be installed to do this. Has less plug-ins and effects than a specialized Digital Audio Workstation (DAW). Can't apply sound effects in realtime. This means that you have to record the track and then apply sound effects to the track. Isn't a specialized audio editing software package, so there are some limitations on multi-track editing and mixing features. Moving up to Audacity 1.3 Audacity 1.3 offers a lot more than its predecessor, 1.2. It has some new features, which include faster equalization and noise removal tools, a new "mixer board" view with per-track volume meters, and a fullscreen view, and in addition, some basic audio information (mute, solo, gain, and track height) is now saved when you save a project. Common audio editing terms used in Audacity As with any new tool, there is often some terminology that comes along with understanding how it works. For Audacity, there are audio recording and editing terms that will come in handy when learning how to use the software. Some basic terms are: Project—when you open Audacity, you will open or create a new project. This includes all of the files, timing, and information on how you combined and edited different pieces of audio into your file or project. This term isn't specific to audio editing, but to software that combines pieces of different files into a single file in order to create a final output. Clip—is a short segment of audio. It can be combined with others to make an audio track. Track—one continuous audio element. Library—a collection of audio files or tracks. These can be grouped according to the content of the audio files (like a music library) or just by the location of where they are stored. Effect—there are two types of effects: generator and processing. Generator effects artificially create sounds using your audio track (or add it in). Processing effects work with the existing audio and edit or change it for a desired result. Noise—is sound of any kind, especially unintelligible or dissonant sound, that interferes with the main audio that you want heard in a track. Or simply put, it is any sound that you don't want in the audio track. Bit or Sample Rates—the number of computer bits that are conveyed or processed per unit of time. This is normally expressed in kilobits per second (kbps). A higher bit or sample rate means that your track was recorded in better quality. Export—the process of saving the audio in another format other than the format of the program that you created it in, usually so that you can play it or use it on another device or computer program. Typically, for audio, you will export files in a WAV or MP3 format. WAV, AIFF, MP3—these are all audio file types. This means that when you export an audio track from Audacity, it can be any of these formats, or you can simply do a Save As, to save it in the Audacity format of AUP. However, then only Audacity will be able to open the AUP file to listen to its contents. As we start using Audacity and create a project, more terms will be added and explained as we move through each step. We'll be sure to call out any new terms so you can add them to your memory banks. Opening Audacity No matter what operating system you use on your computer, all you need to do is find the Audacity program and open it, just as you would with any other software on your computer. The Audacity main window opens with an empty project window. This will look something like the next screenshot: Don't be overwhelmed by this screen. Sure, there are a lot of icons and terms that might not be familiar, but we're going to review each element and how it is used. And as we begin our own sample recording session, we'll again review the icons and their use. There are three main areas on this screen, as discussed in the following sections. Audio controls and editing toolbars The top portion, which includes audio controls and the many editing toolbars. These are the buttons and tools that you will use to edit and manipulate your recorded audio tracks. Project View The middle portion of the screen is the project view. This area will look very different when a project is open, as the timeline won't be empty. In this case it will show a digital representation of the audio that you recorded, along with some more settings that you can adjust. Selection Toolbar Just below the project view is the settings tool bar, which displays the frequency and bit rate information, and more timeline information, which we will cover as we start working on our sample project. But let's first discuss the main menu, and each of the toolbars on the screen. Using the main menu The main menu bar contains basic functionality for Audacity. You can open and save projects, add or hide toolbars in the main window, set preferences, as well as open the program Help file. This menu bar gives access to the entire program, even if you don't have all of the toolbars viewable. The main menu appears a bit differently when using different operating systems. When using Audacity on the Windows or Linux operating systems, the main menu is seen on top of the program window. With the Macintosh operating system, it is along the top bar of the computer screen. When we begin our sample project, you'll see the most common uses of this main menu—for opening and saving Audacity project files.
Read more
  • 0
  • 0
  • 11214

article-image-communicating-server-using-google-web-toolkit-rpc
Packt
19 Jan 2011
5 min read
Save for later

Communicating with Server using Google Web Toolkit RPC

Packt
19 Jan 2011
5 min read
  Google Web Toolkit 2 Application Development Cookbook Over 70 simple but incredibly effective practical recipes to develop web applications using GWT with JPA , MySQL and i Report Create impressive, complex browser-based web applications with GWT 2 Learn the most effective ways to create reports with parameters, variables, and subreports using iReport Create Swing-like web-based GUIs using the Ext GWT class library Develop applications using browser quirks, Javascript,HTML scriplets from scratch Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible  The Graphical User Interface (GUI) resides in the client side of the application. This article introduces the communication between the server and the client, where the client (GUI) will send a request to the server, and the server will respond accordingly. In GWT, the interaction between the server and the client is made through the RPC mechanism. RPC stands for Remote Procedure Call. The concept is that there are some methods in the server side, which are called by the client at a remote location. The client calls the methods by passing the necessary arguments, and the server processes them, and then returns back the result to the client. GWT RPC allows the server and the client to pass Java objects back and forth. RPC has the following steps: Defining the GWTService interface: Not all the methods of the server are called by the client. The methods which are called remotely by the client are defined in an interface, which is called GWTService. Defining the GWTServiceAsync interface: Based on the GWTService interface, another interface is defined, which is actually an asynchronous version of the GWTService interface. By calling the asynchronous method, the caller (the client) is not blocked until the method completes the operation. Implementing the GWTService interface: A class is created where the abstract method of the GWTService interface is overridden. Calling the methods: The client calls the remote method to get the server response. Creating DTO classes In this application, the server and the client will pass Java objects back and forth for the operation. For example, the BranchForm will request the server to persist a Branch object, where the Branch object is created and passed to server by the client, and the server persists the object in the server database. In another example, the client will pass the Branch ID (as an int), the server will find the particular Branch information, and then send the Branch object to the client to be displayed in the branch form. So, both the server and client need to send or receive Java objects. We have already created the JPA entity classes and the JPA controller classes to manage the entity using the Entity Manager. But the JPA class objects are not transferable over the network using the RPC. JPA classes will just be used by the server on the server side. For the client side (to send and receive objects), DTO classes are used. DTO stands for Data Transfer Object. DTO is simply a transfer object which encapsulates the business data and transfers it across the network. Getting ready Create a package com.packtpub.client.dto, and create all the DTO classes in this package. How to do it... The steps required to complete the task are as follows: Create a class BranchDTO that implements the Serializable interface: public class BranchDTO implements Serializable Declare the attributes. You can copy the attribute declaration from the entity classes. But in this case, do not include the annotations: private Integer branchId; private String name; private String location Define the constructors, as shown in the following code: public BranchDTO(Integer branchId, String name, String location) { this.branchId = branchId; this.name = name; this.location = location; } public BranchDTO(Integer branchId, String name) { this.branchId = branchId; this.name = name; } public BranchDTO(Integer branchId) { this.branchId = branchId; } public BranchDTO() { } To generate the constructors automatically in NetBeans, right-click on the code, select Insert Code | Constructor, and then click on Generate after selecting the attribute(s). Define the getter and setter: public Integer getBranchId() { return branchId; } public void setBranchId(Integer branchId) { this.branchId = branchId; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } To generate the setter and getter automatically in NetBeans, right-click on the code, select Insert Code | Getter and Setter…, and then click on Generate after selecting the attribute(s). Mapping entity classes and DTOs In RPC, the client will send and receive DTOs, but the server needs pure JPA objects to be used by the Entity Manager. That's why, we need to transform from DTO to JPA entity class and vice versa. In this recipe, we will learn how to map the entity class and DTO. Getting ready Create the entity and DTO classes. How to do it... Open the Branch entity class and define a constructor with a parameter of type BranchDTO. The constructor gets the properties from the DTO and sets them in its own properties: public Branch(BranchDTO branchDTO) { setBranchId(branchDTO.getBranchId()); setName(branchDTO.getName()); setLocation(branchDTO.getLocation()); } This constructor will be used to create the Branch entity class object from the BranchDTO object. In the same way, the BranchDTO object is constructed from the entity class object, but in this case, the constructor is not defined. Instead, it is done where it is required to construct DTO from the entity class. There's more... Some third-party libraries are available for automatically mapping entity class and DTO, such as Dozer and Gilead. For details, you may visit http://dozer.sourceforge.net/ and http://noon.gilead.free.fr/gilead/. Creating the GWT RPC Service In this recipe, we are going to create the GWTService interface, which will contain an abstract method to add a Branch object to the database. Getting ready Create the Branch entity class and the DTO class.  
Read more
  • 0
  • 0
  • 2198

article-image-working-entities-google-web-toolkit-2
Packt
19 Jan 2011
9 min read
Save for later

Working with Entities in Google Web Toolkit 2

Packt
19 Jan 2011
9 min read
  Google Web Toolkit 2 Application Development Cookbook Over 70 simple but incredibly effective practical recipes to develop web applications using GWT with JPA , MySQL and i Report Create impressive, complex browser-based web applications with GWT 2 Learn the most effective ways to create reports with parameters, variables, and subreports using iReport Create Swing-like web-based GUIs using the Ext GWT class library Develop applications using browser quirks, Javascript,HTML scriplets from scratch 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 GWT, see here.) Finding an entity In this recipe, we are going to write the code to find an entity. From the client side, the ID of the entity will be passed to the server; the server will find the entity in the database using the JPA controller class, and then return the entity to the client in order to display it. How to do it... Declare the following method in the GWTService interface: public BranchDTO findBranch(int branchId); Declare the asynchronous version of the above method in GWTServiceAsync interface public void findBranch(int branchId, AsyncCallback<BranchDTO> asyncCallback); Implement this method in GWTServiceImpl class @Override public BranchDTO findBranch(int branchId) { Branch branch=branchJpaController.findBranch(branchId); BranchDTO branchDTO=null; if(branch!=null) { branchDTO=new BranchDTO(); branchDTO.setBranchId(branch.getBranchId()); branchDTO.setName(branch.getName()); branchDTO.setLocation(branch.getLocation()); } return branchDTO; } Create a callback instance in client side (BranchForm in this case) to call this method as shown in the following code: final AsyncCallback<BranchDTO> callbackFind = new AsyncCallback<BranchDTO>() { @Override public void onFailure(Throwable caught) { MessageBox messageBox = new MessageBox(); messageBox.setMessage("An error occured! Cannot complete the operation"); messageBox.show(); clear(); } @Override public void onSuccess(BranchDTO result) { branchDTO=result; if(result!=null) { branchIdField.setValue(""+branchDTO.getBranchId()); nameField.setValue(branchDTO.getName()); locationField.setValue(branchDTO.getLocation()); } else { MessageBox messageBox = new MessageBox(); messageBox.setMessage("No such Branch found"); messageBox.show(); clear(); } } }; Write the event-handling code for the find button as follows: findButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { MessageBox inputBox = MessageBox.prompt("Input", "Enter the Branch ID"); inputBox.addCallback(new Listener<MessageBoxEvent>() { public void handleEvent(MessageBoxEvent be) { int branchId = Integer.parseInt(be.getValue()); ((GWTServiceAsync)GWT.create(GWTService.class)). findBranch(branchId,callbackFind); } }); } }); How it works... Here, the steps for calling the RPC method are the same as we had done for the add/save operation. The only difference is the type of the result we have received from the server. We have passed the int branch ID and have received the complete BrachDTO object, from which the values are shown in the branch form. Updating an entity In this recipe, we are going to write the code to update an entity. The client will transfer the DTO of updated object, and the server will update the entity in the database using the JPA controller class. How to do it... Declare the following method in the GWTService interface: public boolean updateBranch(BranchDTO branchDTO); Declare the asynchronous version of this method in the GWTServiceAsync interface: public void updateBranch(BranchDTO branchDTO, AsyncCallback<java.lang.Boolean> asyncCallback); Implement the method in the GWTServiceImpl class: @Override public boolean updateBranch(BranchDTO branchDTO) { boolean updated=false; try { branchJpaController.edit(new Branch(branchDTO)); updated=true; } catch (IllegalOrphanException ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } catch (NonexistentEntityException ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } return updated; } Create a callback instance for this method in the client side (BranchForm in this case, if it is not created yet): final AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { MessageBox messageBox = new MessageBox(); @Override public void onFailure(Throwable caught) { messageBox.setMessage("An error occured! Cannot complete the operation"); messageBox.show(); } @Override public void onSuccess(Boolean result) { if (result) { messageBox.setMessage("Operation completed successfully"); } else { messageBox.setMessage("An error occured! Cannot complete the operation"); } messageBox.show(); } }; Write the event handle code for the update button: updateButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { branchDTO.setName(nameField.getValue()); branchDTO.setLocation(locationField.getValue()); ((GWTServiceAsync)GWT.create(GWTService.class)). updateBranch(branchDTO,callback); clear(); } }); How it works... This operation is also almost the same as the add operation shown previously. The difference here is the method of controller class. The method edit of the controller class is used to update an entity. Deleting an entity In this recipe, we are going to write the code to delete an entity. The client will transfer the ID of the object, and the server will delete the entity from the database using the JPA controller class. How to do it... Declare the following method in the GWTService interface public boolean deleteBranch(int branchId); Declare the asynchronous version of this method in GWTServiceAsync interface public void deleteBranch(int branchId, AsyncCallback<java.lang.Boolean> asyncCallback); Implement the method in GWTServiceImpl class @Override public boolean deleteBranch(int branchId) { boolean deleted=false; try { branchJpaController.destroy(branchId); deleted=true; } catch (IllegalOrphanException ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } catch (NonexistentEntityException ex) { Logger.getLogger(GWTServiceImpl.class.getName()). log(Level.SEVERE, null, ex); } return deleted; } Create a callback instance for this method in the client side (BranchForm in this case, if it is not created yet): final AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { MessageBox messageBox = new MessageBox(); @Override public void onFailure(Throwable caught) { messageBox.setMessage("An error occured! Cannot complete the operation"); messageBox.show(); } @Override public void onSuccess(Boolean result) { if (result) { messageBox.setMessage("Operation completed successfully"); } else { messageBox.setMessage("An error occured! Cannot complete the operation"); } messageBox.show(); } }; Write the event handling code for the delete button: deleteButton.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { ((GWTServiceAsync)GWT.create(GWTService.class)). deleteBranch(branchDTO.getBranchId(),callback); clear(); } }); Managing a list for RPC Sometimes, we need to transfer a list of objects as java.util.List (or a collection) back and forth between the server and the client. We already know from the preceding recipes that the JPA entity class objects are not transferable directly using RPC. Because of the same reason, any list of the JPA entity class is not transferable directly. To transfer java.util.List using RPC, the list must contain objects from DTO classes only. In this recipe, we will see how we can manage a list for RPC. In our scenario, we can consider two classes—Customer and Sales. The association between these two classes is that one customer makes zero or more sales and one sale is made by one customer. Because of such an association, the customer class contains a list of sales, and the sales class contains a single instance of customer class. For example, we want to transfer the full customer object with the list of sales made by this customer. Let's see how we can make that possible. How to do it... Create DTO classes for Customer and Sales (CustomerDTO and SalesDTO, respectively). In the following table, the required changes in data types are shown for the entity and DTO class attributes. The list in the DTO class contains objects of only the DTO class; on the other hand, the list of the entity class contains objects of entity class. Define the following constructor in the Customer entity class: public Customer(CustomerDTO customerDTO) { setCustomerNo(customerDTO.getCustomerNo()); setName(customerDTO.getName()); setAddress(customerDTO.getAddress()); setContactNo(customerDTO.getContactNo()); List<SalesDTO> salesDTOList=customerDTO.getSalesList(); salesList = new ArrayList<Sales>(); for(int i=0;i<salesDTOList.size();i++) { SalesDTO salesDTO=salesDTOList.get(i); Sales sales=new Sales(salesDTO); salesList.add(sales); } } Define the following constructor in the Sales entity class: public Sales(SalesDTO salesDTO) { setSalesNo(salesDTO.getSalesNo()); setSalesDate(salesDTO.getSalesDate()); setCustomer(new Customer(salesDTO.getCustomer())); // there's more but not relevant for this recipe } How it works... Now in the server side, the entity classes, Customer and Sales, will be used, and in the client side, CustomerDTO and SalesDTO, will be used. Constructors with DTO class type argument are defined for the mapping between entity class and DTO class. But here, the addition is the loop used for creating the list. From the CustomerDTO class, we get a list of SalesDTO. The loop gets one SalesDTO from the list, converts it to Sales, and adds it in the Sales list—that's all. Authenticating a user through username and password In this recipe, we are going to create the necessary methods to authenticate a user through a login process. Getting ready Create the DTO class for the entity class Users. How to do it... Declare the following method in the GWTService interface: public UsersDTO login(String username,String password); Declare the following method in the GWTServiceAsync interface: public void login(String username, String password, AsyncCallback<UsersDTO> asyncCallback); Implement the method in the GWTServiceImpl class: @Override public UsersDTO login(String username, String password) { UsersDTO userDTO = null; UsersJpaController usersJpaController = new UsersJpaController(); Users user = (Users) usersJpaController.findUsers(username); if (user != null) { if (user.getPassword().equals(password)) { userDTO=new UsersDTO(); userDTO.setUserName(user.getUserName()); userDTO.setPassword(user.getPassword()); EmployeeDTO employeeDTO= new EmployeeDTO(user.getEmployee().getEmployeeId()); employeeDTO.setName(user.getEmployee().getName()); userDTO.setEmployeeDTO(employeeDTO); } } return userDTO; } How it works... A username and password are passed to the method. An object of the UsersJpaController class is created to find the Users object based on the given username. If the find method returns null, it means that no such user exists. Otherwise, the password of the Users object is compared with the given password. If both the passwords match, a UsersDTO object is constructed and returned. The client will call this method during the login process. If the client gets null, the client should handle it accordingly, as the username/password is not correct. If it is not null, the user is authenticated. Summary In this article we how we can manage entities in GWT RPC. Specifically, we covered the following: Finding an entity Updating an entity Deleting an entity Managing a list for RPC Authenticating a user through username and password Further resources on this subject: Google Web Toolkit 2: Creating Page Layout [Article] Communicating with Server using Google Web Toolkit RPC [Article] Password Strength Checker in Google Web Toolkit and AJAX [Article] Google Web Toolkit GWT Java AJAX Programming [Book] Google Web Toolkit 2 Application Development Cookbook [Book]
Read more
  • 0
  • 0
  • 1731

article-image-article-exclusive-offer-all-enterprise-ebooks
Packt
19 Jan 2011
1 min read
Save for later

Enterprise eBook Offer

Packt
19 Jan 2011
1 min read
    Popular eBook Bundles Customers are Buying Right Now You can buy ANY 4 Enterprise eBooks with this offer, but here are some popular bundles people are buying right now:
Read more
  • 0
  • 0
  • 597
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-getting-started-alfresco-records-management-module
Packt
18 Jan 2011
7 min read
Save for later

Getting Started with the Alfresco Records Management Module

Packt
18 Jan 2011
7 min read
  Alfresco 3 Records Management Comply with regulations and secure your organization’s records with Alfresco Records Management. Successfully implement your records program using Alfresco Records Management, fully certified for DoD-5015.2 compliance The first and only book to focus exclusively on Alfresco Records Management Step-by-step instructions describe how to identify records, organize records, and manage records to comply with regulatory requirements Learn in detail about the software internals to get a jump-start on performing customizations Appendix     The Alfresco stack Alfresco software was designed for enterprise, and as such, supports a variety of different stack elements. Supported Alfresco stack elements include some of the most widely used operating systems, relational databases, and application servers. The core infrastructure of Alfresco is built on Java. This core provides the flexibility for the server to run on a variety of operating systems, like Microsoft Windows, Linux, Mac OS, and Sun Solaris. The use of Hibernate allows Alfresco to map objects and data from Java into almost any relational database. The databases that the Enterprise version of Alfresco software is certified to work with include Oracle, Microsoft SQL Server, MySQL, PostgresSQL, and DB2. Alfresco also runs on a variety of Application Servers that include Tomcat, JBoss, WebLogic, and WebSphere. Other relational databases and application servers may work as well, although they have not been explicitly tested and are also not supported. Details of which Alfresco stack elements are supported can be found on the Alfresco website: http://www.alfresco.com/services/subscription/supported-platforms/3-x/. Depending on the target deployment environment, different elements of the Alfresco stack may be favored over others. The exact configuration details for setting up the various stack element options is not discussed in this book. You can find ample discussion and details on the Alfresco wiki on how to configure, set up, and change the different stack elements. The version-specific installation and setup guides provided by Alfresco also contain very detailed information. The example description and screenshots given in this article are based on the Windows operating system. The details may differ for other operating systems, but you will find that the basic steps are very similar. Additional information on the internals of Alfresco software can be found on the Alfresco wiki at http://wiki.alfresco.com/wiki/Main_Page. Alfresco software As a first step to getting Alfresco Records Management up and running, we need to first acquire the software. Whether you plan to use either the Enterprise or the Community version of Alfresco, you should note that the Records Management module was not available until late 2009. The Records Management module was first certified with the 3.2 release of Alfresco Share. The first Enterprise version of Alfresco that supported Records Management was version 3.2R, which was released in February 2010. Make sure the software versions are compatible It is important to note that there was an early version of Records Management that was built for the Alfresco JSF-based Explorer client. That version was not certified for DoD 5015.2 compliance and is no longer supported by Alfresco. In fact, the Alfresco Explorer version of Records Management is not compatible with the Share version of Records Management, and trying to use the two implementations together can result in corrupt data. It is also important to make sure that the version of the Records Management module that you use matches the version of the base Alfresco Share software. For example, trying to use the Enterprise version of Records Management on a Community install of Alfresco will lead to problems, even if the version numbers are the same. The 3.3 Enterprise version of Records Management, as another example, is also not fully compatible with the 3.2R Enterprise version of Alfresco software. Downloading the Alfresco software The easiest way to get Alfresco Records Management up and running is by doing a fresh install of the latest available Alfresco software. Alfresco Community The Community version of Alfresco is a great place to get started. Especially if you are just interested in evaluating if Alfresco software meets your needs, and with no license fees to worry about, there's really nothing to lose in going this route. Since Alfresco Community software is constantly in the "in development" state and is not as rigorously tested, it tends to not be as stable as the Enterprise version. But, in terms of the Records Management module for the 3.2+ version releases of the software, the Community implementation is feature-complete. This means that the same Records Management features in the Enterprise version are also found in the Community version. The caveat with using the Community version is that support is only available from the Alfresco community, should you run across a problem. The Enterprise release also includes support from the Alfresco support team and may have bug fixes or patches not yet available for the community release. Also of note is the fact that there are other repository features beyond those of Records Management features, especially in the area of scalability, which are available only with the Enterprise release. Building from source code It is possible to get the most recent version of the Alfresco Community software by getting a snapshot copy of the source code from the publicly accessible Alfresco Subversion source code repository. A version of the software can be built from a snapshot of the source code taken from there. But unless you are anxiously waiting for a new Alfresco feature or bug fix and need to get your hands immediately on a build with that new code included as part of it, for most people, building from source is probably not the route to go. Building from source code can be time consuming and error prone. The final software version that you build can often be very buggy or unstable due to code that has been checked-in prematurely or changes that might be in the process of being merged into the Community release, but which weren't completely checked-in at the time you updated your snapshot of the code base. If you do decide that you'd like to try to build Alfresco software from source code, details on how to get set up to do that can be found on the Alfresco wiki: http://wiki.alfresco.com/wiki/Alfresco_SVN_Development_Environment. Download a Community version snapshot build Builds of snapshots of the Alfresco Community source code are periodically taken and made available for download. Using a pre-built Community version of Alfresco software saves you much hassle and headaches from not having to do the build from scratch. While not thoroughly tested, the snapshot Community builds have been tested sufficiently so that they tend to be stable enough to see most of the functionality available for the release, although not everything may be working completely. Links to the most recent Alfresco Community version builds can be found on the Alfresco wiki: http://wiki.alfresco.com/wiki/Download_Community_Edition. Alfresco Enterprise The alternative to using Alfresco open source Community software is the Enterprise version of Alfresco. For most organizations, the fully certified Enterprise version of Alfresco software is the recommended choice. The Enterprise version of Alfresco software has been thoroughly tested and is fully supported. Alfresco customers and partners have access to the most recent Enterprise software from the Alfresco Network site: http://network.alfresco.com/. Trial copies of Alfresco Enterprise software can be downloaded from the Alfresco site: http://www.alfresco.com/try/. Time-limited access to on-demand instances of Alfresco software are also available and are a great way to get a good understanding of how Alfresco software works.
Read more
  • 0
  • 0
  • 2991

article-image-facebook-accessing-graph-api
Packt
18 Jan 2011
8 min read
Save for later

Facebook: Accessing Graph API

Packt
18 Jan 2011
8 min read
  Facebook Graph API Development with Flash Build social Flash applications fully integrated with the Facebook Graph API Build your own interactive applications and games that integrate with Facebook Add social features to your AS3 projects without having to build a new social network from scratch Learn how to retrieve information from Facebook's database A hands-on guide with step-by-step instructions and clear explanation that encourages experimentation and play Accessing the Graph API through a Browser We'll dive right in by taking a look at how the Graph API represents the information from a public Page. When I talk about a Page with a capital P, I don't just mean any web page within the Facebook site; I'm referring to a specific type of page, also known as a public profile. Every Facebook user has their own personal profile; you can see yours by logging in to Facebook and clicking on the "Profile" link in the navigation bar at the top of the site. Public profiles look similar, but are designed to be used by businesses, bands, products, organizations, and public figures, as a way of having a presence on Facebook. This means that many people have both a personal profile and a public profile. For example, Mark Zuckerberg, the CEO of Facebook, has a personal profile at http://www.facebook.com/zuck and a public profile (a Page) at http://www.facebook.com/markzuckerberg. This way, he can use his personal profile to keep in touch with his friends and family, while using his public profile to connect with his fans and supporters. There is a second type of Page: a Community Page. Again, these look very similar to personal profiles; the difference is that these are based on topics, experience, and causes, rather than entities. Also, they automatically retrieve information about the topic from Wikipedia, where relevant, and contain a live feed of wall posts talking about the topic. All this can feel a little confusing – don't worry about it! Once you start using it, it all makes sense. Time for action – loading a Page Browse to http://www.facebook.com/PacktPub to load Packt Publishing's Facebook Page. You'll see a list of recent wall posts, an Info tab, some photo albums (mostly containing book covers), a profile picture, and a list of fans and links. That's how website users view the information. How will our code "see" it? Take a look at how the Graph API represents Packt Publishing's Page by pointing your web browser at https://graph.facebook.com/PacktPub. This is called a Graph URL – note that it's the same URL as the Page itself, but with a secure https connection, and using the graph sub domain, rather than www. What you'll see is as follows: { "id": "204603129458", "name": "Packt Publishing", "picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/ hs302.ash1/23274_204603129458_7460_s.jpg", "link": "http://www.facebook.com/PacktPub", "category": "Products_other", "username": "PacktPub", "company_overview": "Packt is a modern, IT focused book publisher, specializing in producing cutting-edge books for communities of developers, administrators, and newbies alike.nnPackt published its first book, Mastering phpMyAdmin for MySQL Management in April 2004.", "fan_count": 412 } What just happened? You just fetched the Graph API's representation of the Packt Publishing Page in your browser. The Graph API is designed to be easy to pick up – practically self-documenting – and you can see that it's a success in that respect. It's pretty clear that the previous data is a list of fields and their values. The one field that's perhaps not clear is id; this number is what Facebook uses internally to refer to the Page. This means Pages can have two IDs: the numeric one assigned automatically by Facebook, and an alphanumeric one chosen by the Page's owner. The two IDs are equivalent: if you browse to https://graph.facebook.com/204603129458, you'll see exactly the same data as if you browse to https://graph.facebook.com/PacktPub. Have a go hero – exploring other objects Of course, the Packt Publishing Page is not the only Page you can explore with the Graph API in your browser. Find some other Pages through the Facebook website in your browser, then, using the https://graph.facebook.com/id format, take a look at their Graph API representations. Do they have more information, or less? Next, move on to other types of Facebook objects: personal profiles, events, groups. For personal profiles, the id may be alphanumeric (if the person has signed up for a custom Facebook Username at http://www.facebook.com/username/), but in general the id will be numeric, and auto-assigned by Facebook when the user signed up. For certain types of objects (like photo albums), the value of id will not be obvious from the URL within the Facebook website. In some cases, you'll get an error message, like: { "error": { "type": "OAuthAccessTokenException", "message": "An access token is required to request this resource." } } Accessing the Graph API through AS3 Now that you've got an idea of how easy it is to access and read Facebook data in a browser, we'll see how to fetch it in AS3. Time for action – retrieving a Page's information in AS3 Set up the project. Check that the project compiles with no errors (there may be a few warnings, depending on your IDE). You should see a 640 x 480 px SWF, all white, with just three buttons in the top-left corner: Zoom In, Zoom Out, and Reset View: This project is the basis for a Rich Internet Application (RIA) that will be able to explore all of the information on Facebook using the Graph API. All the code for the UI is in place, just waiting for some Graph data to render. Our job is to write code to retrieve the data and pass it on to the renderers. I'm not going to break down the entire project and explain what every class does. What you need to know at the moment is a single instance of the controllers. CustomGraphContainerController class is created when the project is initialized, and it is responsible for directing the flow of data to and from Facebook. It inherits some useful methods for this purpose from the controllers.GCController class; we'll make use of these later on. Open the CustomGraphContainerController class in your IDE. It can be found in srccontrollersCustomGraphContainerController.as, and should look like the listing below: package controllers { import ui.GraphControlContainer; public class CustomGraphContainerController extends GCController { public function CustomGraphContainerController (a_graphControlContainer:GraphControlContainer) { super(a_graphControlContainer); } } } The first thing we'll do is grab the Graph API's representation of Packt Publishing's Page via a Graph URL, like we did using the web browser. For this we can use a URLLoader. The URLLoader and URLRequest classes are used together to download data from a URL. The data can be text, binary data, or URL-encoded variables. The download is triggered by passing a URLRequest object, whose url property contains the requested URL, to the load() method of a URLLoader. Once the required data has finished downloading, the URLLoader dispatches a COMPLETE event. The data can then be retrieved from its data property. Modify CustomGraphContainerController.as like so (the highlighted lines are new): package controllers { import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; import ui.GraphControlContainer; public class CustomGraphContainerController extends GCController { public function CustomGraphContainerController (a_graphControlContainer:GraphControlContainer) { super(a_graphControlContainer); var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest(); //Specify which Graph URL to load request.url = "https://graph.facebook.com/PacktPub"; loader.addEventListener(Event.COMPLETE, onGraphDataLoadComplete); //Start the actual loading process loader.load(request); } private function onGraphDataLoadComplete(a_event:Event):void { var loader:URLLoader = a_event.target as URLLoader; //obtain whatever data was loaded, and trace it var graphData:String = loader.data; trace(graphData); } } } All we're doing here is downloading whatever information is at https://graph.facebook.com/PackPub and tracing it to the output window. Test your project, and take a look at your output window. You should see the following data: {"id":"204603129458","name":"Packt Publishing","picture":"http:// profile.ak.fbcdn.net/hprofile-ak-snc4/hs302. ash1/23274_204603129458_7460_s.jpg","link":"http://www.facebook. com/PacktPub","category":"Products_other","username":"PacktPub", "company_overview":"Packt is a modern, IT focused book publisher, specializing in producing cutting-edge books for communities of developers, administrators, and newbies alike.nnPackt published its first book, Mastering phpMyAdmin for MySQL Management in April 2004.","fan_count":412} If you get an error, check that your code matches the previously mentioned code. If you see nothing in your output window, make sure that you are connected to the Internet. If you still don't see anything, it's possible that your security settings prevent you from accessing the Internet via Flash, so check those.  
Read more
  • 0
  • 0
  • 2669

article-image-tortoisesvn-getting-started
Packt
18 Jan 2011
7 min read
Save for later

TortoiseSVN: Getting Started

Packt
18 Jan 2011
7 min read
  TortoiseSVN 1.7 Beginner's Guide Perform version control in the easiest way with the best SVN client – TortoiseSVN Master version control techniques with TortoiseSVN without the need for boring theory Revolves around a real-world example based on a software company The first and the only book that focuses on version control with TortoiseSVN Reviewed by Stefan Kung, lead developer for the TortoiseSVN project So let's get on with it... Our case study Shiny Moose Software is a software house with a small team of developers. They have just started working on their first project—a Hiragana Learning Game written in Python. The lead developer, Quinn, has created a skeleton for the project. He has written the code for the games "splash screen". One of the other developers, Mowbray, downloaded a compressed archive containing Quinn's code and found that on his older computer, the CPU usage spiked massively when the code was run. He looked at the code and noticed that Quinn had made a poor choice when deciding how to detect mouse events. The problem is simple to fix, but Mowbray knows that communicating the changes to Quinn could be problematic. Mowbray could make the required changes and then e-mail the updated code to Quinn, but what if Quinn returns to his computer and resumes his work on the application before he checks his e-mail? What if one of the other developers at Shiny Moose Software has also decided to make some changes to the code? Keeping track of changes submitted by several different developers would be confusing enough even with this relatively small application. Imagine how difficult it would become when the code is measured in hundreds, or thousands of lines, rather than just a few dozen! This is where Subversion saves the day. Instead of copying the code from a normal shared folder, or downloading it from the company's intranet site, Mowbray can use TortoiseSVN to check out a working copy of the code, inform the Subversion server that is currently working on that file, make the changes, and check it back in. A word about our examples The code snippets used in this article are incredibly simplistic. Please don't use them as examples for how to write a Python application! Also, don't worry too much about the language or IDE used in these examples. TortoiseSVN can be used with any language and any development environment. Even team members working on other areas, such as documentation or translation work, can take advantage of TortoiseSVN. The most important thing is to understand the version control principles which are being applied. Working copies explained The first thing Mowbray needs to do is check out a working copy. He can make changes to this copy and then submit the changes once he is done. Time for action – checking out a working copy Checking out a working copy takes just a few simple steps. Create a folder which you will use to store your working copies. For example, C:ProjectsMooseHiragana. Right-click inside that folder and select SVN Checkout... from the menu that appears. Browse to your project's repository (or enter the correct network path) and click OK. A window containing a list of the files which have been checked out will appear. If the checkout was successful, you should see a list of files in your chosen directory, with a green tick on the icon of each file. (Move the mouse over the image to enlarge.) What just happened? You have just checked out a working copy of the files which are stored on the repository. This is useful because it allows you to safely test, change, and experiment with the code without the risk of breaking the original code. Once you are happy with the changes you have made, you can check them in to the repository, so that your fellow developers can synchronize their copies to see your changes. Local repositories vs. remote repositories We will use remote repositories in most of our examples. It is likely that you will, at some point, need to work with a remote repository—either one which is accessed via the internet, or one which is part of your company's network. In that case, all you need to do is enter the full network/ internet address of the repository in the place of the file:/// reference in the URL of Repository box. Checkout depth The MooseHiragana project is quite small, so there is no issue with checking out the entire repository. If you were working on a much larger project, which had thousands of files, then you may prefer to save time, bandwidth and storage space by checking out only the folders that relate to the part of the project you are working on. Time for action – using checkout depth Using a different folder for this working copy, right-click inside the folder, and select SVN Checkout.... This time, in the Checkout window that appears, as well as selecting the correct repository, choose Only file children from the Checkout Depth dropdown. You should see that when the checkout process completes, all the files that are part of the root folder appear in your working copy, but none of the folders have been checked out. What just happened? You have just checked out only the files that are in the root folder of the project on the Subversion server. That may not seem like a particularly useful feature when the project consists of just a few files, but imagine if there were thousands of files. The checkout depth feature becomes useful when projects increase greatly in size. It is also useful if your team has members that work only on specific parts of the application. For example, an artist could check out only the images folder, or a translator could check out only the folder containing the localization files for the language he is working in. If the artist then needs to expand his checkout to include deeper folders, he can use the repository browser to select the extra folders that he needs. There are a number of different checkout depth options. The following table explains what each option means. Checkout Depth OptionPurposeFully recursiveChecks out the entire tree, including all child folders and sub-folders.Immediate children, including foldersChecks out the specified directory, including all files and child folders, but does not populate the child folders.Only file childrenChecks out the specified directory, including all files, but does not check out any child folders.Only this itemChecks out the selected directory only. Does not populate it with files or child folders.Working copyThis option is not shown on the checkout dialog, but it is the default for all other dialogs which have a depth setting. This option tells TortoiseSVN to adhere to the depth specified in the working copy.ExcludeThis option is not shown on the checkout dialog. It is used to reduce the depth of the working copy after a folder has already been populated. Have a go hero – working with checkout depth Imagine that you are an artist. You have been hired by Shiny Moose Software and asked to redesign the logo used on the splash screen and also to create a smaller one for use in the theme of the game. The directory structure chosen by the developers looks like this: The images that you will be working on are stored in the /images folder. You will not need to work on anything inside the /images/artwork or /images/japanese folders. You need to set up your working copy. Rather than cluttering your filesystem with files that you will never need to use, you have decided to checkout only the folder you need for your work—the /images folder. Using another user account (or another PC on your network), try checking out just the contents of that folder from the repository. If you prefer, you could simply create a new working directory using the same user. However, if you do this, you should note that any changes made in that folder will be marked with your own user name. That may be fine for testing TortoiseSVN's features, but is not good practice in a production environment.  
Read more
  • 0
  • 0
  • 2713

article-image-tinkering-around-django-javascript-integration
Packt
18 Jan 2011
9 min read
Save for later

Tinkering Around in Django JavaScript Integration

Packt
18 Jan 2011
9 min read
Minor tweaks and bugfixes Good tinkering can be a process that begins with tweaks and bugfixes, and snowballs from there. Let's begin with some of the smaller tweaks and bugfixes before tinkering further. Setting a default name of "(Insert name here)" Most of the fields on an Entity default to blank, which is in general appropriate. However, this means that there is a zero-width link for any search result which has not had a name set. If a user fills out the Entity's name before navigating away from that page, everything is fine, but it is a very suspicious assumption that all users will magically use our software in whatever fashion would be most convenient for our implementation. So, instead, we set a default name of "(Insert name here)" in the definition of an Entity, in models.py: name = models.TextField(blank = True, default = u'(Insert name here)') Eliminating Borg behavior One variant on the classic Singleton pattern in Gang of Four is the Borg pattern, where arbitrarily many instances of a Borg class may exist, but they share the same dictionary, so that if you set an attribute on one of them, you set the attribute on all of them. At present we have a bug, which is that our views pull all available instances. We need to specify something different. We update the end of ajax_profile(), including a slot for time zones to be used later in this article, to: return render_to_response(u'profile_internal.html', { u'entities': directory.models.Entity.objects.filter( is_invisible = False).order_by(u'name'), u'entity': entity, u'first_stati': directory.models.Status.objects.filter( entity = id).order_by( u'-datetime')[:directory.settings.INITIAL_STATI], u'gps': gps, u'gps_url': gps_url, u'id': int(id), u'emails': directory.models.Email.objects.filter( entity = entity, is_invisible = False), u'phones': directory.models.Phone.objects.filter( entity = entity, is_invisible = False), u'second_stati': directory.models.Status.objects.filter( entity = id).order_by( u'-datetime')[directory.settings.INITIAL_STATI:], u'tags': directory.models.Tag.objects.filter(entity = entity, is_invisible = False).order_by(u'text'), u'time_zones': directory.models.TIME_ZONE_CHOICES, u'urls': directory.models.URL.objects.filter(entity = entity, is_invisible = False), }) Likewise, we update homepage(): profile = template.render(Context( { u'entities': directory.models.Entity.objects.filter( is_invisible = False), u'entity': entity, u'first_stati': directory.models.Status.objects.filter( entity = id).order_by( u'-datetime')[:directory.settings.INITIAL_STATI], u'gps': gps, u'gps_url': gps_url, u'id': int(id), u'emails': directory.models.Email.objects.filter( entity = entity, is_invisible = False), u'phones': directory.models.Phone.objects.filter( entity = entity, is_invisible = False), u'query': urllib.quote(query), u'second_stati':directory.models.Status.objects.filter( entity = id).order_by( u'-datetime')[directory.settings.INITIAL_STATI:], u'time_zones': directory.models.TIME_ZONE_CHOICES, u'tags': directory.models.Tag.objects.filter( entity = entity, is_invisible = False).order_by(u'text'), u'urls': directory.models.URL.objects.filter( entity = entity, is_invisible = False), })) Confusing jQuery's load() with html() If we have failed to load a profile in the main search.html template, we had a call to load(""). What we needed was: else { $("#profile").html(""); } $("#profile").load("") loads a copy of the current page into the div named profile. We can improve on this slightly to "blank" contents that include the default header: else { $("#profile").html("<h2>People, etc.</h2>"); } Preventing display of deleted instances In our system, enabling undo means that there can be instances (Entities, Emails, URLs, and so on) which have been deleted but are still available for undo. We have implemented deletion by setting an is_invisible flag to True, and we also need to check before displaying to avoid puzzling behavior like a user deleting an Entity, being told Your change has been saved, and then seeing the Entity's profile displayed exactly as before. We accomplish this by a specifying, for a Queryset .filter(is_invisible = False) where we might earlier have specified .all(), or adding is_invisible = False to the conditions of a pre-existing filter; for instance: def ajax_download_model(request, model): if directory.settings.SHOULD_DOWNLOAD_DIRECTORY: json_serializer = serializers.get_serializer(u'json')() response = HttpResponse(mimetype = u'application/json') if model == u'Entity': json_serializer.serialize(getattr(directory.models, model).objects.filter( is_invisible = False).order_by(u'name'), ensure_ascii = False, stream = response) else: json_serializer.serialize(getattr(directory.models, model).objects.filter(is_invisible = False), ensure_ascii = False, stream = response) return response else: return HttpResponse(u'This feature has been turned off.') In the main view for the profile, we add a check in the beginning so that a (basically) blank result page is shown: def ajax_profile(request, id): entity = directory.models.Entity.objects.filter(id = int(id))[0] if entity.is_invisible: return HttpResponse(u'<h2>People, etc.</h2>') One nicety we provide is usually loading a profile on mouseover for its area of the search result page. This means that users can more quickly and easily scan through drilldown pages in search of the right match; however, there is a performance gotcha for simply specifying an onmouseover handler. If you specify an onmouseover for a containing div, you may get a separate event call for every time the user hovers over an element contained in the div, easily getting 3+ calls if a user moves the mouse over to the link. That could be annoying to people on a VPN connection if it means that they are getting the network hits for numerous needless profile loads. To cut back on this, we define an initially null variable for the last profile moused over: Then we call the following function in the containing div element's onmouseover: PHOTO_DIRECTORY.last_mouseover_profile = null; Then we call the following function in the containing div element's onmouseover: PHOTO_DIRECTORY.mouseover_profile = function(profile) { if (profile != PHOTO_DIRECTORY.last_mouseover_profile) { PHOTO_DIRECTORY.load_profile(profile); PHOTO_DIRECTORY.last_mouseover_profile = profile; PHOTO_DIRECTORY.register_editables(); } } The relevant code from search_internal.html is as follows: <div class="search_result" onmouseover="PHOTO_DIRECTORY.mouseover_profile( {{ result.id }});" onclick="PHOTO_DIRECTORY.click_profile({{ result.id }});"> We usually, but not always, enable this mouseover functionality; not always, because it works out to annoying behavior if a person is trying to edit, does a drag select, mouses over the profile area, and reloads a fresh, non-edited profile. Here we edit the Jeditable plugin's source code and add a few lines; we also perform a second check for if the user is logged in, and offer a login form if so: /* if element is empty add something clickable (if requested) */if (!$.trim($(this).html())) { $(this).html(settings.placeholder);}$(this).bind(settings.event, function(e) { $("div").removeAttr("onmouseover"); if (!PHOTO_DIRECTORY.check_login()) { PHOTO_DIRECTORY.offer_login(); } /* abort if disabled for this element */ if (true === $(this).data('disabled.editable')) { return; } For Jeditable-enabled elements, we can override the placeholder for an empty element at method call, but the default placeholder is cleared when editing begins; overridden placeholders aren't. We override the placeholder with something that gives us a little more control and styling freedom: // publicly accessible defaults $.fn.editable.defaults = { name : 'value', id : 'id', type : 'text', width : 'auto', height : 'auto', event : 'click.editable', onblur : 'cancel', loadtype : 'GET', loadtext : 'Loading...', placeholder:'<span class="placeholder"> Click to add.</span>', loaddata : {}, submitdata : {}, ajaxoptions: {} }; All of this is added to the file jquery.jeditable.js. We now have, as well as an @ajax_login_required decorator, an @ajax_permission_required decorator. We test for this variable in the default postprocessor specified in $.ajaxSetup() for the complete handler. Because Jeditable will place the returned data inline, we also refresh the profile. This occurs after the code to check for an undoable edit and offer an undo option to the user. complete: function(XMLHttpRequest, textStatus) { var data = XMLHttpRequest.responseText; var regular_expression = new RegExp("<!-" + "-# (d+) #-" + "->"); if (data.match(regular_expression)) { var match = regular_expression.exec(data); PHOTO_DIRECTORY.undo_notification( "Your changes have been saved. " + "<a href='JavaScript:PHOTO_DIRECTORY.undo(" + match[1] + ")'>Undo</a>"); } else if (data == '{"not_permitted": true}' || data == "{'not_permitted': true}") { PHOTO_DIRECTORY.send_notification( "We are sorry, but we cannot allow you " + "to do that."); PHOTO_DIRECTORY.reload_profile(); } }, Note that we have tried to produce the least painful of clear message we can: we avoid both saying "You shouldn't be doing that," and a terse, "bad movie computer"-style message of "Access denied" or "Permission denied." We also removed from that method code to call offer_login() if a call came back not authenticated. This looked good on paper, but our code was making Ajax calls soon enough that the user would get an immediate, unprovoked, modal login dialog on loading the page. Adding a favicon.ico In terms of minor tweaks, some visually distinct favicon.ico (http://softpedia.com/ is one of many free sources of favicon.ico files, or the favicon generator at http://tools.dynamicdrive.com/favicon/ which can take an image like your company logo as the basis for an icon) helps your tabs look different at a glance from other tabs. Save a good, simple favicon in static/favicon.ico. The icon may not show up immediately when you refresh, but a good favicon makes it slightly easier for visitors to manage your pages among others that they have to deal with. It shows up in the address bar, bookmarks, and possibly other places. This brings us to the end of the minor tweaks; let us look at two slightly larger additions to the directory.
Read more
  • 0
  • 0
  • 2476
article-image-creating-line-graphs-r
Packt
17 Jan 2011
7 min read
Save for later

Creating Line Graphs in R

Packt
17 Jan 2011
7 min read
Adding customized legends for multiple line graphs Line graphs with more than one line, representing more than one variable, are quite common in any kind of data analysis. In this recipe we will learn how to create and customize legends for such graphs. Getting ready We will use the base graphics library for this recipe, so all you need to do is run the recipe at the R prompt. It is good practice to save your code as a script to use again later. How to do it... First we need to load the cityrain.csv example data file, which contains monthly rainfall data for four major cities across the world. You can download this file from here. We will use the cityrain.csv example dataset. rain<-read.csv("cityrain.csv") plot(rain$Tokyo,type="b",lwd=2, xaxt="n",ylim=c(0,300),col="black", xlab="Month",ylab="Rainfall (mm)", main="Monthly Rainfall in major cities") axis(1,at=1:length(rain$Month),labels=rain$Month) lines(rain$Berlin,col="red",type="b",lwd=2) lines(rain$NewYork,col="orange",type="b",lwd=2) lines(rain$London,col="purple",type="b",lwd=2) legend("topright",legend=c("Tokyo","Berlin","New York","London"), lty=1,lwd=2,pch=21,col=c("black","red","orange","purple"), ncol=2,bty="n",cex=0.8, text.col=c("black","red","orange","purple"), inset=0.01) How it works... We used the legend() function. It is quite a flexible function and allows us to adjust the placement and styling of the legend in many ways. The first argument we passed to legend() specifies the position of the legend within the plot region. We used "topright"; other possible values are "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "right", and "center". We can also specify the location of legend with x and y co-ordinates as we will soon see. The other important arguments specific to lines are lwd and lty which specify the line width and type drawn in the legend box respectively. It is important to keep these the same as the corresponding values in the plot() and lines() commands. We also set pch to 21 to replicate the type="b" argument in the plot() command. cex and text.col set the size and colors of the legend text. Note that we set the text colors to the same colors as the lines they represent. Setting bty (box type) to "n" ensures no box is drawn around the legend. This is good practice as it keeps the look of the graph clean. ncol sets the number of columns over which the legend labels are spread and inset sets the inset distance from the margins as a fraction of the plot region. There's more... Let's experiment by changing some of the arguments discussed: legend(1,300,legend=c("Tokyo","Berlin","New York","London"), lty=1,lwd=2,pch=21,col=c("black","red","orange","purple"), horiz=TRUE,bty="n",bg="yellow",cex=1, text.col=c("black","red","orange","purple")) This time we used x and y co-ordinates instead of a keyword to position the legend. We also set the horiz argument to TRUE. As the name suggests, horiz makes the legend labels horizontal instead of the default vertical. Specifying horiz overrides the ncol argument. Finally, we made the legend text bigger by setting cex to 1 and did not use the inset argument. An alternative way of creating the previous plot without having to call plot() and lines() multiple times is to use the matplot() function. To see details on how to use this function, please see the help file by running ?matplot or help(matplot) at the R prompt. Using margin labels instead of legends for multiple line graphs While legends are the most commonly used method of providing a key to read multiple variable graphs, they are often not the easiest to read. Labelling lines directly is one way of getting around that problem. Getting ready We will use the base graphics library for this recipe, so all you need to do is run the recipe at the R prompt. It is good practice to save your code as a script to use again later. How to do it... Let's use the gdp.txt example dataset to look at the trends in the annual GDP of five countries: gdp<-read.table("gdp_long.txt",header=T) library(RColorBrewer) pal<-brewer.pal(5,"Set1") par(mar=par()$mar+c(0,0,0,2),bty="l") plot(Canada~Year,data=gdp,type="l",lwd=2,lty=1,ylim=c(30,60), col=pal[1],main="Percentage change in GDP",ylab="") mtext(side=4,at=gdp$Canada[length(gdp$Canada)],text="Canada", col=pal[1],line=0.3,las=2) lines(gdp$France~gdp$Year,col=pal[2],lwd=2) mtext(side=4,at=gdp$France[length(gdp$France)],text="France", col=pal[2],line=0.3,las=2) lines(gdp$Germany~gdp$Year,col=pal[3],lwd=2) mtext(side=4,at=gdp$Germany[length(gdp$Germany)],text="Germany", col=pal[3],line=0.3,las=2) lines(gdp$Britain~gdp$Year,col=pal[4],lwd=2) mtext(side=4,at=gdp$Britain[length(gdp$Britain)],text="Britain", col=pal[4],line=0.3,las=2) lines(gdp$USA~gdp$Year,col=pal[5],lwd=2) mtext(side=4,at=gdp$USA[length(gdp$USA)]-2, text="USA",col=pal[5],line=0.3,las=2) How it works... We first read the gdp.txt data file using the read.table() function. Next we loaded the RColorBrewer color palette library and set our color palette pal to "Set1" (with five colors). Before drawing the graph, we used the par() command to add extra space to the right margin, so that we have enough space for the labels. Depending on the size of the text labels you may have to experiment with this margin until you get it right. Finally, we set the box type (bty) to an L-shape ("l") so that there is no line on the right margin. We can also set it to "c" if we want to keep the top line. We used the mtext() function to label each of the lines individually in the right margin. The first argument we passed to the function is the side where we want the label to be placed. Sides (margins) are numbered starting from 1 for the bottom side and going round in a clockwise direction so that 2 is left, 3 is top, and 4 is right. The at argument was used to specify the Y co-ordinate of the label. This is a bit tricky because we have to make sure we place the label as close to the corresponding line as possible. So, here we have used the last value of each line. For example, gdp$France[length(gdp$France) picks the last value in the France vector by using its length as the index. Note that we had to adjust the value for USA by subtracting 2 from its last value so that it doesn't overlap the label for Canada. We used the text argument to set the text of the labels as country names. We set the col argument to the appropriate element of the pal vector by using a number index. The line argument sets an offset in terms of margin lines, starting at 0 counting outwards. Finally, setting las to 2 rotates the labels to be perpendicular to the axis, instead of the default value of 1 which makes them parallel to the axis. Sometimes, simply using the last value of a set of values may not work because the value may be missing. In that case we can use the second last value or visually choose a value that places the label closest to the line. Also, the size of the plot window and the proximity of the final values may cause overlapping of labels. So, we may need to iterate a few times before we get the placement right. We can write functions to automate this process but it is still good to visually inspect the outcome.
Read more
  • 0
  • 0
  • 4319

article-image-roles-and-responsibilities-records-management-implementation-alfresco-3
Packt
17 Jan 2011
10 min read
Save for later

Roles and Responsibilities for Records Management Implementation in Alfresco 3

Packt
17 Jan 2011
10 min read
  Alfresco 3 Records Management Comply with regulations and secure your organization’s records with Alfresco Records Management. Successfully implement your records program using Alfresco Records Management, fully certified for DoD-5015.2 compliance The first and only book to focus exclusively on Alfresco Records Management Step-by-step instructions describe how to identify records, organize records, and manage records to comply with regulatory requirements Learn in detail about the software internals to get a jump-start on performing customizations Appendix         Read more about this book       (For more resources on this subject, see here.) The steering committee To succeed, our Records Management program needs continued commitment from all levels of the organization. A good way to cultivate that commitment is by establishing a steering committee for the records program. From a high level, the steering committee will direct the program, set priorities for it, and assist in making decisions. The steering committee will provide the leadership to ensure that the program is adequately funded, staffed, properly prioritized with business objectives, and successfully implemented. Committee members should know the organization well and be in a position to be both able and willing to make decisions. Once the program is implemented, the steering committee should not be dissolved; it still will play an important function. It will continue to meet and oversee the Records Management program to make sure that it is properly maintained and updated. The Records Management system is not something that can simply be turned on and forgotten. The steering committee should meet regularly, track the progress of the implementation, keep abreast of changes in regulatory controls, and be proactive in addressing the needs of the Records Management program. Key stakeholders The Records Management steering committee should include executives and senior management from core business units such as Compliance, Legal, Finance, IT, Risk Management, Human Resources, and any other groups that will be affected by Records Management. Each of these groups will represent the needs and responsibilities of their respective groups. They will provide input relative to policies and procedures. The groups will work together to develop a priority-sequenced implementation plan that all can agree upon. Creating a committee that is heavily weighted with company executives will visibly demonstrate that our company is strongly committed to the program and it ensures that we will have the right people on board when it is time to make decisions, and that will keep the program on track. The steering committee should also include representatives from Records Management, IT, and users. Alternatively, representatives from these groups can be appointed and, if not members of the steering committee, they should report directly to the steering committee on a regular basis: The Program Contact The Program Contact is the chair of the steering committee. This role is typically held by someone in senior management and is often someone from the technology side of the business, such as the Director of IT. The Program Contact signs off with the final approval on technology deliverables and budget items. The Program Sponsor A key member of the records steering committee is the Program Sponsor or Project Champion. This role is typically held by a senior executive who will be able to represent the records initiative within the organization's executive team. The Sponsor will be able to establish the priority of the records program, relative to other organizational initiatives and be able to persuade the executive team and others in the company of the importance of the records management initiative. Corporate Records Manager Another key role of the steering committee is the Corporate Records Manager. This role acts as the senior champion for the records program and is responsible for defining the procedures and policies around Records Management. The person in this role will promote the rollout of and the use of the records program. They will work with each of the participating departments or groups, cultivating local champions for Records Management within each of those groups. The Corporate Records Manager must effectively communicate with business units to explain the program to all staff members and work with the various business units to collect user feedback so that those ideas can be incorporated into the planning process. The Corporate Records Manager will try to minimize any adverse user impact or disruption. Project Manager The Project Manager typically is on the steering committee or reports directly to it. The Project Manager plans and tracks the implementation of work on the program and ensures that program milestones are met. The person in this role manages both, the details of the system setup and implementation. This Project Manager also manages the staff time spent working on the program tasks. Business Analyst The Business Analyst analyzes business processes and records, and from these, creates a design and plan for the records program implementation. The Business Analyst works closely with the Corporate Records Manager to develop records procedures and provides support for the system during rollout. Systems Administrator The Systems Administrator leads the technical team for supporting the records application. The Systems Administrator specifies and puts into place the hardware required for the records program, the storage space, memory, and CPU capabilities. The person in this role monitors the system performance and backs up the system regularly. The Systems Administrator leads the team to apply software upgrades and to perform system troubleshooting. The Network Administrator The Network Administrator ensures that the network infrastructure is in place for the records program to support the appropriate bandwidth for the server and client workstations that will access the application. The Network Administrator works closely with the Systems Administrator. The Technical Analyst The Technical Analyst is responsible for analyzing the configuration of the records program. The Technical Analyst needs to work closely with the Business Analyst and Corporate Records Manager. The person in this role will specify the classification and structure used for the records program File Plan. They will also specify the classes of documents stored as records in the records application and the associated metadata for those documents. The Records Assistant The Records Assistant assists in the configuration of the records application. Tasks that the Records Assistant will perform include data entry and creating the folder structure hierarchy of the File Plan within the records application based on the specification created by the Technical Analyst. The Records Developer The Records Developer is a software engineer that is assigned to support the implementation of the records program, based on requirements derived by the Business Analyst. The Records Developer may need to edit and update configuration files, often using technologies like XML. The Records Developer may also need to make customizations to the user interface of the application. The Trainer The Trainer will work with end users to ensure that they understand the system and their responsibilities in interacting with it. The trainer typically creates training materials and provides training seminars to users. The Technical Support Specialist The Technical Support Specialist provides support to users on the functioning of the Records Management application. This person is typically an advanced user and is trained to be able to provide guidance in interacting with the application. But more than just the Records Management application, the support specialist should also be well versed in and be able to assist users and answer their questions about records processes and procedures, as well as concepts like retention and disposition of documents. The Technical Support Specialist will, very often, be faced with requests or questions that are really enhancement requests. The support specialist needs to have a good understanding of the scope of the records implementation and be able to distinguish an enhancement request from a defect or bug report. Enhancements should be collected and routed back through the Project Manager and, depending on the nature of the request or problem, possibly even to the Corporate Records Manager or the Steering Committee. Similarly, application defects or bugs that are found should be reported back through to the Project Manager. Bug reports will be prioritized by the Project Manager, as appropriate, assigned to the Technical Developers, or reported to the Systems Integrator or to Alfresco. The Users The Users are the staff members who will use the Records Management application as part of their job. Users are often the key to the success or failure of a records program. Unfortunately, users are one aspect of the project that is often overlooked. Obviously, it is important that the records application be well designed and meet the objectives and requirements set out for it. But if users complain and can't accept it, then the program will be doomed to failure. Users will often be asked to make changes to processes that they have become very comfortable with. Frequent and early communication with users is a must in order to ultimately gain their acceptance and participation. Prior to and during the implementation of the records system, users should receive status updates and explanations from the Corporate Records Manager and also from the Records Manager lead in their business unit. It is important that frequent communications be made with users to ensure their opinions and ideas are heard, and also so that they will learn to be able to most effectively use the records system. Once the application is ready, or better yet, well before the application goes live, users should attend training sessions on proper records-handling behavior; they should experience hands-on training with the application; and they should also be instructed in how best to communicate with the Technical Support Specialist, should they ever have questions or encounter any problems. Alfresco, Consultants, and Systems Integrators Alfresco is the software vendor for Alfresco Records Management, but Alfresco typically does not work directly with customers. We could go at it alone, but more likely, we'll probably choose to work directly with one of Alfresco's System Integration partners or consultants in planning for and setting up our system. Depending on the size of our organization and the available skill set within it, the Systems Integrator can take on as much or as little of the burden for helping us to get up and running with our Records Management program. Almost any of the Technical Team roles discussed in this section, like those of the Analyst and Developer, and even the role of the Project Manager, are ones that can be performed by a Systems Integrator. A list of certified Alfresco Integrators can be found on the Alfresco site: http://www.alfresco.com/partners/search.jsp?t=si A Systems Integrator can bring to our project an important breadth of experience that can help save time and ensure that our project will go smoothly. Alfresco Systems Integration partners know their stuff. They are required to be certified in Alfresco technology and they have worked with Alfresco extensively. They are familiar with best practices and have picked up numerous implementation tips and tricks having worked on similar projects with other clients.
Read more
  • 0
  • 0
  • 11505

article-image-replication-mysql-admin
Packt
17 Jan 2011
10 min read
Save for later

Replication in MySQL Admin

Packt
17 Jan 2011
10 min read
Replication is an interesting feature of MySQL that can be used for a variety of purposes. It can help to balance server load across multiple machines, ease backups, provide a workaround for the lack of fulltext search capabilities in InnoDB, and much more. The basic idea behind replication is to reflect the contents of one database server (this can include all databases, only some of them, or even just a few tables) to more than one instance. Usually, those instances will be running on separate machines, even though this is not technically necessary. Traditionally, MySQL replication is based on the surprisingly simple idea of repeating the execution of all statements issued that can modify data—not SELECT—against a single master machine on other machines as well. Provided all secondary slave machines had identical data contents when the replication process began, they should automatically remain in sync. This is called Statement Based Replication (SBR). With MySQL 5.1, Row Based Replication (RBR) was added as an alternative method for replication, targeting some of the deficiencies SBR brings with it. While at first glance it may seem superior (and more reliable), it is not a silver bullet—the pain points of RBR are simply different from those of SBR. Even though there are certain use cases for RBR, all recipes in this chapter will be using Statement Based Replication. While MySQL makes replication generally easy to use, it is still important to understand what happens internally to be able to know the limitations and consequences of the actions and decisions you will have to make. We assume you already have a basic understanding of replication in general, but we will still go into a few important details. Statement Based Replication SBR is based on a simple but effective principle: if two or more machines have the same set of data to begin with, they will remain identical if all of them execute the exact same SQL statements in the same order. Executing all statements manually on multiple machines would be extremely tedious and impractical. SBR automates this process. In simple terms, it takes care of sending all the SQL statements that change data on one server (the master) to any number of additional instances (the slaves) over the network. The slaves receiving this stream of modification statements execute them automatically, thereby effectively reproducing the changes the master machine made to its data originally. That way they will keep their local data files in sync with the master's. One thing worth noting here is that the network connection between the master and its slave(s) need not be permanent. In case the link between a slave and its master fails, the slave will remember up to which point it had read the data last time and will continue from there once the network becomes available again. In order to minimize the dependency on the network link, the slaves will retrieve the binary logs (binlogs) from the master as quickly as they can, storing them on their local disk in files called relay logs. This way, the connection, which might be some sort of dial-up link, can be terminated much sooner while executing the statements from the local relay-log asynchronously. The relay log is just a copy of the master's binlog. The following image shows the overall architecture: Filtering In the image you can see that each slave may have its individual configuration on whether it executes all the statements coming in from the master, or just a selection of those. This can be helpful when you have some slaves dedicated to special tasks, where they might not need all the information from the master. All of the binary logs have to be sent to each slave, even though it might then decide to throw away most of them. Depending on the size of the binlogs, the number of slaves and the bandwidth of the connections in between, this can be a heavy burden on the network, especially if you are replicating via wide area networks. Even though the general idea of transferring SQL statements over the wire is rather simple, there are lots of things that can go wrong, especially because MySQL offers some configuration options that are quite counter-intuitive and lead to hard-to-find problems. For us, this has become a best practice: "Only use qualified statements and replicate-*-table configuration options for intuitively predictable replication!" What this means is that the only filtering rules that produce intuitive results are those based on the replicate-do-table and replicate-ignore-table configuration options. This includes those variants with wildcards, but specifically excludes the all-database options like replicate-do-db and replicate-ignore-db. These directives are applied on the slave side on all incoming relay logs. The master-side binlog-do-* and binlog-ignore-* configuration directives influence which statements are sent to the binlog and which are not. We strongly recommend against using them, because apart from hard-to-predict results they will make the binlogs undesirable for server backup and restore. They are often of limited use anyway as they do not allow individual configurations per slave but apply to all of them. Setting up automatically updated slaves of a server based on a SQL dump In this recipe, we will show you how to prepare a dump file of a MySQL master server and use it to set up one or more replication slaves. These will automatically be updated with changes made on the master server over the network. Getting ready You will need a running MySQL master database server that will act as the replication master and at least one more server to act as a replication slave. This needs to be a separate MySQL instance with its own data directory and configuration. It can reside on the same machine if you just want to try this out. In practice, a second machine is recommended because this technique's very goal is to distribute data across multiple pieces of hardware, not place an even higher burden on a single one. For production systems you should pick a time to do this when there is a lighter load on the master machine, often during the night when there are less users accessing the system. Taking the SQL dump uses some extra resources, but unless your server is maxed out already, the performance impact usually is not a serious problem. Exactly how long the dump will take depends mostly on the amount of data and speed of the I/O subsystem. You will need an administrative operating system account on the master and the slave servers to edit the MySQL server configuration files on both of them. Moreover, an administrative MySQL database user is required to set up replication. We will just replicate a single database called sakila in this example. Replicating more than one database In case you want to replicate more than one schema, just add their names to the commands shown below. To replicate all of them, just leave out any database name from the command line. How to do it... At the operating system level, connect to the master machine and open the MySQL configuration file with a text editor. Usually it is called my.ini on Windows and my.cnf on other operating systems. On the master machine, make sure the following entries are present and add them to the [mysqld] section if not already there: server-id=1000 log-bin=master-bin If one or both entries already exist, do not change them but simply note their values. The log-bin setting need not have a value, but can stand alone as well. Restart the master server if you need to modify the configuration. Create a user account on the master that can be used by the slaves to connect: master> grant replication slave on *.* to 'repl'@'%' identified by 'slavepass'; Using the mysqldump tool included in the default MySQL install, create the initial copy to set up the slave(s): $ mysqldump -uUSER -pPASS --master-data --single-transaction sakila > sakila_master.sql Transfer the sakila_master.sql dump file to each slave you want to set up, for example, by using an external drive or network copy. On the slave, make sure the following entries are present and add them to the [mysqld] section if not present: server-id=1001 replicate-wild-do-table=sakila.% When adding more than one slave, make sure the server-id setting is unique among master and all clients. Restart the slave server. Connect to the slave server and issue the following commands (assuming the data dump was stored in the /tmp directory): slave> create database sakila; slave> use sakila; slave> source /tmp/sakila_master.sql; slave> CHANGE MASTER TO master_host='master.example.com', master_port=3306, master_ user='repl', master_password='slavepass'; slave> START SLAVE; Verify the slave is running with: slave> SHOW SLAVE STATUSG ************************** 1. row *************************** ... Slave_IO_Running: Yes Slave_SQL_Running: Yes ... How it works... Some of the instructions discussed in the previous section are to make sure that both master and slave are configured with different server-id settings. This is of paramount importance for a successful replication setup. If you fail to provide unique server-id values to all your server instances, you might see strange replication errors that are hard to debug. Moreover, the master must be configured to write binlogs—a record of all statements manipulating data (this is what the slaves will receive). Before taking a full content dump of the sakila demo database, we create a user account for the slaves to use. This needs the REPLICATION SLAVE privilege. Then a data dump is created with the mysqldump command line tool. Notice the provided parameters --master-data and --single-transaction. The former is needed to have mysqldump include information about the precise moment the dump was created in the resulting output. The latter parameter is important when using InnoDB tables, because only then will the dump be created based on a transactional snapshot of the data. Without it, statements changing data while the tool was running could lead to an inconsistent dump. The output of the command is redirected to the /tmp/sakila_master.sql file. As the sakila database is not very big, you should not see any problems. However, if you apply this recipe to larger databases, make sure you send the data to a volume with sufficient free disk space—the SQL dump can become quite large. To save space here, you may optionally pipe the output through gzip or bzip2 at the cost of a higher CPU load on both the master and the slaves, because they will need to unpack the dump before they can load it, of course. If you open the uncompressed dump file with an editor, you will see a line with a CHANGE MASTER TO statement. This is what --master-data is for. Once the file is imported on a slave, it will know at which point in time (well, rather at which binlog position) this dump was taken. Everything that happened on the master after that needs to be replicated. Finally, we configure that slave to use the credentials set up on the master before to connect and then start the replication. Notice that the CHANGE MASTER TO statement used for that does not include the information about the log positions or file names because that was already taken from the dump file just read in. From here on the slave will go ahead and record all SQL statements sent from the master, store them in its relay logs, and then execute them against the local data set. This recipe is very important because the following recipes are based on this! So in case you have not fully understood the above steps yet, we recommend you go through them again, before trying out more complicated setups.
Read more
  • 0
  • 0
  • 1810
article-image-working-master-pages-aspnet-mvc-2
Packt
17 Jan 2011
6 min read
Save for later

Working with Master Pages in ASP.NET MVC 2

Packt
17 Jan 2011
6 min read
  ASP.NET MVC 2 Cookbook A fast-paced cookbook with recipes covering all that you wanted to know about developing with ASP.NET MVC Solutions to the most common problems encountered with ASP.NET MVC development Build and maintain large applications with ease using ASP.NET MVC Recipes to enhance the look, feel, and user experience of your web applications Expand your MVC toolbox with an introduction to lots of open source tools Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible      How to create a master page In this recipe, we will take a look at how to create a master page and associate it with our view. Part of creating a master page is defining placeholders for use in the view. We will then see how to utilize the content placeholders that we defined in the master page. How to do it... Start by creating a new ASP.NET MVC application. Then add a new master page to your solution called Custom.Master. Place it in the Views/Shared directory. Notice that there is a placeholder already placed in the middle of our page. Let's wrap that placeholder with a table. We will put a column to the left and the right of the existing placeholder. Then we will rename the placeholder to MainContent.Views/Shared/Custom.Master: <table> <tr> <td> </td> <td> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"></asp:ContentPlaceHolder> </td> <td> </td> </tr> </table> Next, we will copy the placeholder into the first and the third columns.Views/Shared/Custom.Master: <table> <tr> <td> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"></asp:ContentPlaceHolder> </td> <td> <asp:ContentPlaceHolder ID="MainContent" runat="server"></asp:ContentPlaceHolder> </td> <td> <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server"></asp:ContentPlaceHolder> </td> </tr> </table> Next, we need to add a new action to the HomeController.cs file, from which we will create a new view. Do this by opening the HomeController.cs file, then add a new action named CustomMasterDemo.Controllers/HomeController.cs: public ActionResult CustomMasterDemo() { return View(); } Then right-click on the CustomerMasterDemo and choose AddView, and select the new Custom.Master page that we created. Next, you need to change the ContentPlaceHolderID box to show the center placeholder name ContentPlaceHolder2. Then hit Add and you should see a new view with four placeholders. Views/Home/CustomMasterDemo.aspx: <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"> <h2>Custom Master Demo</h2> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server"> <meta name="description" content="Here are some keywords for our page description."> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <div style="width:200px;height:200px;border:1px solid #ff0000;"> <ul> <li>Home</li> <li>Contact Us</li> <li>About Us</li> </ul> </div> </asp:Content> <asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder2" runat="server"> <div style="width:200px;height:200px;border:1px solid #000000;"> <b>News</b><br/> Here is a blurb of text on the right! </div> </asp:Content> You should now see a page similar to this: How it works... This particular feature is a server-side carry over from web forms. It works just as it always has. Before being sent down to the client, the view is merged into the master file and processed according to the matching placeholder IDs. Determining the master page in the ActionResult In the previous recipe, we took a look at how to build a master page. In this recipe, we are going to take a look at how to control what master page to use programmatically. There are all sorts of reasons for using different master pages. For example, you might want to use different master pages based on the time of day, if a user is logged in or not, for different areas of your site (blog, shopping, forum, and so on). How to do it... We will get started by first creating a new MVC web application. Next, we need to create a second master page. We can do this quickly by making a copy of the default master page that is provided. Name it Site2.Master. Next, we need to make sure we can tell these two master pages apart. The easiest way to do this is to change the contents of the H1 tag to say Master 1 and Master 2 in each of the master pages. Now we can take a look at the HomeController. We will check if we are in an even or odd second and based on that we can return an even or odd master page. We do this by specifying the master page name that we want to use when we return the view.Controllers/HomeController.cs: public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; string masterName = ""; if (DateTime.Now.Second % 2 == 0) masterName = "Site2"; else masterName = "Site"; return View("Index", masterName); } Now you can run the application. Refreshing the home page should alternate between the two master pages now and then. (Remember that this is based on the second and is now just a pure alternating page scheme.) How it works... This method of controlling which master page is used by the view is built into the MVC framework and is the easiest way of performing this type of control. However, having to dictate this type of logic in every single action would create quite a bit of fluff code in our controller. This option might be appropriate for certain needs though!
Read more
  • 0
  • 0
  • 4061

article-image-integrating-twitter-magento
Packt
14 Jan 2011
2 min read
Save for later

Integrating Twitter with Magento

Packt
14 Jan 2011
2 min read
Integrating your Magento website with Twitter is a useful way to stay connected with your customers. You'll need a Twitter account (or more specifically an account for your business)  but once that's in place it's actually pretty easy. Adding a 'Follow Us On Twitter' button to your Magento store One of the more simple ways to integrate your store's Twitter feed with Magento is to add a 'Follow Us On Twitter' button to your store's design. Generating the markup from the Twitter website Go to the Twitter Goodies website (): Select the Follow Buttons option and then select the Looking for Follow us on Twitter buttons? towards the bottom of the screen: The buttons will now change to the FOLLOW US ON Twitter buttons: Select the style of button you'd like to make use of on your Magento store and then select the generated HTML that is provided in the pop-up that is displayed: The generated HTML for the M2 Store's Twitter account (with the username of M2MagentoStore) looks like the following: <a href="http://www.twitter.com/M2MagentoStore"> <img src="http://twitter-badges.s3.amazonaws.com/follow_us-a.png" alt="Follow M2MagentoStore on Twitter"/> </a> Adding a static block in Magento for your Twitter button Now you will need to create a new static block in the Magento CMS feature: navigate to CMS Static Blocks| in your Magento store's administration panel and click on Add New Block. As you did when creating a static block for the supplier logos used in your store's footer, complete the form to create the new static block. Add the Follow Us On Twitter button to the Content field by disabling the Rich Text Editor with the Show/Hide Editor button and pasting in the markup you generated previously: You don't need to upload an image to your store through Magento's CMS here as the Twitter buttons are hosted elsewhere. Note that the Identifier field reads follow-twitter—you will need this for the layout changes you are about to make!
Read more
  • 0
  • 0
  • 3670
Modal Close icon
Modal Close icon