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

How-To Tutorials - Web Development

1802 Articles
article-image-working-binding-data-and-ui-elements-silverlight-4
Packt
10 May 2010
6 min read
Save for later

Working with Binding data and UI elements in Silverlight 4

Packt
10 May 2010
6 min read
Binding data to another UI element Sometimes, the value of the property of an element is directly dependent on the value of the property of another element. In this case, you can create a binding in XAML called an element binding or element-to-element binding . This binding links both values. If needed, the data can flow bidirectionally. In the banking application, we can add a loan calculator that allows the user to select an amount and the number of years in which they intend to pay the loan back to the bank, including (of course) a lot of interest. Getting ready To follow this recipe, you can either continue with your solution from the previous recipe or use the provided solution that can be found in the Chapter02/SilverlightBanking_ Element_Binding_Starter folder in the code bundle that is available on the Packt website. The finished application for this recipe can be found in the Chapter02/SilverlightBanking_Element_Binding_Completed folder. How to do it... To build the loan calculator, we'll use Slider controls. Each Slider is bound to a TextBlock using an element-to-element binding to display the actual value. Let's take a look at the steps we need to follow to create this binding: We will build the loan calculator as a separate screen in the application. Add a new child window called LoanCalculation.xaml. To do so, right-click on the Silverlight project in the Solution Explorer, select Add | New Item..., and choose Silverlight Child Window under Visual C#. Within MainPage.xaml, add a Click event on the LoanCalculationButton as shown in the following code: <Button x_Name="LoanCalculationButton" Click="LoanCalculationButton_Click" /> In the code-behind's event handler for this Click event, we can trigger the display of this new screen with the following code: private void LoanCalculationButton_Click(object sender, RoutedEventArgs e) { LoanCalculation loanCalculation = new LoanCalculation(); loanCalculation.Show(); } The UI of the LoanCalculation.xaml is quite simple—it contains two Slider controls. Each Slider control has set values for its Minimum and Maximum values (not all UI code is included here; the complete listing can be found in the finished sample code) as shown in the following code: <Slider x_Name="AmountSlider" Minimum="10000" Maximum="1000000" SmallChange="10000" LargeChange="10000" Width="300" > </Slider> <Slider x_Name="YearSlider" Minimum="5" Maximum="30" SmallChange="1" LargeChange="1" Width="300" UseLayoutRounding="True"> </Slider> As dragging a Slider does not give us proper knowledge of where we are exactly between the two values, we add two TextBlock controls. We want the TextBlock controls to show the current value of the Slider control, even while dragging. This can be done by specifying an element-to-element binding as shown in the following code: <TextBlock x_Name="AmountTextBlock" Text="{Binding ElementName=AmountSlider, Path=Value}"> </TextBlock> <TextBlock x_Name="MonthTextBlock" Text="{Binding ElementName=YearSlider, Path=Value}"> </TextBlock> Add a Button that will perform the actual calculation called CalculateButton and a TextBlock called PaybackTextBlock to show the results. This can be done using the following code: <Button x_Name="CalculateButton" Content="Calculate" Click="CalculateButton_Click"> </Button> <TextBlock x_Name="PaybackTextBlock"></TextBlock> The code for the actual calculation that is executed when the Calculate button is clicked uses the actual value for either the Slider or the TextBlock. This is shown in the following code: private double percentage = 0.0345; private void CalculateButton_Click(object sender, RoutedEventArgs e) { double requestedAmount = AmountSlider.Value; int requestedYears = (int)YearSlider.Value; for (int i = 0; i < requestedYears; i++) { requestedAmount += requestedAmount * percentage; } double monthlyPayback = requestedAmount / (requestedYears * 12); PaybackTextBlock.Text = "€" + Math.Round(monthlyPayback, 2); } Having carried out the previous steps, we now have successfully linked the value of the Slider controls and the text of the TextBlock controls. The following screenshot shows the LoanCalculation.xaml screen as it is included in the finished sample code containing some extra markup: How it works... An element binding links two properties of two controls directly from XAML. It allows creating a Binding where the source object is another control. For this to work, we need to create a Binding and specify the source control using the ElementName property. This is shown in the following code: <TextBlock Text="{Binding ElementName=YearSlider, Path=Value}" > </TextBlock> Element bindings were added in Silverlight 3. Silverlight 2 did not support this type of binding. There's more... An element binding can also work in both directions, that is, from source to target and vice versa. This can be achieved by specifying the Mode property on the Binding and setting it to TwoWay. The following is the code for this. In this code, we replaced the TextBlock by a TextBox. When entering a value in the latter, the Slider will adjust its position: <TextBox x_Name="AmountTextBlock" Text="{Binding ElementName=AmountSlider, Path=Value, Mode=TwoWay}" > </TextBox> Element bindings without bindings Achieving the same effect in Silverlight 2—which does not support this feature—is also possible, but only through the use of an event handler as shown in the following code. Element bindings eliminate this need: private void AmountSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { AmountSlider.Value = Math.Round(e.NewValue); AmountTextBlock.Text = AmountSlider.Value.ToString(); } See also Element-to-element bindings can be easily extended to use converters. For more information on TwoWay bindings, take a look at the Using the different modes of data binding to allow persisting data recipe in this article. Binding collections to UI elements Often, you'll want to display lists of data in your application such as a list of shopping items, a list of users, a list of bank accounts, and so on. Such a list typically contains a bunch of items of a certain type that have the same properties and need to be displayed in the same fashion. We can use data binding to easily bind a collection to a Silverlight control (such as a ListBox or DataGrid) and use the same data binding possibilities to defi ne how every item in the collection should be bound. This recipe will show you how to achieve this. Getting ready For this recipe, you can fi nd the starter solution in the Chapter02/SilverlightBanking_ Binding_Collections_Starter folder and the completed solution in the Chapter02/SilverlightBanking_Binding_Collections_Completed folder in the code bundle that is available on the Packt website.
Read more
  • 0
  • 0
  • 4518

article-image-working-dataform-microsoft-silverlight-4
Packt
10 May 2010
9 min read
Save for later

Working with DataForm in Microsoft Silverlight 4

Packt
10 May 2010
9 min read
Displaying and editing an object using the DataForm Letting a user work with groups of related data is a requirement of almost every application. It includes displaying a group of people, editing product details, and so on. These groups of data are generally contained in forms and the Silverlight DataForm (from the Silverlight Toolkit) is just that—a form. In the next few recipes, you'll learn how to work with this DataForm. As of now, let's start off with the basics, that is, displaying and editing the data. Getting ready For this recipe, we're starting with a blank solution, but you do need to install the Silverlight Toolkit as the assemblies containing the DataForm are offered through this. You can download and install it from http://www.codeplex.com/Silverlight/. You can find the completed solution in the Chapter05/Dataform_DisplayAndEdit_Completed folder in the code bundle that is available on the Packt website. How to do it... We're going to create a Person object, which will be displayed through a DataForm. To achieve this, we'll carry out the following steps: Start a new Silverlight solution, name it DataFormExample, and add a reference to System.Windows.Controls.Data.DataForm.Toolkit (from the Silverlight Toolkit). Alternatively, you can drag the DataForm from the Toolbox to the design surface. Open MainPage.xaml and add a namespace import statement at the top of this fi le (in the tag) as shown in the following code. This will allow us to use the DataForm, which resides in the assembly that we've just referenced. Add a DataForm to MainPage.xaml and name it as myDataForm. In the DataForm, set AutoEdit to False and CommandButtonsVisibility to All as shown in the following code: <Grid x_Name="LayoutRoot"> <Grid.RowDefinitions> <RowDefinition Height="40" ></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <TextBlock Text="Working with the DataForm" Margin="10" FontSize="14" > </TextBlock> <df:DataForm x_Name="myDataForm" AutoEdit="False" CommandButtonsVisibility="All" Grid.Row="1" Width="400" Height="300" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Top" > </df:DataForm> </Grid> Add a new class named Person to the Silverlight project having ID, FirstName, LastName, and DateOfBirth as its properties. This class is shown in the following code. We will visualize an instance of the Person class using the DataForm. public class Person { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime DateOfBirth { get; set; } } Open MainPage.xaml.cs and add a person property of the Person type to it. Also, create a method named InitializePerson in which we'll initialize this property as shown in the following code: public Person person { get; set; } private void InitializePerson() { person = new Person() { ID = 1, FirstName = "Kevin", LastName = "Dockx", DateOfBirth = new DateTime(1981, 5, 5) }; } Add a call to InitializePerson in the constructor of MainPage.xaml.cs and set the CurrentItem property of the DataForm to a person as shown in the following code: InitializePerson(); myDataForm.CurrentItem = person; You can now build and run your solution. When you do this, you'll see a DataForm that has automatically generated the necessary fields in order to display a person. This can be seen in the following screenshot: How it works... To start off, we needed something to display in our DataForm: a Person entity. This is why we've created the Person class: it will be bound to the DataForm by setting the CurrentItem property to an object of type Person. Doing this will make sure that the DataForm automatically generates the necessary fi elds. It looks at all the public properties of our Person object and generates the correct control depending on the type. A string will be displayed as a TextBox, a Boolean value will be displayed as a CheckBox, and so on. As we have set the CommandButtonsVisibility property on the DataForm to All, we get an Edit icon in the command bar at the top of the DataForm. (Setting AutoEdit to False makes sure that we start in the display mode, rather than the edit mode). When you click on the Edit icon, the DataForm shows the person in the editable mode (using the EditItemTemplate) and an OK button appears. Clicking on the OK button will revert the form to the regular displaying mode. Do keep in mind that the changes you make to the person are persisted immediately in memory (in the case of a TextBox, when it loses focus). If necessary, you can write extra code to persist the Person object from the memory to an underlying datastore by handling the ItemEditEnded event on the DataForm. There's more... At this moment, we've got a DataForm displaying a single item that you can either view or edit. But what if you want to cancel your edit? As of now, the Cancel button appears to be disabled. As the changes you make in the DataForm are immediately persisted to the underlying object in the memory, cancelling the edit would require some extra business logic. Luckily, it's not hard to do. First of all, you'll want to implement the IEditableObject interface on the Person class, which will make sure that cancelling is possible. As a result, the Cancel button will no longer be disabled. The following code is used to implement this: public class Person : IEditableObject { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime DateOfBirth { get; set; } public void BeginEdit() {} public void CancelEdit() {} public void EndEdit() {} } This interface exposes three methods: BeginEdit, CancelEdit, and EndEdit. If needed, you can write extra business logic in these methods, which is exactly what we need to do. For most applications, you might want to implement only CancelEdit, which would then refetch the person from the underlying data store. In our example, we're going to solve this problem by using a different approach. (You can use this approach if you haven't got an underlying database from which your data can be refetched, or if you don't want to access the database again.) In the BeginEdit method, we save the current property values of the person. When the edit has been cancelled, we put them back to the way they were before. This is shown in the following code: public void BeginEdit() { // save current values tmpPerson = new Person() { ID = this.ID, FirstName = this.FirstName, LastName = this.LastName, DateOfBirth = this.DateOfBirth }; } public void CancelEdit() { // reset values ID = tmpPerson.ID; FirstName = tmpPerson.FirstName; LastName = tmpPerson.LastName; DateOfBirth = tmpPerson.DateOfBirth; } Now, cancelling an edit is possible and it actually reverts to the previous property values. More on DataForm behavior The DataForm exposes various events such as BeginningEdit (when you begin to edit an item), EditEnding (occurs just before an item is saved), and EditEnded (occurs after an item has been saved). It also exposes properties that you can use to defi ne how the DataForm behaves. Validating a DataForm or a DataGrid As you might have noticed, the DataForm includes validation on your fields automatically. For example, try inputting a string value into the ID field. You'll see that an error message appears. This is beyond the scope of this recipe, but more on this will be discussed in the Validating the DataForm recipe. Managing the editing of an object on different levels There are different levels of managing the editing of an object. You can manage this on the control level itself by handling events such as BeginningEdit or ItemEditEnded in the DataForm. Besides that, you can also handle editing on a business level by implementing the IEditableObject interface and providing custom code for the BeginEdit, CancelEdit, or EndEdit methods in the class itself. Depending on the requirements of your application, you can use either of the levels or even both together. See also In this recipe, we've seen how the DataForm is created automatically. For most applications, you require more control over how your fi elds, for example, are displayed. The DataForm is highly customizable, both on a template level (through template customization) and on how the data is generated (through data annotations). If you want to learn about using the DataForm to display or edit a list of items rather than just one, have a look at the next recipe, Displaying and editing a collection using the DataForm. Displaying and editing a collection using the DataForm In the previous recipe, you learned how to work with the basic features of the DataForm. You can now visualize and edit an entity. But in most applications, this isn't enough. Often, you'll want to have an application that shows you a list of items with the ability to add a new item or delete an item from the list. You'll want the application to allow you to edit every item and provide an easy way of navigating between them. A good example of this would be an application that allows you to manage a list of employees. The DataForm can do all of this and most of it is built-in. In this recipe, you'll learn how to achieve this. Getting ready For this recipe, we're starting with the basic setup that we completed in the previous recipe. If you didn't complete that recipe, you can find a starter solution in the Chapter05/ Dataform_Collection_Starter folder in the code bundle that is available on the Packt website. The finished solution for this recipe can be found in the Chapter05/Dataform_ Collection_Completed folder. In any case, you'll need to install the Silverlight Toolkit as the assemblies containing the DataForm are offered through it. You can download and install it from http://www.codeplex.com/Silverlight/.
Read more
  • 0
  • 0
  • 11214

article-image-creating-and-modifying-filters-moodle-19
Packt
06 May 2010
6 min read
Save for later

Creating and Modifying Filters in Moodle 1.9

Packt
06 May 2010
6 min read
Moodle filters modify content from the database as it is output to the screen, thus adding function to the display. An example of this is the multimedia filter, which can detect references to video and audio files, and can replace them with a "mini-player" embedded in the content. How a filter works Before trying to build a filter, it would help to understand how it works. To begin with, any text written to the screen in Moodle should be processed through the format_text function. The purpose of this function is to process the text, such that it is always safe to be displayed. This means making sure there are no security issues and that any HTML used contains only allowed tags. Additionally, the output is run through the filter_text function, and this is the function we are interested in. This function takes the text destined for the screen, and applies all enabled filters to it. The resulting text will be the result of all of these filters. filter_text applies each enabled filter to the text in the order defined in the filter configuration screen (shown in the following screenshot). The order is important; each filter will be fed the output of the previous filter's text. So it is always possible that one filter may change the text in a way that impacts the next filter. Building a filter Now it's time to build our own filter. To begin with, let's come up with a requirement. Let's assume that our organization, called "Learning is Fun", has a main website at http://2fun2learn.org. Now, we need any instance of the phrase learning is fun to be hyperlinked to the website URL every time it appears on the screen, as in the forum post shown in the following screenshots: We can do this by implementing a policy with our content creators that forces them to create hyperlink tags around the phrase every time they write it. However, this will be difficult to enforce and will be fraught with errors. Instead, wouldn't it be easier if the system itself could recognize the phrase and create the hyperlink for us? That's what our filter will do. Getting started We need a name for our filter. It is the name that will be used for the directory the filter will reside in. We want a name that will describe what our filter does and will be unlikely to conflict with any other filter name. Let's call it "learningisfunlink". To start with, create a new subdirectory in the /filter directory and call it learningisfunlink. Next, create a new file called filter.php. This is the only file required for a filter. Open the new filter.php file in your development environment. The filter only requires one function, which is named after the filter name and suffixed with _filter. Add the PHP open and close tags (<?php and ?>), and an empty function called learningisfunlink_filter that takes two arguments: a course ID and the text to filter. When completed, you should have a file that looks like this: <?phpfunction learningisfunlink_filter($courseid, $text) {return $text;}?> We now have the bare minimum required for the filter to be recognized by the system. It doesn't do what we want yet, but it will be present. Creating the language file Log in to the site (that makes use of your new filter) as an administrator. On the main page of your site, look for the Modules Filters| folder in the Site Administration block. Click on the Manage filters link. If you have the default filter setup, you will see your new filter near the bottom of the list, called Learningisfunlink, as shown in the following screenshot: Now, even though the name is reasonably descriptive, it will be better if it were a phrase similar to the others in the list; something like Main website link. To do this, we need to create a new directory in our /filter/learningisfunlink directory called lang/en_utf8/ (the en_utf8 is the language specific part—English in this case). In this directory, we create a new file called filter_learningisfunlink.php. This name is the concatenation of the phrase filter_ and the name of our filter. In this file, we need to add the following line: $string['filtername'] = "Main website link"; This language string defines the text that will be displayed as the name of our filter, replacing the phrase Learningisfunlink that we saw earlier with Main website link. This file will contain any other strings that we may output to the screen, specifically for this filter. Once we have created this file, returning to the Manage filters page should now show our filter with the name that we provided for it in our language file. Creating the filter code We now have a filter that is recognized by the system and that displays the name we want it to. However, we haven't made it do anything. Let's create the code to add some functionality. Remember, what we want this filter to do is to search the text and add a hyperlink pointing to our website for all occurrences of the phrase "learning is fun". We could simply perform a search and replace function on the text and return it, and that would be perfectly valid. However, for the sake of learning more about the Moodle API, we'll use some functions that are set up specifically for filters. To that end, we'll look at two code constructs: the filterobject class and the filter_phrases function, both of which are contained in the /lib/filterlib.php file. The filterobject class defines an object that contains all of the information required by the filter_phrases function to change the text to the way the filter wants it to be. It contains the phrase to be filtered, the tag to start the replacement with, the tag to end the replacement with, whether to match case, whether a full match is required, and any replacement text for the match. An array of filterobjects is sent to the filter_phrases function, along with the text to search in. It's intended to be used when you have a number of phrases and replacements to apply at one time, but we'll use it anyway. Let's initialize our filter strings: $searchphrase = "learning is fun";$starttag = "<a href="http://2fun2learn.org">";$endtag = "</a>"; Now, let's create our filterobject: $filterobjects = array();$filterobjects[] = new filterobject($searchphrase, $starttag, $endtag); Lastly, let's pass the structure to the filter_phrases function, along with the text to be filtered: $text = filter_phrases($text, $filterobjects); Our function now has the code to change any occurrence of the phrase "learning is fun" to a hyperlinked phrase. Let's go test it
Read more
  • 0
  • 0
  • 2576

article-image-vim-72-scripting
Packt
30 Apr 2010
9 min read
Save for later

Vim 7.2 Scripting

Packt
30 Apr 2010
9 min read
Scripting tips In this section, we will look at a few extra tips that can be handy when you create scripts for Vim. Some are simple code pieces you can add directly in your script, while others are good-to-know tips. Gvim or Vim? Some scripts have extra features when used in the GUI version of Vim (Gvim). This could be adding menus, toolbars, or other things that only work if you are using Gvim. So what do you do to check if the user runs the script in a console Vim or in Gvim? Vim has already prepared the information for you. You simply have to check if the feature gui_running is enabled. To do so, you use a function called has(), which returns 1 (true) if a given feature is supported / enabled and 0 (false), otherwise. An example could be: if has("gui_running") "execute gui-only commands here.endif This is all you need to do to check if a user has used Gvim or not. Note that it is not enough to check if the feature "gui" exists, because this will return true if your Vim is just compiled with GUI support—even if it is not using it. Look in :help 'feature-list' for a complete list of other features you can check with the has() function. Which operating system? If you have tried to work with multiple operating systems such as Microsoft Windows and Linux, you will surely know that there are many differences. This can be everything from where programs are placed, to which programs you have available and how access to files is restricted. Sometimes, this can also have an influence on how you construct your Vim script as you might have to call external programs, or use other functionality, specific for a certain operating system. Vim lets you check which operation system you are on, such that you can stop executing your script or make decisions about how to configure your script. This is done with the following piece of code: if has("win16") || has("win32") || has("win64")|| has("win95") " do windows things hereelseif has("unix") " do linux/unix things hereendif This example only shows how to check for Windows (all flavors available) and Linux / Unix. As Vim is available on a wide variety of platforms, you can of course also check for these. All of the operating systems can be found in: :help 'feature-list' Which version of Vim? Throughout the last decade or two, Vim has developed and been extended with a large list of functions. Sometimes, you want to use the newest functions in your script, as these are the best / easiest to use. But what about the users who have a version of Vim that is older than the one you use, and hence don't have access to the functions you use? You have three options: Don't care and let it be the user's own problem (not a good option). Check if the user uses an old version of Vim, and then stop executing the script if this is the case. Check if the user has too old a version of Vim, and then use alternative code. The first option is really not one I would recommend anyone to use, so please don't use it. The second option is acceptable, if you can't work around the problem in the old version of Vim. However, if it is possible to make an alternative solution for the older version of Vim, then this will be the most preferable option. So let's look at how you can check the version of Vim. Before we look at how to check the version, we have to take a look at how the version number is built. The number consists of three parts: Major number (for example, 7 for Vim version 7) Minor number (for example, 3 for Vim version 6.3) Patch number (for example, 123 for Vim 7.0.123) The first two numbers are the actual version number, but when minor features / patches are applied to a version of Vim, it is mostly only the patch number that is increased. It takes quite a bit of change to get the minor number to increase, and a major part of Vim should change in order to increase the major version number. Therefore, when you want to check which version of Vim the user is using, you do it for two versions—major and minor versions and patch number. The code for this could look like: if v:version >= 702 || v:version == 701 && has("patch123") " code here is only done for version 7.1 with patch 123 " and version 7.2 and aboveendif The first part of the if condition checks if our version of Vim is version 7.2 (notice that the minor version number is padded with 0 if less than 10) or above. If this is not the case, then it checks to see if we have a version 7.1 with patch 123. If patch version 124 or above is included, then you also have patch 123 automatically. Printing longer lines Vim was originally created for old text terminals where the length of lines was limited to a certain number of characters. Today, this old limitation shows up once in a while. One place where you meet this limitation of line length is when printing longer lines to the screen using the "echo" statement. Even though you use Vim in a window where there are more than the traditional 80 characters per line, Vim will still prompt you to press Enter after echoing lines longer than 80 characters. There is, however, a way to get around this, and make it possible to use the entire window width to echo on. Window width means the total number of columns in the Vim window minus a single character. So if your Vim window is wide enough to have 120 characters on each line, then the window width is 120-1 characters. By adding the following function to your script, you will be able to echo screen-wide long lines in Vim: " WideMsg() prints [long] message up to (&columns-1) lengthfunction! WideMsg(msg) let x=&ruler | let y=&showcmd set noruler noshowcmd redraw echo a:msg let &ruler=x | let &showcmd=yendfunction This function was originally proposed by the Vim script developer Yakov Lerner on the Vim online community site at http://www.vim.org. Now whenever you need to echo a long line of text in your script, instead of using the echo statement you simply use the function Widemsg(). An example could be: :call WideMsg("This should be a very long line of text") The length of a single line message is still limited, but now it is limited to the width of the Vim window instead of the traditional 80-1 characters. Debugging Vim scripts Sometimes things in your scripts do not work exactly as you expect them to. In these cases, it is always good to know how to debug your script. In this section, we will look at some of the methods you can use to find your error. Well-structured code often has fewer bugs and is also easier to debug. In Vim, there is a special mode to perform script debugging. Depending on what you want to debug, there are some different ways to start this mode. So let's look at some different cases. If Vim just throws some errors (by printing them at the bottom of the Vim window), but you are not really sure where it is or why it happens, then you might want to try to start Vim directly in debugging mode. This is done on the command line by invoking Vim with the -Dargument. vim -D somefile.txt The debugging mode is started when Vim starts to read the first vimrc file it loads (in most cases the global vimrc file where Vim is installed). We will look at what to do when you get into debug mode in a moment. Another case where you might want to get into debug mode is when you already know which function the error (most likely) is in, and hence, just want to debug that function. In that case you just open Vim as normal (load the script with the particular function if needed) and then use the following command: :debug call Myfunction() Here everything after the :debug is the functionality you want to debug. In this case, it is a simple call of the function Myfunction(), but it could just as well be any of the following: :debug read somefile.txt:debug nmap ,a :call Myfunction() <CR>:debug help :debug So let's look at what to do when we get into the debugging mode. When reaching the first line that it should debug, Vim breaks the loading and shows something like: Entering Debug mode. Type "cont" to continue.cmd: call MyFunction()> Now you are in the Vim script debugger and have some choices for what to make Vim do. If you are not familiar with debugging techniques, it might be a good idea to read up on this subject before starting to debug your scripts. The following commands are available in the debugger (shortcuts are in parentheses): cont (c): Continue running the scripts / commands as normal (no debugging) until the next breakpoint (more about this later). quit (q): Quit the debugging process without executing the last lines. interrupt (i): Stop the current process like quit, but go back to the debugger. step (s): Execute the next line of code and come back to the debugger when it is finished. If a line calls a function or sources a file, then it will step into the function / file. next (n): Execute the next command and come back to the debugger when it is finished. If used on a line with a function call, it does not go into the function but steps over it. finish (f): Continue executing the script without stopping on breakpoints. Go into debug mode when done.
Read more
  • 0
  • 0
  • 3295

article-image-scripty2-action
Packt
30 Apr 2010
13 min read
Save for later

Scripty2 in Action

Packt
30 Apr 2010
13 min read
(For more resources on Scripty2, see here.) Introduction to Scripty2 Some years ago the web started to see, with great amazement, the born of many JavaScript libraries. Most of them really helped us developers in working with JavasScript code, making life easier, and coding more fun and efective. Some names that usually come to our minds are jQuery, MooTools, dojo, prototype, and surely many, many others. Among these, surely we can remember one called script.aculo.us. It's not only about the cool name, but the great features it brings along with it. Now Thomas Fuchs, the developer behind script.aculo.us, is announcing a newer version. This time called Scripty2, and most interesting of all, this is a full rewrite, every line of code is new, with a big emphasis on making things better, faster and yet easy to use. The three parts in which Scripty2 is divided is: Core Fx Ui We are going to take a quick glance to Fx and Ui, so you can see some of their impressive features. First steps, downloading and placing the necessary code. In order to download the library we need to go to http://scripty2.com/ here we will see an image just like the next one: Clicking on it will result in the file being downloaded, and when the download finishes, we will be able to unzip it. Inside there are three more folders, and the necessary license documents. These folders are: dist → we can find inside this folder the files we will need for the article. doc → the documentation for the library, equal to the online one, but we can check it while offline. However, it's advisable to check the online documentation when possible, as it will be more up to date. src → here we can find the source files for the library, each part of the library being on a separate file. For the Scripty2 library to work, we will also need to included the prototype library, which is also included in the package. But we have another option, that's to include a file called prototype.s2.min.js. This file includes both libraries in it. Summarizing it, if we want to use the Scripty2 libray we have 2 options, to include both libraries separately or simply include prototype.s2.min.js: <script type="text/javascript" src="js/prototype.js"></script> <script type="text/javascript" src="js/s2.js"></script> Note that we are including the prototype-one first, as Scripty2 needs it. The second option, and the one we are going to follow in this article is: <script type="text/javascript" src="js/prototype.s2.min.js"></script> Now, let's take a look at what will be our base structure, first we will have a index.html file, with this code in it: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xml_lang="es-ES" lang="es-ES" ><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Scripty2</title><link rel="stylesheet" href="css/reset.css" type="text/css" /><link rel="stylesheet" href="css/styles.css" type="text/css" /> </head><body> <script type="text/javascript" src="js/prototype.s2.min.js"></script> </body></html> Note that we have our JavaScript file placed at the end of the code, this is usually better for performance. This JavaScript file is located in a folder called js. We have also included two css files, one styles.css, which is empty for now. And the other one is reset.css . I like to use Eric Meyer's css reset which you can find it here:http://meyerweb.com/eric/tools/css/reset/. And that's all we need for now. We are ready to go, we will start with the UI part. Scripty2 UI The Scripty2 includes some very interesting UI controls, like accordion, tabs, autocompleter and many others. I think we could start with the accordion one, as it will make a nice example. Accordion For this we will need to add some code to our index.html file, a good start would be something like this: <body> <div id="tabs_panel"> <ul> <li><a href="#tab1">Sample tab</a></li> <li><a href="#tab2">Another tab</a></li> <li><a href="#tab3">And another one</a></li> </ul> <div id="tab1">1.- This will be the content for the first tab.</div> <div id="tab2">2.- And here we can find the content for the second one.</div> <div id="tab3">3.- Of course we are adding some content to the third one.</div></div> What have we done here? Just three things: First we have created a tabs_panel div, inside which we will place the necessary code for tabs. It will be our container. Next we have placed three div elements, with a link element inside each one, targeting a div. Inside each link, we find the title for the tab. Finally we have placed the final divs, with the ids corresponding to these ones that where being targeted by the previous links. It will be in these divs that we will place the content for each tab. Once we have this code in place we need something more to do the work, as this alone won't do anything. We need to make the necessary Scripty2 function call: ... <div id="tab3">3.- Of course we are adding some content to the third one.</div> </div> <script type="text/javascript" src="./js/prototype.s2.min.js"></script><script type="text/javascript"> new S2.UI.Tabs('tabs_panel');</script> Easy, isn't it? We just need to add this call new S2.UI.Tabs('tabs_panel'); which targets our previously created div. Would this be enough? Let's take a look: It seems nothing has happened, but that's far from true; if we check our page using Firebug, we will see something like the next image: Want to learn more about Firebug? Check this Packt article: http://www.packtpub.com/article/installation-and-getting-started-with-firebug. As we can see in the image, a whole bunch of css classes have been added to our quite simple html code. These classes are responsible for the tabs to work, does that mean that we have to create all of them? Well, not really. Luckily for us, we can use jQuery UI themes for this. Yes, that's it, just go to this url: http://jqueryui.com/themeroller/ And download your favourite one, from the gallery panel: For example, I'm going to download the Hot sneaks one: Once downloaded, we will be able to find the styles we need, inside the packaged file. If we unzip the file we will see these folders: css development-bundle js index.html Opening the css folder we will see a folder called hot-sneaks, or the name of the theme you have downloaded. We will copy the entire folder into our own css folder. Thus we will have this structure: css hot-sneaks reset.css styles.css Inside the hot-sneaks folder there's a file called jquery-ui-1.8.custom.css , we need to link this file in our index.html one, we will add these modifications: … <title>Scripty2</title> <link rel="stylesheet" href="css/reset.css" type="text/css" /> <link rel="stylesheet" href="css/hot-sneaks/jquery-ui-1.8.custom.css" type="text/css" /> <link rel="stylesheet" href="css/styles.css" type="text/css" /> ... But before taking a look at the result of these changes, we still need to do some modifications, this time in our own styles.css file: body{ padding: 10px; }#tabs_panel{ width:350px; font-size: 12px;} And we are done! Our site will look mostly like this: In the image, we can see the three possible states of the tabs: Normal tab Active tab Hover tab It was easy to achieve, isn't it? Next example will be a text autocompleter, stay with us! Text Autocompleter In this example, we are going to use another of the Scripty2 nice feature, this time to build a text autocompleter. This can be used to enhance site search, and it's pretty easy to achieve, thanks to Scripty2. First we need to add the necessary markup in our index.html file: … <div id="tab3">3.- Of course we are adding some content to the third one.</div> </div> <br/><br/> <div id="text_autocompleter"> <input type="text" name="demo" /> </div>... Not much added here, just another container div, and an input, so we can write in it. We now need our JavasCript code to make this work: new S2.UI.Tabs('tabs_panel'); var favourite = [ 'PHP', 'Ruby', 'Python', '.NET', 'JavaScript', 'CSS', 'HTML', 'Java' ]; new S2.UI.Autocompleter('text_autocompleter', { choices: favourite }); </script> … First what we need to do is to create an array of possible values, and then we call the Autocompleter method, with two parameters, first the div we are targetting, and then the array of values. Also we are going to modify our styles.css file, just to add some styling to our text_autocompleter div: ...#tabs_panel, #text_autocompleter{ width:350px; ... If we check our page after these changes, it will be looking this: If we try to enter some text, like a p in the example, we will see how options appear in the box under the input. If we do click on the option, the input box will be filled: Just after we select our desired option the suggestions panel will disappear, as it will do if we click outside the input box. Note that if the theme we are using lacks the ui-helper-hidden class, the suggestions panel won't dissapear. But don't worry, solving this is as easy as adding this class to our styles.css file: .ui-helper-hidden{    visibility: hidden;    } And we are done, now lets see an example about the accordion control. Accordion This is quite similar to the tabs example, quite easy too, first, as always, we are going to add some html markup to our index.html file: <div id="accordion"> <h3><a href="#">Sample tab</a></h3> <div> 1.- This will be the content for the first tab. </div> <h3><a href="#">Another tab</a></h3> <div> 2.- And here we can find the content for the second one. </div> <h3><a href="#">And another one</a></h3> <div> 3.- Of course we are adding some content to the third one. </div> </div> Good, this will be enough for now. We have a container div, where we are placing the necessary elements, each h3 element, with links inside, will be the headings, and the divs will be the contents for each tab. Let's add some styles in our styles.css file: #tabs_panel, #text_autocompleter, #accordion{ width:350px; font-size: 12px;}#accordion h3 a{ padding-left: 30px; } I've placed the necessary changes in bold. Now to the JavaScript code, we will add this in our index.html file: … new S2.UI.Accordion('accordion'); </script> ... The first parameter will be the id of our container div, for now, we don't need anything more. How does all this look like? Just take a look: Good, clicking on each one of the headings will result in closing the current tab and opening the clicked one. But, what if we want to be able to open each clicked tab, but without closing the others? Well, thanks to Scripty2 we can also achieve that. We only need to make some small modifications to the JavaScript call: …new S2.UI.Accordion('accordion', { multiple: true }); </script> … As we see, the second parameter for our accordion function can receive some options, this time we are selecting multiple to true. This way our accordion tabs won't close: In the previous image we can see all our tabs open, but we have some more options, let's see them. The first one will help us define our prefered header selector. As our code is now we are using h3 elements: <h3><a href="#">Sample tab</a></h3> <div> 1.- This will be the content for the first tab.</div>   But what if we wanted to use h1 elements? Well, it won't be very hard, just a tiny add to our JavaScript code: new S2.UI.Accordion('accordion', { multiple: true, headerSelector: 'h1' }); The last option we are going to see is the icons one, by default, this option will use these values: icons: { header:'ui-icon-triangle-1-e',headerSelected: 'ui-icon-triangle-1-s' } Where do these icons come from? Well, these little icons are from the theme we downloaded, and we have plenty of them to use. If you open the theme package, the one we downloaded at the start of the article, and we click on the index.html file, we will be able to see a demo of all styles included in the package. More or less at the bottom we will see a group of tiny icons:   If we hover over these little icons, its name will appear, and that's what we can use to change our options. So in our index.html file, we could change our JavaScript code just like this: new S2.UI.Accordion('accordion', { multiple: true, headerSelector: 'h1', icons: { header: 'ui-icon-circle-plus', headerSelected: 'ui-icon-circle-minus' } }); We define one option for the headers, and other for the selected one, how will this look like:   And with this option we have seen all the three available. With them we can customize our accordion as we wish. Summarizing, we have found that the Scripty2 library includes some very useful UI controllers. We have seen some of them, but there are many others, such as: Buttons → Scripty2 helps us in creating good looking buttons. Not only normal buttons, but also buttons that behave as checkboxes, or even radio buttons. Dialog → There are also some functions in the Scripty2 library that will help us in creating modal dialog boxes, with the contents we want. Slider → If at anytime we are in need of creating a slider, be it for moving the contents of a div, for creating an image gallery or for creating an interesting price filter, it is pretty easy with Scripty2. Progress bar → This one is pretty interesting, as will help us in the task of developing an animated progress bar, very nice! Now we will be taking a look at another interesting part of the library, the FX one.
Read more
  • 0
  • 0
  • 2315

article-image-vim-72-formatting-code
Packt
30 Apr 2010
11 min read
Save for later

Vim 7.2 Formatting Code

Packt
30 Apr 2010
11 min read
Formatting code often depends on many different things. Each programming language has its own syntax, and some languages rely on formatting like indentation more than others. In some cases, the programmer is following style guidelines given by an employer so that code can follow the company-wide style. So, how should Vim know how you want your code to be formatted? The short answer is that it shouldn't! But by being flexible, Vim can let you set up exactly how you want your formatting done. However, the fact is that even though formatting differs, most styles of formatting follow the same basic rules. This means that in reality, you only have to change the things that differ. In most cases, the changes can be handled by changing a range of settings in Vim. Among these, there are a few especially worth mentioning: Formatoptions: This setting holds formatting-specific settings (see :help 'fo') Comments: What are comments and how they should be formatted (see :help 'co') (no)expandtab: Convert tabs to spaces (see :help 'expandtab') Softtabstop: How many spaces a single tab is converted to (see :help 'sts') Tabstop: How many spaces a tab looks like (see :help 'ts') With these options, you can set nearly every aspect of how Vim will indent your code, and whether it should use spaces or tabs for indentation. But this is not enough because you still have to tell Vim if it should actually try to do the indentation for you, or if you want to do it manually. It you want Vim to do the indentation for you, you have the choice between four different ways for Vim to do it. In the following sections, we will look at the options you can set to interact with the way Vim indents code. Autoindent Autoindent is the simplest way of getting Vim to indent your code. It simply stays at the same indentation level as the previous line. So, if the current line is indented with four spaces, then the new line you add by pressing Enter will automatically be indented with four spaces too. It is then up to you as to how and when the indentation level needs to change again. This type of indentation is particularly good for languages where the indentation stays the same for several lines in a row. You get autoindent by using :set, autoindent, or :set ai. Smartindent Smartindent is the next step when you want a smarter indent than autoindent. It still gives you the indentation from the previous line, but you don't have to change the indentation level yourself. Smartindent recognizes the most common structures from the C programming language and uses this as a marker for when to add / remove the indentation levels. As many languages are loosely based on the same syntax as C, this will work for those languages as well. You get smart indent by using any of the following commands: :set smartindent :set si Cindent Cindent is often called clever indent or configurable indent because it is more configurable than the previous two indentation methods. You have access to three different setup options: cinkeys This option contains a comma-separated list of keys that Vim should use to change the indentation level. An example could be: :set cinkeys="0{,0},0#,:", which means that it should reindent whenever it hits a {, a } or a # as the first character on the line, or if you use : as the last character on the line (as used in switch constructs in many languages).The default value for cinkeys is "0{, 0}, 0), :, 0#, !^F, o, O, and e". See :help cinkeys for more information on what else you can set in this option. cinoptions This option contains all the special options you can set specifically for cindent. A large range of options can be set in this comma-separated list. An example could be:set cinoptions=">2,{3,}3", which means that we want Vim to add two extra spaces to the normal indent length, and we want to place { and } three spaces as compared to the previous line. So, if we have a normal indent to be four spaces, then the previous example could result in the code looking like this (dot marks represent a space): if( a == b) ...{ ......print "hello"; ...} The default value for cinoptions is this quite long string: ">s,e0,n0,f0,{0,}0,^0,:s,=s,l0,b0,gs,hs,ps,ts,is,+s,c3,C0,/0,(2s,us,U0,w0,W0,m0,j0,)20,*30" . See :help 'cinoptions' for more information on all the options. cinwords This option contains all the special keywords that will make Vim add indentation on the next line. An example could be: :set cinwords="if,else,do,while,for,switch", which is also the default value for this option. See :help 'cinwords' for more information. Indentexpr Indentexpr is the most flexible indent option to use, but also the most complex. When used, indentexpr evaluates an expression to compute the indent of a line. Hence, you have to write an expression that Vim can evaluate. You can activate this option by simply setting it to a specific expression such as: :set indentexpr=MyIndenter() Here, MyIndenter() is a function that computes the indentation for the lines it is executed on. A very simple example could be a function that emulates the autoindent option: function! MyIndenter() " Find previous line and get its indentation let prev_lineno = s:prevnonblank(v:lnum) let ind = indent( prev_lineno ) return indendfunction Adding just a bit more functionality than this, the complexity increases quite fast. Vim comes with a lot of different indent expressions for many programming languages. These can serve as inspiration if you want to write your own indent expression. You can find them in the indent folder in your VIMHOME. You can read more about how to use indentexpr in :help 'indentexpr' and :help 'indent-expression'. Fast code-block formatting After you have configured your code formatting, you might want to update your code to follow these settings. To do so, you simply have to tell Vim that it should reindent every single line in the file from the first line to the last. This can be done with the following Vim command: 1G=G If we split it up, it simply says: 1G: Go to the first line of the file (alternatively you can use gg) =: Equalize lines; in other words, indent according to formatting configuration G: Go to the last line in the file (tells Vim where to end indenting) You could easily map this command to a key in order to make it easily accessible: :nmap <F11> 1G=G:imap <F11> <ESC>1G=Ga The last a is to get back into the insert mode as this was where we originally were. So, now you can just press the F11key in order to reindent the entire buffer correctly. Note that if you have a programmatic error, for example, missing a semicolon at the end of a line in a C program, the file will not be correctly indented from that point on in the buffer. This can sometimes be useful to identify where a scope is not closed correctly (for example, a { not closed with a } ). Sometimes, you might just want to format smaller blocks of code. In those cases, you typically have two options—use the natural scope blocks in the code, or select a block of code in the visual mode and indent it. The last one is simple. Go into the visual mode with, for example,Shift+v and then press = to reindent the lines. When it comes to using code blocks on the other hand, there are several different ways to do it. In Vim, there are multiple ways to select a block of code. So in order to combine a command that indents a code block, we need to look at the different types and the commands to select them: i{ Inner block, which means everything between { and } excluding the brackets. This can also be selected with i} and iB. a{ A block, which means all the code between { and } including the brackets. This can also be selected with a} and aB. i( Inner parenthesis, meaning everything between ( and ) excluding the parentheses. Can also be selected with i) and ib. a( A parentheses, meaning everything between ( and ) including the parenthesis. Can also be selected with a) and ab. i< Inner < > block, meaning everything between < and > excluding the brackets. Can also be selected with i>. a< A < > block, meaning everything between < and > including the brackets. Can also be selected with a>. i[ Inner [ ] block, meaning everything between [ and ] excluding the square brackets. Can also be selected with i]. a[ A [ ] block, meaning everything between [ and ], including the square brackets. This can also be selected with a]. So, we have defined what Vim sees a block of code as; now, we simply have to tell it what to do with the block. In our case, we want to reindent the code. We already know that = can do this. So, an example of a code block reindentation could look like this: =i{ Let's execute the code block reindentation in the following code (| being the place where the cursor is): if( a == b ) { print |"a equals b"; } This would produce the following code (with default C format settings): if( a == b ) { print |"a equals b"; } If, on the other hand, we choose to use a { as the block we are working on, then the resulting code would look like this: if( a == b ) { print "a equals b"; } As you can see in the last piece of code, the =a{ command corrects the indentation of both the brackets and the print line. In some cases where you work in a code block with multiple levels of code blocks, you might want to reindent the current block and maybe the surrounding one. No worries, Vim has a fast way to do this. If, for instance, you want to reindent the current code block and besides that want to reindent the block that surrounds it, you simply have to execute the following command while the cursor is placed in the innermost block: =2i{ This simply tells Vim that you will equalize / reindent two levels of inner blocks counting from the "active" block and out. You can replace the number 2 with any number of levels of code blocks you want to reindent. Of course, you can also swap the inner block command with any of the other block commands, and that way select exactly what you want to reindent. So, this is really all it takes to get your code to indent according to the setup you have. Auto format pasted code The trend among programmers tells us that we tend to reuse parts of our code, or so-called patterns. This could mean that you have to do a lot of copying and pasting of code. Most users of Vim have experienced what is often referred to as the stair effect when pasting code into a file. This effect occurs when Vim tries to indent the code as it inserts it. This often results in each new line to be indented to another level, and you ending up with a stair: code line 1 code line 2 codeline 3 code line 4 ... The normal workaround for this is to go into the paste-mode in Vim, which is done by using: :set paste After pasting your code, you can now go back to your normal insert mode again: :set nopaste But what if there was another workaround? What if Vim could automatically indent the pasted code such that it is indented according to the rest of the code in the file? Vim can do that for you with a simple paste command. p=`] This command simply combines the normal paste command (p) with a command that indents the previously inserted lines (=`]). It actually relies on the fact that when you paste with p (lowercase), the cursor stays on the first character of the pasted text. This is combined with `], which takes you to the last character of the latest inserted text and gives you a motion across the pasted text from the first line to the last. So, all you have to do now is map this command to a key and then use this key whenever you paste a piece of code into your file. Using external formatting tools Even though experienced Vim users often say that Vim can do everything, this is of course not the truth—but is close. For those things that Vim can't do, it is smart enough to be able to use external tools. In the following sections, we will take a look at some of the most used external tools that can be used for formatting your code, and how to use them.
Read more
  • 0
  • 0
  • 9219
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 $19.99/month. Cancel anytime
article-image-installing-typo3-extensions
Packt
30 Apr 2010
2 min read
Save for later

Installing TYPO3 Extensions

Packt
30 Apr 2010
2 min read
TYPO3 is one of the most functional and powerful content management systems (CMS). Offering both functionality and expansiveness, TYPO3 is a relevant competitor for commercial solutions. One of the advantages of using TYPO3 is that this CMS has expandability possibilities that are called "extensions". Using these extensions, you can extend the TYPO3 functionality. You can manage shops, galleries, forums, or even a small community portal. You can download extensions from the TYPO3 extension repository (TER): http://typo3.org/extensions. *.t3x is the file format used for extension files. This package is partly compressed using GZIP and it contains the necessary files for the extension (SQL dump, tables, functions, templates, image resources, and so on). This site is a recommended easy way to search for appropriate and suitable extensions. Also, you can find an overview of the extension functionality and additional documentation. For easy extension installation, use its import through Extension Manager. In the extensions section, http://typo3.org/extensions, you'll find the following: New and updated: the latest updated or recently added extensions from the last 20 days—as per the claim on the repository. Popular: a list of the most downloaded extensions on TER. Full list: a complete list of extensions sorted by alphabet. Search: search the form to find an appropriate extension you need. A Search form is also provided in the section New and updated. All the extensions are sorted in groups according to their status: Reviewed extensions: extensions that are secure. These extensions don't affect the normal operation of the system and are qualitative. Alfa: early stage of extension development. Beta: early stage of extension development but operates partly. Stable: stable extension that can be used to provide page functionality. Test: test extension. These kinds of extensions are usually without functionality or are used for concept examples. Obsolete: extensions that are included in the TYPO3 core or are associated with other extensions. For our new shop, we need an eCommerce extension that provides product catalogue and functionality of a shopping cart. You can type shop or commerce in the search area and get a few versions of online shop extensions and those extensions that provide extra functionality to basic extensions. Note the most popular and downloaded online shop extensions: Shop System (tt_products) by Franz Holzinger Webformat Shop System (extendedshop) by Mauro Lorenzutti Commerce (commerce) by Ingo Schmitt, Volker Graubaum, and Thomas Hempel
Read more
  • 0
  • 0
  • 2224

article-image-using-aspnet-master-pages-your-mcms-applications
Packt
29 Apr 2010
6 min read
Save for later

Using ASP.NET Master Pages in your MCMS Applications

Packt
29 Apr 2010
6 min read
Overview and Benefits of Master Pages A master page includes common markup and one or more content placeholders. From this master page, new content pages can be created, which include content controls that are linked to the content placeholders in the master page. This provides an ideal way to separate common site branding, navigation, etc., from the actual content pages, and can significantly decrease duplication and markup errors. Master pages make working with template files a lot easier than before. You can add common markup and shared controls such as headers, footers, and navigation bars to master pages. Once a master page has been built, you can create MCMS template files based upon it. The template files will immediately adopt the look and feel defined in the master template. You can also mark certain regions of the master page to be customizable by introducing content placeholders (note that these are controls designed specifically for master pages and are not to be confused with MCMS placeholder controls). The space marked by content placeholders provides areas where you could add individual template markup as well as MCMS placeholder controls, as shown in the following diagram: Although at first glance both master pages and MCMS templates offer a way to standardize the look and feel of a site, their similarities end there. Don’t be mistaken into thinking that master pages take over the role of MCMS templates completely. A key difference between the two is that the use of master pages is reserved solely for site developers to ensure that template files created have a common look and feel. You can’t create a master page and expect authors to use it to create postings. In fact, master pages work alongside template files and offer a number of benefits to MCMS developers. Avoids duplication in MCMS Template files: Often MCMS templates contain common page layout code (usually an HTML table) along with navigation bars, headers, and footers (usually web user controls). This code has to be copied and pasted into each new template file after it is created or abstracted into user controls. In addition a change in the layout of this common code has to be applied to all template files. So, for example, an MCMS application with ten template files will duplicate this markup ten times. By placing this markup within a master page, this duplication can be removed. Separation of site-wide markup from template markup: One of the biggest drawbacks to MCMS is that the task of developing templates cannot be easily separated. It is a common requirement to separate the tasks of defining site branding, layout, and the development of controls such as navigation (performed by webmasters and programmers) from the task of designing template layouts (performed by business users). While master pages and Visual Studio 2005 do not address this completely due to MCMS’s inherent architecture, they offer a substantial improvement in this area. Avoids issues with MCMS Template File Visual Studio templates: The MCMS Project Item Templates have a number of issues, and do not fully embrace the Visual Studio 2005 project system. Although any web form can be MCMS ‘enabled’, master pages offer a more seamless development experience with less manual tweaks required. Visual Studio 2005 Designer support: One of the common problems with using user controls within template files in Visual Studio .NET is that the template design view doesn't provide an adequate experience for template developers. Visual Studio 2005 offers an improved design-view experience including rendering of user control content, and this is especially valuable when working with master pages. Experience of Master Pages: Just as MCMS is a great way to learn ASP.NET, MCMS SP2 is a great way to learn ASP.NET 2.0! In addition, master pages are a fundamental building block of future Web Content Management offerings from Microsoft. MCMS placeholder controls in the master page will work, but are not officially supported. As we will see in this article, master pages provide an ideal way to separate common site branding, navigation, etc., from the actual content pages, and can significantly decrease duplication and markup errors. The TropicalGreen Web Site Tropical Green is the fictitious gardening society upon which the article’s sample website is based. In the book, Building Websites with Microsoft Content Management Server from Packt Publishing (ISBN 1-904811-16-7), we built the Tropical Green website from scratch using ASP.NET 1.x. In this article series, we will attempt to rebuild parts of the website using MCMS SP2 and ASP.NET 2.0. While the code will be rewritten from the ground-up, we won’t start with a blank database. Instead, we’ll take a shortcut and import the TropicalGreen database objects from the TropicalGreen.sdo file available from the support section on Packt Publishing’s website (http://www.packtpub.com/support). Importing the TropicalGreen Site Deployment Object File Before we begin, let’s populate the database by importing objects using the Site Deployment Manager. Download the TropicalGreen.sdo file. Open Site Manager and log in with an MCMS administrator account. From the menu, select File | Package | Import…. In the Site Deployment Import dialog, click on the Browse… button. Navigate to the TropicalGreen_Final.sdo file downloaded earlier. In the Container Rules tab, set the following: Property Value When Adding Containers Use package container rights When Replacing Containers Keep destination container rights In the Rights Group tab, set the following: Property Value Select how Rights Groups are imported Import User Rights Groups Click on Import. The import confirmation dialog appears. Click on Continue. Creating a New MCMS Web Application To get started, let’s create a new MCMS web application using the project templates we created in the previous article. From Visual Studio, from the File Menu, choose New | Web Site. In the New Web Site dialog, select the MCMS SP2 Web Application icon in the My Templates section. Select HTTP in the Location list box. Enter http://localhost/TropicalGreen in the Location textbox, and click on OK. Our MCMS web application is created and opened in Visual Studio 2005.
Read more
  • 0
  • 0
  • 2999

article-image-django-debugging-overview
Packt
28 Apr 2010
9 min read
Save for later

Django Debugging Overview

Packt
28 Apr 2010
9 min read
Django debug settings Django has a number of settings that control the collection and presentation of debug information. The primary one is named DEBUG; it broadly controls whether the server operates in development (if DEBUG is True) or production mode. In development mode, the end-user is expected to be a site developer. Thus, if an error arises during processing of a request, it is useful to include specific technical information about the error in the response sent to the web browser. This is not useful in production mode, when the user is expected to be simply a general site user. This section describes three Django settings that are useful for debugging during development. Additional settings are used during production to control what errors should be reported, and where error reports should be sent. These additional settings will be discussed in the section on handling problems in production. The DEBUG and TEMPLATE_DEBUG settings DEBUG is the main debug setting. One of the most obvious effects of setting this to True is that Django will generate fancy error page responses in the case of serious code problems, such as exceptions raised during processing of a request. If TEMPLATE_DEBUG is also True, and the exception raised is related to a template error, then the fancy error page will also include information about where in the template the error occurred. The default value for both of these settings is False, but the settings.py file created by manage.py startproject turns both of them on by including these lines at the top of the file: DEBUG = True TEMPLATE_DEBUG = DEBUG Note that setting TEMPLATE_DEBUG to True when DEBUG is False isn't useful. The additional information collected with TEMPLATE_DEBUG turned on will never be displayed if the fancy error pages, controlled by the DEBUG setting, are not displayed. Similarly, setting TEMPLATE_DEBUG to False when DEBUG is True isn't very useful. In this case, for template errors, the fancy debug page will be lacking helpful information. Thus, it makes sense to keep these settings tied to each other, as previously shown. Details on the fancy error pages and when they are generated will be covered in the next section. Besides generating these special pages, turning DEBUG on has several other effects. Specifically, when DEBUG is on: A record is kept of all queries sent to the database. Details of what is recorded and how to access it will be covered in a subsequent section. For the MySQL database backend, warnings issued by the database will be turned into Python Exceptions. These MySQL warnings may indicate a serious problem, but a warning (which only results in a message printed to stderr) may pass unnoticed. Since most development is done with DEBUG turned on, raising exceptions for MySQL warnings then ensures that the developer is aware of the possible issue. The admin application performs extensive validation of the configuration of all registered models and raises an ImproperlyConfigured exception on the first attempt to access any admin page if an error is found in the configuration. This extensive validation is fairly expensive and not something you'd generally want done during production server start-up, when the admin configuration likely has not changed since the last start-up. When running with DEBUG on, though, it is possible that the admin configuration has changed, and thus it is useful and worth the cost to do the explicit validation and provide a specific error message about what is wrong if a problem is detected. Finally, there are several places in Django code where an error will occur while DEBUG is on, and the generated response will contain specific information about the cause of the error, whereas when DEBUG is off the generated response will be a generic error page. The TEMPLATE_STRING_IF_INVALID setting A third setting that can be useful for debugging during development is TEMPLATE_STRING_IF_INVALID. The default value for this setting is the empty string. This setting is used to control what gets inserted into a template in place of a reference to an invalid (for example, non-existent in the template context) variable. The default value of an empty string results in nothing visible taking the place of such invalid references, which can make them hard to notice. Setting TEMPLATE_STRING_IF_INVALID to some value can make tracking down such invalid references easier. However, some code that ships with Django (the admin application, in particular), relies on the default behavior of invalid references being replaced with an empty string. Running code like this with a non-empty TEMPLATE_STRING_IF_INVALID setting can produce unexpected results, so this setting is only useful when you are specifically trying to track down something like a misspelled template variable in code that always ensures that variables, even empty ones, are set in the template context. Debug error pages With DEBUG on, Django generates fancy debug error pages in two circumstances: When a django.http.Http404 exception is raised When any other exception is raised and not handled by the regular view processing code In the latter case, the debug page contains a tremendous amount of information about the error, the request that caused it, and the environment at the time it occurred. The debug pages for Http404 exceptions are considerably simpler. To see examples of the Http404 debug pages, consider the survey_detail view def survey_detail(request, pk): survey = get_object_or_404(Survey, pk=pk) today = datetime.date.today() if survey.closes < today: return display_completed_survey(request, survey) elif survey.opens > today: raise Http404 else: return display_active_survey(request, survey) There are two cases where this view may raise an Http404 exception: when the requested survey is not found in the database, and when it is found but has not yet opened. Thus, we can see the debug 404 page by attempting to access the survey detail for a survey that does not exist, say survey number 24. The result will be as follows: Notice there is a message in the middle of the page that describes the cause of the page not found response: No Survey matches the given query. This message was generated automatically by the get_object_or_404 function. By contrast, the bare raise Http404 in the case where the survey is found but not yet open does not look like it will have any descriptive message. To confirm this, add a survey that has an opens date in the future, and try to access its detail page. The result will be something like the following: That is not a very helpful debug page, since it lacks any information about what was being searched for and why it could not be displayed. To make this page more useful, include a message when raising the Http404 exception. For example: raise Http404("%s does not open until %s; it is only %s" % (survey.title, survey.opens, today)) Then an attempt to access this page will be a little more helpful: Note that the error message supplied with the Http404 exception is only displayed on the debug 404 page; it would not appear on a standard 404 page. So you can make such messages as descriptive as you like and not worry that they will leak private or sensitive information to general users. Another thing to note is that a debug 404 page is only generated when an Http404 exception is raised. If you manually construct an HttpResponse with a 404 status code, it will be returned, not the debug 404 page. Consider this code: return HttpResponse("%s does not open until %s; it is only %s" % (survey.title, survey.opens, today), status=404) If that code were used in place of the raise Http404 variant, then the browser will simply display the passed message: Without the prominent Page not found message and distinctive error page formatting, this page isn't even obviously an error report. Note also that some browsers by default will replace the server-provided content with a supposedly "friendly" error page that tends to be even less informative. Thus, it is both easier and more useful to use the Http404 exception instead of manually building HttpResponse objects with status code 404. A final example of the debug 404 page that is very useful is the one that is generated when URL resolution fails. For example, if we add an extra space before the survey number in the URL, the debug 404 page generated will be as follows: The message on this page includes all of the information necessary to figure out why URL resolution failed. It includes the current URL, the name of the base URLConf used for resolution, and all patterns that were tried, in order, for matching. If you do any significant amount of Django application programming, it's highly likely that at some time this page will appear and you will be convinced that one of the listed patterns should match the given URL. You would be wrong. Do not waste energy trying to figure out how Django could be so broken. Rather, trust the error message, and focus your energies on figuring out why the pattern you think should match doesn't in fact match. Look carefully at each element of the pattern and compare it to the actual element in the current URL: there will be something that doesn't match. In this case, you might think the third listed pattern should match the current URL. The first element in the pattern is the capture of the primary key value, and the actual URL value does contain a number that could be a primary key. However, the capture is done using the pattern d+. An attempt to match this against the actual URL characters—a space followed by 2—fails because d only matches numeric digits and the space character is not a numeric digit. There will always be something like this to explain why the URL resolution failed. For now, we will leave the subject of debug pages and learn about accessing the history of database queries that is maintained when DEBUG is on.
Read more
  • 0
  • 0
  • 6943

article-image-form-validation-codeigniter-17
Packt
26 Apr 2010
8 min read
Save for later

Form Validation with Codeigniter 1.7

Packt
26 Apr 2010
8 min read
Form validation is an important part of any application. Take a look at your favorite web application, notice that there are many forms in these web apps, and it is important that they be secure. It is also important that you have rules that should be adhered to; this also helps to keep a layer of security. In this article by Adam Griffiths, author of CodeIgniter 1.7 Professional Development, you will: Learn how the form validation process works Build a contact form Apply validation rules to the form's input fields Use callbacks to create your own rules We will cover database interaction seperately. (Read more interesting articles on CodeIgniter 1.7 Professional Development here.) Why should I validate my forms? The answer to this question is simple: security. If you simply left your forms bare, with no validation, and then stored this information directly in a database, you are liable to attack. People can simply place in some SQL code and can see a dump of a part or all of your database. By using form validation and creating rules, you will disallow most, if not all, of these practices from occurring. By having set validation rules you can limit the types of data being allowed in your forms. Best of all, the Form Validation Library makes it easy to re-populate your form fields and to show individual errors for each field, making the overall end user experience better; which can mean a lot in an environment with many forms. Even if you are building a contact form, it is a good idea to validate your forms to stop people abusing your form. Using the Form Validation Library In this article, we'll go over a Contact Form and how to use the Form Validation Library methods for validation. The form validation process The Form Validation processes are different for the developers and for users. Read on to see how the user interacts with the forms, as well as how the developer will create the forms. The user's process A form is displayed to the user, who then fills it in and submits it. The Form Validation Library then checks the form against any rules that the developer has set. If an error occurs the library returns these errors and they are shown against the form with the fields re-populated. This process proceeds until a valid form is submitted. The development process You create a form, along with a dynamic value from a form helper function—this will re-populate the data if needed. You will also display individual or global errors in the form view file. You set validation rules, which must be adhered to. Then you check to see if the validation process has been run, and if it has not, you load the form view file. Contact form We validate the form data using the Form Validation Library to complete tasks such as checking for empty fields, validating the e-mail, and then send the e-mail off. All of the code shown should be in the index() function of your email controller. Loading the assets We need to load two libraries for our contact form: the Form Validation Library and the Email class. We can do this in one line, by passing an array to the load->library function. $this->load->library(array('email', 'form_validation')); We also need to load two helpers: the email helper and the form helper. We will do this in the same way as we loaded the two libraries in the previous line of code. $this->load->helper(array('email', 'form')); Setting the rules The next step in using the Form Validation Library is to set the rules for the form. These rules are set and must be adhered to. The way we set rules is by using the set_rules() function of the Form Validation Library. We use the function as follows: $this->form_validation-> set_rules('field_name', 'human_name', 'rules'); As you can see, the function accepts three parameters. The first is the name of the form field that you wish to set the rule for. The second parameter is the name that you wish to be assigned to this, for humans to read. The final parameter is where you pass any validation rules. List of validation rules The following rules are readily available for use: required matches[field_name] min_length[x] max_length[x] exact_length[x] alpha alpha_numeric alpha_dash numeric integer is_natural is_natural_no_zero valid_email valid_emails valid_ip valid_base64 As you can see, some of these rules have a single parameter. The rule matches[] will return TRUE if the field matches the field name passed to it. The min_length[], max_length[], and exact_length[] rules will take an integer as a parameter and check if the minimum length, maximum length respectively, or exact length matches the rule. The rules with no parameters are pretty much self-explanatory. You are able to use more than one rule, simply separate rules with a vertical bar '|' and they will cascade. These rules can also be called as discrete functions. You may also use any native PHP function that accepts one parameter as a rule. $this->form_validation->required($string);$this->form_validation->is_array($string); // native PHP // function as a rule Prepping data We can also use various prepping functions to prep the data before we apply rules to it. Here's a list of the prepping rules that we can perform: xss_clean prep_for_form prep_url strip_image_tags encode_php_tags The first function listed is xss_clean. This basically strips out any code and unwanted characters, and replaces them with HTML entities. The function prep_for_form will convert special characters so that HTML data can be shown in a form without breaking it. The function prep_url will simply add http:// to a URL, if it is missing. The function strip_image_tags will remove image tags, leaving the RAW image URL. The function encode_php_tags will convert PHP tags into entities. You may also use any native PHP function that accepts one parameter as a rule. The rules Now that we know how to set rules and what the rules we can use are, we can go ahead and set the rules necessary for our form. All fields should be required, and the e-mail field should be validated to ensure that the e-mail address is correctly formatted. We also want to run all of the data through the XSS filter. $this->form_validation-> set_rules('name', 'Name', 'required|xss_clean');$this->form_validation-> set_rules('email', 'Email Address', 'required|valid_email|xss_clean');$this->form_validation-> set_rules('subject', 'Subject', 'required|xss_clean');$this->form_validation->set_rules('message', 'Message', 'required|xss_clean'); Check the validation process Instead of checking one of the form field's POST value to check if the form has been submitted, we simply check to see if the Form Validation Library has run. We do this by using the following code: if($this->form_validation->run() === FALSE){ // load the contact form}else // send the email} It's fairly simple: if the Form Validation Library hasn't processed a form, we display the form to the user; if the library has processed a form and there are no errors, we'll send the e-mail off. Sending the email As you'll notice, everything is the same as how we got the field data earlier. $name = $this->input->post('name');$email = $this->input->post('email');$subject = $this->input->post('subject');$message = $this->input->post('message'); $this->email->from($email, $name);$this->email->to('youremail@yourdomain.ext'); $this->email->subject($subject);$this->email->message($message); $this->email->send(); Final controller code Here is the entirety of our controller code: <?phpclass Email extends Controller{function Email(){parent::Controller();} // function Email()function index(){$this->load->library(array('email', 'form_validation'));$this->load->helper(array('email', 'form'));$this->form_validation->set_rules('name', 'Name', 'required|xss_clean');$this->form_validation->set_rules('email', 'Email Address','required|valid_email|xss_clean');$this->form_validation->set_rules('subject', 'Subject', 'required|xss_clean');$this->form_validation->set_rules('message', 'Message', 'required|xss_clean');if($this->form_validation->run() == FALSE){$this->load->view('email'); // load the contact form}else{$name = $this->input->post('name');$email = $this->input->post('email');$subject = $this->input->post('subject');$message = $this->input->post('message');$this->email->from($email, $name);$this->email->to('youremail@yourdomain.ext');$this->email->subject($subject);$this->email->message($message);$this->email->send();}} // function index()} // class Email extends Controller?>
Read more
  • 0
  • 0
  • 4174
article-image-database-interaction-codeigniter-17
Packt
26 Apr 2010
4 min read
Save for later

Database Interaction with Codeigniter 1.7

Packt
26 Apr 2010
4 min read
(Read more interesting articles on CodeIgniter 1.7 Professional Development here.) Loading the library Loading the Database library is slightly different from loading other libraries. This is because it is large and resides in a different folder, unlike the other libraries. $this->load->database(); Performing simple queries Let's dive straight in by starting with the simple stuff. CodeIgniter gives us a function that we can pass a SQL Query to, and the query will be run on the database. Here's how it works: $this->db->query('PUT YOUR SQL HERE'); This function is incredibly simple to use; you simply use this function in place of any native PHP functions you would use to run queries. This function will return TRUE or FALSE for write queries, and will return a dataset for read queries. There is another function that you can use for very simple queries; this will only return TRUE or FALSE. It won't let you cache your query or run the query timer. In most cases you won't want to use this function. $this->db->simple_query('PUT YOUR SQL HERE'); The SQL code that you pass to these functions are database-dependent. Only Active Record queries are independent of any type of Database SQL. Returning values You can assign the function $this->db->query() to a variable. You can then run a number of helper functions on the variable in order to return the data in different formats. Take the following example: $query = $this->db->query('SELECT * FROM 'users''); Return a result object In this case, returning the result will return an array of objects, or an empty array if the query failed. You would usually use this function in a foreach loop. foreach($query->result() as $row){ echo $row->username; echo $row->email;} If your query does not return a result, the CodeIgniter User Guide encourages you to check for a failure before using this function. if($query->num_rows > 0){ foreach($query->result() as $row) { echo $row->username; echo $row->email; }} Returning a result array You are also able to return the result dataset as an array. Typically, you would use this function inside a foreach loop as well. foreach($query->result_array() as $row){ echo $row['username']; echo $row['email'];} Returning a row object If your query is only expected to return a single result, you should return the row by using the following function. The row is returned as an object. if($query->num_rows() > 0){$row = $query->row();echo $row->username;echo $row->email;} You can return a specific row by passing the row number as a digit in the first parameter. $query->row(2); Returning a row array You can return a row as an array, if you prefer. The function is used in the same way as the previous example. if($query->num_rows() > 0){ $row = $query->row_array(); echo $row['username']; echo $row['email'];} You can return a numbered row by passing the digit to the first parameter, also. $query->row_array(2); Result helper functions Besides the helper function that helps to return the dataset in different ways, there are some other more generalized helper functions. Number of rows returned Used in the same way as the other helper functions, this will return the total number of rows returned from a query. Take the following example: echo $query->num_rows(); Number of fields returned Just like the previous function, this will return the number of fields returned by your query. echo $query->num_fields(); Free result This function will remove the resource ID associated with your query, and free the associated memory. PHP will usually do this by default, although when using many queries you may wish to use this to free up memory space. $query->free_result();
Read more
  • 0
  • 0
  • 2561

article-image-data-manipulation-silverlight-4-data-grid
Packt
26 Apr 2010
9 min read
Save for later

Data Manipulation in Silverlight 4 Data Grid

Packt
26 Apr 2010
9 min read
Displaying data in a customized DataGrid Displaying data is probably the most straightforward task we can ask the DataGrid to do for us. In this recipe, we'll create a collection of data and hand it over to the DataGrid for display. While the DataGrid may seem to have a rather fixed layout, there are many options available on this control that we can use to customize it. In this recipe, we'll focus on getting the data to show up in the DataGrid and customize it to our likings. Getting ready In this recipe, we'll start from an empty Silverlight application. The finished solution for this recipe can be found in the Chapter04/Datagrid_Displaying_Data_Completed folder in the code bundle that is available on the Packt website. How to do it... We'll create a collection of Book objects and display this collection in a DataGrid. However,we want to customize the DataGrid. More specifically, we want to make the DataGridfixed. In other words, we don't want the user to make any changes to the bound data or move the columns around. Also, we want to change the visual representation of the DataGrid by changing the background color of the rows. We also want the vertical column separators to be hidden and the horizontal ones to get a different color. Finally, we'll hook into the LoadingRow event, which will give us access to the values that are bound to a row and based on that value, the LoadingRow event will allow us to make changes to the visual appearance of the row. To create this DataGrid, you'll need to carry out the following steps: Start a new Silverlight solution called DatagridDisplayingData in Visual Studio. We'll start by creating the Book class. Add a new class to the Silverlight project in the solution and name this class as Book. Note that this class uses two enumerations—one for the Category and the other for the Language. These can be found in the sample code. The following is the code for the Book class: public class Book { public string Title { get; set; } public string Author { get; set; } public int PageCount { get; set; } public DateTime PurchaseDate { get; set; } public Category Category { get; set; } public string Publisher { get; set; } public Languages Language { get; set; } public string ImageName { get; set; } public bool AlreadyRead { get; set; } } In the code-behind of the generated MainPage.xaml file, we need to create a generic list of Book instances (List) and load data into this collection.This is shown in the following code: private List<Book> bookCollection; public MainPage() { InitializeComponent(); LoadBooks(); } private void LoadBooks() { bookCollection = new List<Book>(); Book b1 = new Book(); b1.Title = "Book AAA"; b1.Author = "Author AAA"; b1.Language = Languages.English; b1.PageCount = 350; b1.Publisher = "Publisher BBB"; b1.PurchaseDate = new DateTime(2009, 3, 10); b1.ImageName = "AAA.png"; b1.AlreadyRead = true; b1.Category = Category.Computing; bookCollection.Add(b1); ... } Next, we'll add a DataGrid to the MainPage.xaml file. For now, we won't add any extra properties on the DataGrid. It's advisable to add it to the page by dragging it from the toolbox, so that Visual Studio adds the correct references to the required assemblies in the project, as well as adds the namespace mapping in the XAML code. Remove the AutoGenerateColumns="False" for now so that we'll see all the properties of the Book class appear in the DataGrid. The following line of code shows a default DataGrid with its name set to BookDataGrid: <sdk:DataGrid x_Name="BookDataGrid"></sdk:DataGrid> Currently, no data is bound to the DataGrid. To make the DataGrid show the book collection, we set the ItemsSource property from the code-behind in the constructor. This is shown in the following code: public MainPage() { InitializeComponent(); LoadBooks(); BookDataGrid.ItemsSource = bookCollection; } Running the code now shows a default DataGrid that generates a column for each public property of the Book type. This happens because the AutoGenerateColumns property is True by default. Let's continue by making the DataGrid look the way we want it to look. By default, the DataGrid is user-editable, so we may want to change this feature. Setting the IsReadOnly property to True will make it impossible for a user to edit the data in the control. We can lock the display even further by setting both the CanUserResizeColumns and the CanUserReorderColumns properties to False. This will prohibit the user from resizing and reordering the columns inside the DataGrid, which are enabled by default. This is shown in the following code: <sdk:DataGrid x_Name="BookDataGrid" AutoGenerateColumns="True" CanUserReorderColumns="False" CanUserResizeColumns="False" IsReadOnly="True"> </sdk:DataGrid> The DataGrid also offers quite an impressive list of properties that we can use to change its appearance. By adding the following code, we specify alternating the background colors (the RowBackground and AlternatingRowBackground properties), column widths (the ColumnWidth property), and row heights (the RowHeight property). We also specify how the gridlines should be displayed (the GridLinesVisibility and HorizontalGridLinesBrushs properties). Finally, we specify that we also want a row header to be added (the HeadersVisibility property ). <sdk:DataGrid x_Name="BookDataGrid" AutoGenerateColumns="True" CanUserReorderColumns="False" CanUserResizeColumns="False" RowBackground="#999999" AlternatingRowBackground="#CCCCCC" ColumnWidth="90" RowHeight="30" GridLinesVisibility="Horizontal" HeadersVisibility="All" HorizontalGridLinesBrush="Blue"> </sdk:DataGrid> We can also get a hook into the loading of the rows. For this, the LoadingRow event has to be used. This event is triggered when each row gets loaded. Using this event, we can get access to a row and change its properties based on custom code. In the following code, we are specifying that if the book is a thriller, we want the row to have a red background: private void BookDataGrid_LoadingRow(object sender, DataGridRowEventArgs e) { Book loadedBook = e.Row.DataContext as Book; if (loadedBook.Category == Category.Thriller) { e.Row.Background = new SolidColorBrush(Colors.Red); //It's a thriller! e.Row.Height = 40; } else { e.Row.Background = null; } } After completing these steps, we have the DataGrid that we wanted. It displays the data (including headers), fixes the columns and makes it impossible for the user to edit the data. Also, the color of the rows and alternating rows is changed, the vertical grid lines are hidden, and a different color is applied to the horizontal grid lines. Using the LoadingRow event, we have checked whether the book being added is of the "Thriller" category, and if so, a red color is applied as the background color for the row. The result can be seen in the following screenshot: How it works... The DataGrid allows us to display the data easily, while still offering us many customization options to format the control as needed. The DataGrid is defined in the System.Windows.Controls namespace, which is located in the System.Windows.Controls.Data assembly. By default, this assembly is not referenced while creating a new Silverlight application. Therefore, the following extra references are added while dragging the control from the toolbox for the first time: System.ComponentModel.DataAnnotations System.Windows.Controls.Data System.Windows.Controls.Data.Input System.Windows.Data While compiling the application, the corresponding assemblies are added to the XAP file (as can be seen in the following screenshot, which shows the contents of the XAP file). These assemblies need to be added because while installing the Silverlight plugin, they aren't installed as a part of the CLR. This is done in order to keep the plugin size small. However, when we use them in our application, they are embedded as part of the application. This results in an increase of the download size of the XAP file. In most circumstances, this is not a problem. However, if the file size is an important requirement, then it is essential to keep an eye on this. Also, Visual Studio will include the following namespace mapping into the XAML file: From then on, we can use the control as shown in the following line of code: <sdk:DataGrid x_Name="BookDataGrid"> </sdk:DataGrid> Once the control is added on the page, we can use it in a data binding scenario. To do so, we can point the ItemsSource property to any IEnumerable implementation. Each row in the DataGrid will correspond to an object in the collection. When AutoGenerateColumns is set to True (the default), the DataGrid uses a refl ection on the type of objects bound to it. For each public property it encounters, it generates a corresponding column. Out of the box, the DataGrid includes a text column, a checkbox column, and a template column. For all the types that can't be displayed, it uses the ToString method and a text column. If we want the DataGrid to feature automatic synchronization, the collection should implement the INotifyCollectionChanged interface. If changes to the objects are to be refl ected in the DataGrid, then the objects in the collection should themselves implement the INotifyPropertyChanged interface. There's more While loading large amounts of data into the DataGrid, the performance will still be very good. This is the result of the DataGrid implementing UI virtualization, which is enabled by default. Let's assume that the DataGrid is bound to a collection of 1,000,000 items (whether or not this is useful is another question). Loading all of these items into memory would be a time-consuming task as well as a big performance hit. Due to UI virtualization, the control loads only the rows it's currently displaying. (It will actually load a few more to improve the scrolling experience.) While scrolling, a small lag appears when the control is loading the new items. Since Silverlight 3, the ListBox also features UI virtualization. Inserting, updating, and deleting data in a DataGrid The DataGrid is an outstanding control to use while working with large amounts of data at the same time. Through its Excel-like interface, not only can we easily view the data, but also add new records or update and delete existing ones. In this recipe, we'll take a look at how to build a DataGrid that supports all of the above actions on a collection of items. Getting ready This recipe builds on the code that was created in the previous recipe. To follow along with this recipe, you can keep using your code or use the starter solution located in the Chapter04/Datagrid_Editing_Data_Starter folder in the code bundle available on the Packt website. The finished solution for this recipe can be found in the Chapter04/Datagrid_Editing_Data_Completed folder.
Read more
  • 0
  • 0
  • 6188

article-image-flash-video-encoding-skinning-and-components-wordpress
Packt
26 Apr 2010
6 min read
Save for later

Flash Video Encoding, Skinning and Components in Wordpress

Packt
26 Apr 2010
6 min read
Encoding with the Adobe Media Encoder If you have a video file, such as an MOV or MP4 file that you want to display as a SWF on the Web, simply encode (or compress) the video file into an FLV. With Flash CS4, you use the Adobe Media Encoder to do this. It can be accessed directly or through Flash's import video function. If you are using an earlier version of Flash, encoding is still possible, and the process is similar. Getting ready Make sure that you have a video file that is compatible with the Adobe Media Encoder. If you do not have a file to use, by all means, use the short.mov file. This file is a clip of the full length summer.mp4 file from www.archive.org that is listed on that website as being in the Public Domain. Use the MOV file because it is a short file, so the time it takes the encoder to render the video will be shorter. This is good for the purposes of learning and practicing. Also, do not worry if you cannot hear any of the sounds. There is nothing wrong with the speakers on your computer. This file does not have audio. How to do it... Open the Adobe Media Encoder: Click on the Add button. Navigate to the file you want to encode, such as short.move, and click on Choose/OK. It is now listed in the queue: Click on the down arrow under Format to select into which file format you will encode the video. Choose FLV | F4V if not already selected. Click on the down arrow under Preset to choose one of the preset export setting options. The default of FLV - Same As Source (Flash 8 and Higher) is generally fine. If you have fewer standard video needs, make a different choice based on your needs. Also, there is an option to Edit Export Settings as well as a Settings button if you want to make your own decisions. See the Edit Export Settings section for more on that. Click on the file name under Output File to select the destination of your encoded file. You can also change the file name. Click on Start Queue, and the encoding process will begin. If you are encoding a long video, you might want to go take a walk or get a cup of tea. For short.mov, just sit tight. It should only take a minute or two to encode. Once encoding is complete, the FLV is saved in the location you chose under the Output File section. There is also a check mark under the encoder's Status section. Now, you can do what you want with the file. For instance, you can take it into Flash and import it into an SWF. How it works... The Adobe Media Encoder encodes the selected video file into the FLV format. It is similar to taking a Photoshop file or a TIFF and compressing either of them into a JPG. The process is simply more involved because the data is more complex. There's more... The Adobe Media Encoder has many options and capabilities. Among these is a wealth of export settings that can be edited to suit your needs. Also available to you is the ability to not only encode multiple files in one sitting but also to duplicate and remove files in your queue. Edit Export Settings With your file selected in the encoder, click on the Settings button. This gives you the Export Settings dialog box: As you can see, it has a lot of options. Only some of the myriad of options will be discussed below. At the top left of the dialog box are two buttons: Source and Output. Source shows the video file you have selected. Output shows a preview of the encoded version of the file. On the bottom/middle left of the Export Settings dialog box, you can address the timeline. You are able to clip the movie if you want to export only part of it; and you can set up cue points. To clip the movie, do the following: Drag the playback head back and forth to manually preview the movie. This helps you find the section you want to keep. Drag the in and out point triangles back and forth to isolate the section you want to keep. The triangle on the left is the in point, and the one on the right is the out point. Everything between the two triangles will be encoded. The timer keeps track of time in milliseconds. The right side of the dialog box allows you to change the desired file format; save your own preset with the button that looks like a computer disk circa 1996. You can also change the file name of the encoded video and choose if you are exporting only video, only audio, or both. The Summary section gives you just that, a summary of your choices thus far. The bottom right section gives you options for putting on a blur filter under the Filter tab and changing the format as applicable under the Format tab. The Video tab lets you choose which Codec to use to encode the video. On2 VP6 is usually the best choice. Stick with that one. It is more advanced, gives better quality, and allows you to encode an Alpha Channel if you have one to encode. Alpha Channels, areas of transparency in video (i.e., green screen), cannot be set up in Flash. They must be set up in a video editing program such as Premiere Pro or Final Cut Pro. The encoder can only honor them, not generate them. If you need to resize your video, check the box for Resize Video, and change the values as needed. If you want to constrain the proportions of your video, leave the chain whole. Frame rate can also be changed here. Generally, it is in your best interest to leave the video set to the same frame rate it was shot in. Same as source is a good choice. For Bitrate Settings, the defaults are usually pretty good. If you want higher quality and can take the additional file size, you can change Encoding Passes to Two. For Advanced Settings, you can change overall quality by selecting either Quality for Speed, Good, or Best. It all depends on your needs. For Audio, if you have it incorporated into your video file, choose Stereo. It sounds better. The only reason to go with Mono is if you have little sound, if it is a video of a talking head, or if your file size needs to be as small as possible. For Bitrate Settings for audio, 128 kb per second is good. Again, only turn this lower if the audio is overly simple, not important, or your file size dictates it. Faster bitrate/higher number gives you better quality sound. When you are finished making changes, click on OK. This gets you back to the encoder. Proceed from here as needed.
Read more
  • 0
  • 0
  • 2042
article-image-moodle-19-theme-design-customizing-header-and-footer-part-1
Packt
23 Apr 2010
7 min read
Save for later

Moodle 1.9 Theme Design: Customizing the Header and Footer (Part 1)

Packt
23 Apr 2010
7 min read
So, let's get on with it... Important preliminary points In order to continue with the exercises in the article, you will need to understand the importance of web browser compatibility. All web browsers are different, and most of them handle HTML and Cascading Style Sheets (CSS) differently. It is not so much that one web browser is better than another or that one web browser is more accurate at rendering HTML or CSS. Rather, it's that CSS rules are often interpreted differently by software developers who designed these browsers. For web developers and designers, this can be very annoying, but an unfortunate and inevitable reality. So, to make sure that the changes that you make to Moodle's theme files are the same or similar across most of the major web browsers, you will need to install various web browsers, such as Firefox, Internet Explorer, Chrome, Opera, Safari, and so on, and make sure that you remember to test your changes. You shall learn to install the required web browsers as you work through this article. Customizing the header One of the first tasks that you will be asked to do concerning Moodle theming is to customize the main Moodle header file. Most people start by learning to change the Moodle logo for one of their own. The file that you will be editing in the first part of this article is the header.html file. For this article, you will assume the standard theme that comes with Moodle. Time for action – making a copy of the standard theme In this exercise, you will be making a copy of the standard theme so that you can make changes to it without interfering with Moodle's theming process. You need to do this because many of the Moodle themes use the standard theme as the base theme. Navigate to the folder: C:Program FilesApache Software FoundationApache 2.2htdocstheme. Right-click on the standard theme folder and choose Copy, as seen in the following screenshot: Right-click again in some empty space and choose Paste. The copied standard theme will be replicated and have the name Copy of standard, as seen below: Right-click on this folder and choose Rename to rename the folder to mytheme. What just happened? You have just made a copy of the standard theme that comes with Moodle and have relocated and renamed the theme, so you can now make some basic changes without interfering with any other themes in the theme directory. Most themes use the standard theme as the parent theme and then build upon this styled theme. So, if you were to change this theme directly, you would probably mess up most of the themes that are installed in your Moodle site. Adding your own logo Now that you have made a copy of the standard theme, you will go on and replace the Moodle logo with your own. Most oft en, your organization will have a logo that you can use; perhaps you could just copy one from their website. An important point to note here is that the logo that you use should be in the GIF or .png format. The following figure has been created with Adobe Photoshop to demonstrate that it would be best to create a very basic logo if you don't have one. Time for action – copying your logo to your mytheme directory Navigate to the location of your logo. Right-click and choose Copy. Navigate to your Moodle site's thememythemepix directory, right-click, and choose Paste. The result should resemble the following screenshot: What just happened? In this very simple exercise, you have copied the logo that you had or created and placed it in the correct directory in your new mytheme directory. This is now ready for you to use in the header.html file to display your logo. Now you will edit the main header.html file to include your new logo. The header.html file can be found in your site's thememytheme directory. Time for action – adding the logo code to your header.html file Navigate to your mytheme directory, right-click on the header.html file, and choose Open With | WordPad. Open the header.html file with your favorite text editor (WordPad, Notepad, Vim, and so on). As a Windows shortcut, you can right-click on the header.html file and choose Open With | WordPad, as seen below: Top Tip – Text editorsWe have chosen WordPad here as it retains the original markup format. Notepad, on the other hand, can be difficult to use, as it lacks some of the functionalities of WordPad. If you already use another text or HTML editor, then please use it. It's about familiarity here, so it's always best to use that with which you feel comfortable. Find the following lines of code: <?php print_container_start(true, '', 'header-home'); ?> <h1 class="headermain"><?php echo $heading ?></h1> <div class="headermenu"><?php echo $menu ?></div><?php print_container_end(); ?> Insert the following line of code: <img src="<?php echo $CFG->themewww .'/'. current_theme() ?>/pix/logo.gif" alt="Institutions Logo" /> Immediately after: <h1 class="headermain"> As shown here: <?php print_container_start(true, '', 'header-home'); ?> <h1 class="headermain"> <img src="<?php echo $CFG->themewww .'/'. current_theme() ?>/pix/logo.gif" alt="Institutions Logo" /> <?php echo $heading ?></h1> <div class="headermenu"><?php echo $menu ?></div><?php print_container_end(); ?> You can download this code from the Packt website. Save and close header.html. Open your web browser and type in the URL of your local Moodle site. Change the current theme, which should be Autumn, to your theme by navigating to Appearance | Themes | Theme Selector and choosing mytheme. You should see something similar to the following screenshot but with your own logo. What just happened? In this exercise, we have learned where a theme's header.html file is and how to open the header.html file for editing. We also learned what part of the code we should change in order to have our own logo appear on the front page of out Moodle site. Have a go hero – adding another logo Again, it's time for you to have a go yourself at changing and modifying some of the things that you have learned through this article. First, it would be a good idea if you would try to create a new logo and add it to the header.html file in your mytheme folder. This time leave the inner page header as it is. Top Tip – Two headersDuring this exercise, you may have noticed that the header.html file has two instances of the following line of code: <h1 class="headermain">. This is because Moodle loads a slightly different header depending on whether you are on the front page or any other page within the site. This means that the changes we have made will only be visible on the front page and not on any other page at the moment. Why don't you go and check this by opening your local Moodle site and clicking on the Logout link in the top right-hand corner and then clicking the Login link in the same place? This will take you to the login front page of Moodle and you will notice that your logo isn't where it is supposed to be. In most situations, we would want to have our logo on all pages within our Moodle site, so we will have to replicate the last exercise and paste our logo code in the other instance of <h1 class="headermain">.
Read more
  • 0
  • 0
  • 2066

article-image-moodle-19-theme-design-customizing-header-and-footer-part-2
Packt
23 Apr 2010
6 min read
Save for later

Moodle 1.9 Theme Design: Customizing the Header and Footer (Part 2)

Packt
23 Apr 2010
6 min read
Customizing the footer Obviously, the second thing that we are going to do after we have made changes to our Moodle header file is to carry on and change the footer.html file. The following tasks will be slightly easier than changing the header logo and title text within our Moodle site, as there is much less code and subsequently much less to change. Removing the Moodle logo The first thing that we will notice about the footer in Moodle is that it has the Moodle logo on the front page of your Moodle site and a Home button on all other pages. In addition to this, there is the login info text that shows who is logged in and a link to log out. More often than not Moodle themers will want to remove the Moodle logo so that they can give their Moodle site its own branding. So let's get stuck in with the next exercise, but don't forget that this logo credits the Moodle community. Time for action – deleting the Moodle logo Navigate to your mytheme directory and right-click on the footer.html file and choose Open With | WordPad. Find the following two lines of code: echo $loggedinas;echo $homelink; Comment out the second line using a PHP comment: echo $loggedinas;/*echo $homelink; */ Save the footer.html file and refresh your browser window. You should now see the footer without the Moodle logo. What just happened? In this exercise, we learned which parts of the PHP code in the footer.html file control where the Moodle logo appears in the Moodle footer. We also learned how to comment out the PHP code that controls the rendering of the Moodle logo so that it does not appear. You could try to put the Moodle logo back if you want. Removing the login info text and link Now that we have removed the Moodle logo, which of course is completely up to you, you might also want to remove the login info link. This link is used exactly like the one in the top right-hand corner of your Moodle site, insofar as it acts as a place where you can log in and log out and provide details of who you logged in as. The only thing to consider here is that if you decide to remove the login info link from the header.html file and also remove it from the footer, you will have no easy way of logging in or out of Moodle. So it is always wise to leave it either in the header or the footer. You might also consider the advantages of having this here as some Moodle pages such as large courses are very long. So, once the user has scrolled way down the page, he/she has a place to log out if needed. The following task is very simple and will require you to go through similar steps as the"deleting the logo" exercise. The only difference is that you will comment out a different line of code. Time for action – deleting the login info text Navigate to your mytheme directory and right-click on the footer.html file and choose Open With | WordPad (or an editor of your choice). Find the following two lines of code: echo $loggedinas;echo $homelink; Comment out the first line by using a PHP comment as shown below: /* echo $loggedinas; */ echo $homelink; Save the footer.html file and refresh your browser window. You will see the footer without the Moodle logo or the login info link. What just happened? In this task, we learned about those parts of the PHP code in the footer.html that control whether the Moodle login info text appears in the Moodle footer similar to the Moodle logo in the previous exercise. We also learned how to comment out the code that controls the rendering of the login info text so that it does not appear. Have a go hero – adding your own copyright or footer text The next thing that we are going to do in this article is to add some custom footer text where the Moodle logo and the login info text were before we removed them. It's completely up to you what to add in the next exercises. If you would like to just add some text to the footer then please do. However, as part of the following tasks we are going to add some copyright text and format it using some very basic HTML. Time for action – adding your own footer text Navigate to your mytheme directory and right-click on the footer.html file and choose Open With | WordPad. At the very top of the file, paste the following text or choose your own footer text to include: My School © 2009/10 All rights reserved. Save the footer.html and refresh your browser. You will see that your footer text is at the bottom of the page on the right-hand side. However, this text is aligned to the left as all text in a browser would be. Open the footer.html file again (if it isn't open already) and wrap the following code around the footer text that you have just added: <div align="right">My School &copy; 2009/10 All rights reserved</div> Save your footer.html file and refresh your browser. You will see that the text is now aligned to the right. What just happened? We just added some very basic footer text to our footer.html file, saved it, and viewed it in our web browser. We have demonstrated here that it is very easy to add our own text to the footer.html file. We have also added some basic HTML formatting to move the text from the left to the right-hand side of the footer. There are other ways to do so, which involve the use of CSS. For instance, we could have given the <div> tag a CSS class and used a CSS selector to align the text to the right. Have a go hero – adding your own footer logo Now try to see if you can edit the footer.html and add the same logo as you have in the header.html in to the footer. Remember that you can put the logo code anywhere outside of a PHP code block. So try to copy the header logo code and paste it into the footer.html. Finally, based on what we have learned, try to align the logo to the right as we did with the footer text.
Read more
  • 0
  • 0
  • 3390
Modal Close icon
Modal Close icon