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

How-To Tutorials

7018 Articles
article-image-tracking-sql-queries-request-using-django
Packt
22 Apr 2010
13 min read
Save for later

Tracking SQL Queries for a Request using Django

Packt
22 Apr 2010
13 min read
For a typical Django application, database interactions are of key importance. Ensuring that the database queries being made are correct helps to ensure that the application results are correct. Further, ensuring that the database queries produced for the application are efficient helps to make sure that the application will be able to support the desired number of concurrent users. Django provides support in this area by making the database query history available for examination. This type of access is useful to see the SQL that is issued as a result of calling a particular model method. However, it is not helpful in learning about the bigger picture of what SQL queries are made during the processing of a particular request. This section will show how to include information about the SQL queries needed for production of a page in the page itself. We will alter our existing survey application templates to include query information, and examine the query history for some of the existing survey application views. Though we are not aware of any problems with the existing views, we may learn something in the process of verifying that they issue the queries we expect. Settings for accessing query history in templates Before the query history can be accessed from a template, we need to ensure some required settings are configured properly. Three settings are needed in order for the SQL query information to be available in a template. First, the debug context processor, django.core.context_processors.debug, must be included in the TEMPLATE_CONTEXT_PROCESSORS setting. This context processor is included in the default value for TEMPLATE_CONTEXT_PROCESSORS. We have not changed that setting; therefore we do not need to do anything to enable this context processor in our project. Second, the IP address of the machine sending the request must be listed in the INTERNAL_IPS setting. This is not a setting we have used before, and it is empty by default, so we will need to add it to the settings file. When testing using the same machine as where the development server runs, setting INTERNAL_IPS to include the loopback address is sufficient: # Addresses for internal machines that can see potentially sensitive # information such as the query history for a request. INTERNAL_IPS = ('127.0.0.1', ) If you also test from other machines, you will need to include their IP addresses in this setting as well. Third and finally, DEBUG must be True in order for the SQL query history to be available in templates. When those three settings conditions are met, the SQL query history may be available in templates via a template variable named sql_queries. This variable contains a list of dictionaries. Each dictionary contains two keys: sql and time. The value for sql is the SQL query itself, and the value for time is the number of seconds the query took to execute. Note that the sql_queries context variable is set by the debug context processor. Context processors are only called during template rendering when a RequestContext is used to render the template. Up until now, we have not used RequestContexts in our survey application views, since they were not necessary for the code so far. But in order to access the query history from the template, we will need to start using RequestContexts. Therefore, in addition to modifying the templates, we will need to change the view code slightly in order to include query history in the generated pages for the survey application. SQL queries for the home page Let's start by seeing what queries are issued in order to generate the survey application home page. Recall that the home page view code is: def home(request): today = datetime.date.today() active = Survey.objects.active() completed = Survey.objects.completed().filter(closes__gte=today- datetime.timedelta(14)) upcoming = Survey.objects.upcoming().filter( opens__lte=today+datetime.timedelta(7)) return render_to_response('survey/home.html', {'active_surveys': active, 'completed_surveys': completed, 'upcoming_surveys': upcoming, }) There are three QuerySets rendered in the template, so we would expect to see that this view generates three SQL queries. In order to check that, we must first change the view to use a RequestContext: from django.template import RequestContext def home(request): today = datetime.date.today() active = Survey.objects.active() completed = Survey.objects.completed().filter(closes__gte=today- datetime.timedelta(14)) upcoming = Survey.objects.upcoming().filter( opens__lte=today+datetime.timedelta(7)) return render_to_response('survey/home.html', {'active_surveys': active, 'completed_surveys': completed, 'upcoming_surveys': upcoming,}, RequestContext(request)) The only change here is to add the RequestContext(request) as a third parameter to render_to_response, after adding an import for it earlier in the file. When we make this change, we may as well also change the render_to_response lines for the other views to use RequestContexts as well. That way when we get to the point of examining the SQL queries for each, we will not get tripped up by having forgotten to make this small change. Second, we'll need to display the information from sql_queries somewhere in our survey/home.html template. But where? We don't necessarily want this information displayed in the browser along with the genuine application data, since that could get confusing. One way to include it in the response but not have it be automatically visible on the browser page is to put it in an HTML comment. Then the browser will not display it on the page, but it can be seen by viewing the HTML source for the displayed page. As a first attempt at implementing this, we might change the top of survey/home.html to look like this: {% extends "survey/base.html" %} {% block content %} <!-- {{ sql_queries|length }} queries {% for qdict in sql_queries %} {{ qdict.sql }} ({{ qdict.time }} seconds) {% endfor %} --> This template code prints out the contents of sql_queries within an HTML comment at the very beginning of the content block supplied by survey/home. html. First, the number of queries is noted by filtering the list through the length filter. Then the code iterates through each dictionary in the sql_queries list and displays sql, followed by a note in parentheses about the time taken for each query. How well does that work? If we try it out by retrieving the survey home page (after ensuring the development server is running), and use the browser's menu item for viewing the HTML source for the page, we might see that the comment block contains something like: <!-- 1 queries SELECT `django_session`.`session_key`, `django_session`.`session_data`, `django_session`.`expire_date` FROM `django_session` WHERE (`django_ session`.`session_key` = d538f13c423c2fe1e7f8d8147b0f6887 AND `django_ session`.`expire_date` &gt; 2009-10-24 17:24:49 ) (0.001 seconds) --> Note that the exact number of queries displayed here will depend on the version of Django you are running. This result is from Django 1.1.1; later versions of Django may not show any queries displayed here. Furthermore, the history of the browser's interaction with the site will affect the queries issued. This result is from a browser that had been used to access the admin application, and the last interaction with the admin application was to log out. You may see additional queries if the browser had been used to access the admin application but the user had not logged out. Finally, the database in use can also affect the specific queries issued and their exact formatting. This result is from a MySQL database. That's not exactly what we expected. First, a minor annoyance, but 1 queries is wrong, it should be 1 query. Perhaps that wouldn't annoy you, particularly just in internal or debug information, but it would annoy me. I would change the template code that displays the query count to use correct pluralization: {% with sql_queries|length as qcount %} {{ qcount }} quer{{ qcount|pluralize:"y,ies" }} {% endwith %} Here, since the template needs to use the length result multiple times, it is first cached in the qcount variable by using a {% with %} block. Then it is displayed, and it is used as the variable input to the pluralize filter that will put the correct letters on the end of quer depending on the qcount value. Now the comment block will show 0 queries, 1 query, 2 queries, and so on. With that minor annoyance out of the way, we can concentrate on the next, larger, issue, which is that the displayed query is not a query we were expecting. Furthermore, the three queries we were expecting, to retrieve the lists of completed, active, and upcoming surveys, are nowhere to be seen. What's going on? We'll take each of these in turn. The query that is shown is accessing the django_session table. This table is used by the django.contrib.sessions application. Even though the survey application does not use this application, it is listed in our INSTALLED_APPS, since it is included in the settings.py file that startproject generates. Also, the middleware that the sessions application uses is listed in MIDDLEWARE_CLASSES. The sessions application stores the session identifier in a cookie, named sessionid by default, that is sent to the browser as soon as any application uses a session. The browser will return the cookie in all requests to the same server. If the cookie is present in a request, the session middleware will use it to retrieve the session data. This is the query we see previously listed: the session middleware is retrieving the data for the session identified by the session cookie sent by the browser. But the survey application does not use sessions, so how did the browser get a session cookie in the first place? The answer is that the admin application uses sessions, and this browser had previously been used to access the admin application. At that time, the sessionid cookie was set in a response, and the browser faithfully returns it on all subsequent requests. Thus, it seems likely that this django_session table query is due to a sessionid cookie set as a side-effect of using the admin application. Can we confirm that? If we find and delete the cookie from the browser and reload the page, we should see that this SQL query is no longer listed. Without the cookie in the request, whatever code was triggering access to the session data won't have anything to look up. And since the survey application does not use sessions, none of its responses should include a new session cookie, which would cause subsequent requests to include a session lookup. Is this reasoning correct? If we try it, we will see that the comment block changes to: <!-- 0 queries --> Thus, we seem to have confirmed, to some extent, what happened to cause a django_session table query during processing of a survey application response. We did not track down what exact code accessed the session identified by the cookie—it could have been middleware or a context processor, but we probably don't need to know the details. It's enough to keep in mind that there are other applications running in our project besides the one we are working on, and they may cause database interactions independent of our own code. If we observe behavior which looks like it might cause a problem for our code, we can investigate further, but for this particular case we will just avoid using the admin application for now, as we would like to focus attention on the queries our own code is generating. Now that we understand the query that was listed, what about the expected ones that were not listed? The missing queries are due to a combination of the lazy evaluation property of QuerySets and the exact placement of the comment block that lists the contents of sql_queries. We put the comment block at the top of the content block in the home page, to make it easy to find the SQL query information when looking at the page source. The template is rendered after the three QuerySets are created by the view, so it might seem that the comment placed at the top should show the SQL queries for the three QuerySets. However, QuerySets are lazy; simply creating a QuerySet does not immediately cause interaction with the database. Rather, sending the SQL to the database is delayed until the QuerySet results are actually accessed. For the survey home page, that does not happen until the parts of the template that loop through each QuerySet are rendered. Those parts are all below where we placed the sql_queries information, so the corresponding SQL queries had not yet been issued. The fix for this is to move the placement of the comment block to the very bottom of the content block. When we do that we should also fix two other issues with the query display. First, notice that the query displayed above has &gt; shown instead of the > symbol that would actually have been in the query sent to the database. Furthermore, if the database in use is one (such as PostgreSQL) that uses straight quotes instead of back quotes for quoting, all of the back quotes in the query would be shown as &quot;. This is due to Django's automatic escaping of HTML markup characters. This is unnecessary and hard to read in our HTML comment, so we can suppress it by sending the sql query value through the safe filter. Second, the query is very long. In order to avoid needing to scroll to the right in order to see the entire query, we can also filter the sql value through wordwrap to introduce some line breaks and make the output more readable. To make these changes, remove the added comment block from the top of the content block in the survey/home.html template and instead change the bottom of this template to be: {% endif %} <!-- {% with sql_queries|length as qcount %} {{ qcount }} quer{{ qcount|pluralize:"y,ies" }} {% endwith %} {% for qdict in sql_queries %} {{ qdict.sql|safe|wordwrap:60 }} ({{ qdict.time }} seconds) {% endfor %} --> {% endblock content %} Now, if we again reload the survey home page and view the source for the returned page, we will see the queries listed in a comment at the bottom: <!-- 3 queries SELECT `survey_survey`.`id`, `survey_survey`.`title`, `survey_survey`.`opens`, `survey_survey`.`closes` FROM `survey_survey` WHERE (`survey_survey`.`opens` <= 2009-10-25 AND `survey_survey`.`closes` >= 2009-10-25 ) (0.000 seconds) SELECT `survey_survey`.`id`, `survey_survey`.`title`, `survey_survey`.`opens`, `survey_survey`.`closes` FROM `survey_survey` WHERE (`survey_survey`.`closes` < 2009-10-25 AND `survey_survey`.`closes` >= 2009-10-11 ) (0.000 seconds) SELECT `survey_survey`.`id`, `survey_survey`.`title`, `survey_survey`.`opens`, `survey_survey`.`closes` FROM `survey_survey` WHERE (`survey_survey`.`opens` > 2009-10-25 AND `survey_survey`.`opens` <= 2009-11-01 ) (0.000 seconds) --> That is good, those look like exactly what we expect to see for queries for the home page. Now that we seem to have some working template code to show queries, we will consider packaging up this snippet so that it can easily be reused elsewhere.
Read more
  • 0
  • 0
  • 11020

article-image-developing-soa-applications-using-pojos
Packt
21 Apr 2010
4 min read
Save for later

Developing SOA Applications using POJOs

Packt
21 Apr 2010
4 min read
GlassFish ESB You may previously have used OpenESB, and if so you will be familiar with GlassFish ESB. GlassFish ESB is simply the OpenESB core runtime, bundled with the GlassFish application server, the NetBeans IDE and some of the more common JBI components already deployed to the ESB. With release 2.2 of GlassFish ESB, the PoJo Service Engine has been included with the software download. Both GlassFish ESB and a number of additional JBI Components can be downloaded from the Open ESB website at: https://open-esb.dev.java.net/Downloads.html. Creating a PoJo and Deploying to GlassFish ESB Using GlassFish ESB, its easy to create PoJos and deploy them to the JBI runtime adding different bindings such as SOAP or REST to it or to deploy them to the BPEL engine and use them as part of a business process. By deploying to GlassFish ESB, we are allowing many different types of client to consume our PoJos. For this article, I'm going to write a simple PoJo that reverses strings and then deploy this to GlasFish ESB with a SOAP binding. This will allow any web service client that supports SOAP to access the PoJo. If you are familiar at all with NetBeans, then creating a PoJo for deployment to the ESB will be a simple matter. The first stage is creating a Java project in which the PoJo can be created. Note that PoJos are created in standard Java projects and not in a SOA project template. Using the "New Project" option in NetBeans, create a new "Java Class Library" project and call it ReversePoJo. Upon creating a standard Java Project, PoJos can be created in the project by using the New PoJo Service menu option under the ESB category. Select this option and create a new PoJo Service as shown below. Class Name: ReversePoJoPackage: com.davidsalter.soa.reversepojoMethod Name: reverseStringInput Argument Type: StringReturn Type: String When we press the Finish button, NetBeans will create an empty PoJo using the details supplied. The code is shown below. @Provider public class ReversePoJo { public ReversePoJo() { } @Operation (outMessageTypeQN="{http://reversepojo.soa.davidsalter.com/ReversePoJo/}ReversePoJoOperationResponse") public String reverseString(String input) { return input; }} Looking at this code, we can see that this is indeed a simple PoJo. The class does not extend any special framework classes and does not need to implement any framework interfaces. We can see however that there are two annotations used on the class which are required to allow us to deploy the class to GlassFish ESB. @Provider defines that the PoJo is a JBI provider, i.e. it provides business logic to other components. In this case, we are stating that the ReversePoJo class can provide business logic to other components, either by adding bindings to the service and exposing directly from the ESB, or being invoked within the ESB from the BPEL runtime. @Operation defines methods in the class that can be consumed - that is methods that other components can invoke. In the simplest case, @Operation methods take a String as a parameter and return a String. More complex types such as org.w3c.dom.Node and javax.jbi.messaging.NormalizedMessage can however be used for both input and output parameters. To implement the reverseString method in this class, add the following implementation. @Operation (outMessageTypeQN="{http://reversepojo.soa.davidsalter.com/ReversePoJo/}ReversePoJoOperationResponse")public String reverseString(String input) { StringBuffer reverse = new StringBuffer(); for (int i = input.length(); i > 0; i--) { reverse.append(input.charAt(i-1)); } return reverse.toString();} This code simply takes the input argument, reverses it and returns it to the caller. One of the benefits of writing PoJos for deployment to the ESB runtime is that the PoJos can be easily tested. Unit tests can be added to a NetBeans project by selecting the Tools | Create Unit Tests menu option in the project explorer. A simple unit test for this class is shown below. public class ReversePoJoTest { public ReversePoJoTest() { } @Test public void testReverseString() { String input = "abcdefg"; ReversePoJo instance = new ReversePoJo(); String expResult = "gfedcba"; String result = instance.reverseString(input); assertEquals(expResult, result); }}
Read more
  • 0
  • 0
  • 1760

article-image-django-debug-toolbar
Packt
20 Apr 2010
9 min read
Save for later

The Django Debug Toolbar

Packt
20 Apr 2010
9 min read
The debug toolbar has a far more advanced way of displaying the information than simply embedding it in HTML comments. The capabilities are best shown by example, so we will immediately proceed with installing the toolbar. Installing the Django Debug Toolbar The toolbar can be found on the Python package index site: https://pypi.python.org/pypi/django-debug-toolbar. Once installed, activating the debug toolbar in a Django project is accomplished with the addition of just a couple of settings. First, the debug toolbar middleware, debug_toolbar.middleware.DebugToolbarMiddleware, must be added to the MIDDLEWARE_CLASSES setting. The documentation for the toolbar notes that it should be placed after any other middleware that encodes the response content, so it is best to place it last in the middleware sequence. Second, the debug_toolbar application needs to be added to INSTALLED_APPS. The debug_toolbar application uses Django templates to render its information, thus it needs to be listed in INSTALLED_APPS so that its templates will be found by the application template loader. Third, the debug toolbar requires that the requesting IP address be listed in INTERNAL_IPS. Finally, the debug toolbar is displayed only when DEBUG is True. We've been running with debug turned on, so again we don't have to make any changes here. Note also that the debug toolbar allows you to customize under what conditions the debug toolbar is displayed. It's possible, then, to set things up so that the toolbar will be displayed for requesting IP addresses not in INTERNAL_IPS or when debug is not turned on, but for our purposes the default configuration is fine so we will not change anything. One thing that is not required is for the application itself to use a RequestContext in order for things such as the SQL query information to be available in the toolbar. The debug toolbar runs as middleware, and thus is not dependent on the application using a RequestContext in order for it to generate its information. Thus, the changes made to the survey views to specify RequestContexts on render_to_response calls would not have been needed if we started off first with the Django Debug Toolbar. Debug toolbar appearance Once the debug toolbar is added to the middleware and installed applications settings, we can see what it looks like by simply visiting any page in the survey application. Let's start with the home page. The returned page should now look something like this: Note this screenshot shows the appearance of the 0.8.0 version of the debug toolbar. Earlier versions looked considerably different, so if your results do not look like this you may be using a different version than 0.8.0. The version that you have will most likely be newer than what was available when this was written, and there may be additional toolbar panels or functions that are not covered here. As you can see, the debug toolbar appears on the right-hand side of the browser window. It consists of a series of panels that can be individually enabled or disabled by changing the toolbar configuration. The ones shown here are the ones that are enabled by default. Before taking a closer look at some of the individual panels, notice that the toolbar contains an option to hide it at the top. If Hide is selected, the toolbar reduces itself to a small tab-like indication to show that it is present: This can be very useful for cases where the expanded version of the toolbar obscures application content on the page. All of the information provided by the toolbar is still accessible, after clicking again on the DjDT tab; it is just out of the way for the moment. Most of the panels will provide detailed information when they are clicked. A few also provide summary information in the main toolbar display. As of debug toolbar version 0.8.0, the first panel listed, Django Version, only provides summary information. There is no more detailed information available by clicking on it. As you can see in the screenshot, Django 1.1.1 is the version in use here. Note that the current latest source version of the debug toolbar already provides more information for this panel than the 0.8.0 release. Since 0.8.0, this panel has been renamed to Versions, and can be clicked to provide more details. These additional details include version information for the toolbar itself and for any other installed Django applications that provide version information. The other three panels that show summary information are the Time, SQL, and Logging panels. Thus, we can see at a glance from the first appearance of the page that 60 milliseconds of CPU time were used to produce this page (111 milliseconds total elapsed time), that the page required four queries, which took 1.95 milliseconds, and that zero messages were logged during the request. In the following sections, we will dig into exactly what information is provided by each of the panels when clicked. We'll start first with the SQL panel, since it is one of the most interesting and provides the same information (in addition to a lot more). The SQL panel If we click on the SQL section of the debug toolbar, the page will change to: At a glance, this is a much nicer display of the SQL queries for the page than what we came up with earlier. The queries themselves are highlighted so that SQL keywords stand out, making them easier to read. Also, since they are not embedded inside an HTML comment, their content does not need to be altered in any way—there was no need to change the content of the query containing the double dash in order to avoid it causing display problems. (Now would probably be a good time to remove that added query, before we forget why we added it.) Notice also that the times listed for each query are more specific than what was available in Django's default query history. The debug toolbar replaces Django's query recording with its own, and provides timings in units of milliseconds instead of seconds. The display also includes a graphical representation of how long each query took, in the form of horizontal bars that appear above each query. This representation makes it easy to see when there are one or more queries that are much more expensive than the others. In fact, if a query takes an excessive amount of time, its bar will be colored red. In this case, there is not a great deal of difference in the query times, and none took particularly long, so all the bars are of similar length, and are colored gray. Digging deeper, some of the information we had to manually figure out earlier in this article is just a click away on this SQL query display. Specifically, the answer to the question of what line of our code triggered a particular SQL query to be issued. Each of the displayed queries has a Toggle Stacktrace option, which when clicked will show the stack trace associated with the query: Here we can see that all queries are made by the home method in the survey views. py file. Note that the toolbar filters out levels in the stack trace that are within Django itself, which explains why each of these has only one level shown. The first query is triggered by Line 61, which contains the filter call added to test what will happen if a query containing two dashes in a row was logged. The remaining queries are all attributed to Line 66, which is the last line of the render_to_response call in the home view. These queries, as we figured out earlier, are all made during the rendering of the template. (Your line numbers may vary from those shown here, depending on where in the file various functions were placed.) Finally, this SQL query display makes available information that we had not even gotten around to wanting yet. Under the Action column are links to SELECT, EXPLAIN, and PROFILE each query. Clicking on the SELECT link shows what the database returns when the query is actually executed. For example: Similarly, clicking on EXPLAIN and PROFILE displays what the database reports when asked to explain or profile the selected query, respectively. The exact display, and how to interpret the results, will differ from database to database. (In fact, the PROFILE option is not available with all databases—it happens to be supported by the database in use here, MySQL.) Interpreting the results from EXPLAIN and PROFILE is beyond the scope of what's covered here, but it is useful to know that if you ever need to dig deep into the performance characteristics of a query, the debug toolbar makes it easy to do so. We've now gotten a couple of pages deep into the SQL query display. How do we get back to the actual application page? Clicking on the circled >> at the upper-right of the main page display will return to the previous SQL query page, and the circled >> will turn into a circled X. Clicking the circled X on any panel detail page closes the details and returns to displaying the application data. Alternatively, clicking again on the panel area on the toolbar for the currently displayed panel will have the same effect as clicking on the circled symbol in the display area. Finally, if you prefer using the keyboard to the mouse, pressing Esc has the same effect as clicking the circled symbol. Now that we have completely explored the SQL panel, let's take a brief look at each of the other panels provided by the debug toolbar. The Time panel Clicking on the Time panel brings up more detailed information on where time was spent during production of the page: The total CPU time is split between user and system time, the total elapsed (wall clock) time is listed, and the number of voluntary and involuntary context switches are displayed. For a page that is taking too long to generate, these additional details about where the time is being spent can help point towards a cause. Note that the detailed information provided by this panel comes from the Python resource module. This is a Unix-specific Python module that is not available on non-Unix-type systems. Thus on Windows, for example, the debug toolbar time panel will only show summary information, and no further details will be available.
Read more
  • 0
  • 0
  • 5833

article-image-handling-invalid-survey-submissions-django
Packt
20 Apr 2010
5 min read
Save for later

Handling Invalid Survey Submissions with Django

Packt
20 Apr 2010
5 min read
What would make a survey submission invalid? The only likely error case for our QuestionVoteForm is if no answer is chosen. What happens, then, if we attempt to submit a survey with missing answers? If we try it, we see that the result is not ideal: There are at least two problems here. First, the placement of the error messages, above the survey questions, is confusing. It is hard to know what the first error message on the page is referring to, and the second error looks like it is associated with the first question. It would be better to move the error messages closer to where the selection is actually made, such as between the question and answer choice list. Second, the text of the error message is not very good for this particular form. Technically the list of answer choices is a single form field, but to a general user the word field in reference to a list of choices sounds odd. We will correct both of these errors next. Coding custom error message and placement Changing the error message is easy, since Django provides a hook for this. To override the value of the error message issued when a required field is not supplied, we can specify the message we would like as the value for the required key in an error_messages dictionary we pass as an argument in the field declaration. Thus, this new definition for the answer field in QuestionVoteForm will change the error message to Please select an answer below: class QuestionVoteForm(forms.Form): answer = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=None, empty_label=None, error_messages={'required': 'Please select an answer below:'}) Changing the placement of the error message requires changing the template. Instead of using the as_p convenience method, we will try displaying the label for the answer field, errors for the answer field, and then the answer field itself, which displays the choices. The {% for %} block that displays the survey forms in the survey/active_survey.html template then becomes: {% for qform in qforms %} {{ qform.answer.label }} {{ qform.answer.errors }} {{ qform.answer }}{% endfor %} How does that work? Better than before. If we try submitting invalid forms now, we see: While the error message itself is improved, and the placement is better, the exact form of the display is not ideal. By default, the errors are shown as an HTML unordered list. We could use CSS styling to remove the bullet that is appearing (as we will eventually do for the list of choices), but Django also provides an easy way to implement custom error display, so we could try that instead. To override the error message display, we can specify an alternate error_class attribute for QuestionVoteForm, and in that class, implement a __unicode__ method that returns the error messages with our desired formatting. An initial implementation of this change to QuestionVoteForm and the new class might be: class QuestionVoteForm(forms.Form): answer = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=None, empty_label=None, error_messages={'required': 'Please select an answer below:'}) def __init__(self, question, *args, **kwargs): super(QuestionVoteForm, self).__init__(*args, **kwargs) self.fields['answer'].queryset = question.answer_set.all() self.fields['answer'].label = question.question self.error_class = PlainErrorListfrom django.forms.util import ErrorListclass PlainErrorList(ErrorList): def __unicode__(self): return u'%s' % ' '.join([e for e in sefl]) The only change to QuestionVoteForm is the addition of setting its error_class attribute to PlainErrorList in its __init__ method. The PlainErrorList class is based on the django.form.util.ErrorList class and simply overrides the __unicode__ method to return the errors as a string with no special HTML formatting. The implementation here makes use of the fact that the base ErrorList class inherits from list, so iterating over the instance itself returns the individual errors in turn. These are then joined together with spaces in between, and the whole string is returned. Note that we're only expecting there to ever be one error here, but just in case we are wrong in that assumption, it is safest to code for multiple errors existing. Although our assumption may never be wrong in this case, it's possible we might decide to re-use this custom error class in other situations where the single possible error expectation doesn't hold. If we code to our assumption and simply return the first error in the list, this may result in confusing error displays in some situations where there are multiple errors, since we will have prevented reporting all but the first error. If and when we get to that point, we may also find that formatting a list of errors with just spaces intervening is not a good presentation, but we can deal with that later. First, we'd like to simply verify that our customization of the error list display is used.
Read more
  • 0
  • 0
  • 3241

article-image-animation-silverlight-4
Packt
20 Apr 2010
8 min read
Save for later

Animation in Silverlight 4

Packt
20 Apr 2010
8 min read
Silverlight sports a rich animation system that is surprisingly easy to use. The animation model in Silverlight is time based, meaning that movements occur based on a set timeline. At the heart of every animation is a StoryBoard, which contains all the animation data and independent timeline. Silverlight controls can contain any number of Storyboards. StoryBoards contain one or more Key frame elements, which are responsible for making objects on screen change position, color, or any number of properties. There are four general types of Key frames in Silverlight 4: Linear, Discrete, Spline, and Easing. The table below illustrates what each one does: Very different than Flash The animation model in Silverlight is markedly different than the one found in Adobe Flash. Animations in Flash are frame-based, whereas in Silverlight they are time-based. The term StoryBoard comes from the motion picture industry, where scenes are drawn out before they are filmed. Time for action – animation time The client would like to transform their text-only logo into something a little more elaborate. The designers have once again given us a XAML snippet of code exported from their graphic design tool. We will need to do the following: Open up the CakeORama logo project in Blend. Blend should have automatically loaded the MainControl.xaml file and your screen should look like this: In the Objects and Timeline tab, you'll see a list of objects that make up this vector drawing. There is Path object for every character. Let's add an animation. On the Object and Timeline tab, click the plus sign (+) to create a new StoryBoard. In the Create Storyboard Resource dialog, type introAnimationStoryboard into the text box and click OK. You'll notice a couple of changes to your screen. For one, the art board is surrounded by a red border and a notification that: intoAnimationStoryboard timeline recording is on just like in this screenshot: If you take a look at the Objects and Timeline tab, you'll see the timeline for our newly created introAnimationStoryboard: Let's add a key frame at the very beginning. The vertical yellow line is the play head, which marks where you currently are in the timeline. Select the canvas1 object. You can switch to the Animation Workspace in Blend by pressing F6. Click on the square icon with a green plus sign to create a new Key frame here at position 0. A white oval appears representing the Key frame that you just created. It should look similar to the following screenshot: Move the play head to 0.7 seconds, by clicking on the tick mark to the immediate left of the number 1. Click the same button you did in step 9 to create a new key frame here so that your timeline looks like this: Move the play head back to zero. Make sure the canvas1 object is still selected, click and drag the logo graphic up, so that all of it is in the grey area. This moves the logo "off stage". Hit the play button highlighted in the below screenshot, to preview the animation and enjoy the show! Now all we need to do is tell Silverlight to run the animation when our control loads, but first we need to get out of recording mode. To do this, click the x button on the Objects and Timeline tab. Click on [UserControl] in the Objects and Timeline tab. On the Properties tab, you'll see an icon with a lightning bolt on it. Click on it to see the events associated with a UserControl object: To wire up an event handler for the Loaded event, type UserControl_Loaded in the text box next to Loaded, as shown in the next screenshot: Once you hit Enter, the code behind will immediately pop up with your cursor inside the event handler method. Add this line of code to the method: introAnimationStoryboard.Begin(); Run the solution via the menu bar or by pressing F5. You should see the logo graphic smoothly and evenly animate into view. If for some reason the animation doesn't get displayed, refresh the page in your browser. You should see it now. What just happened? You just created your first animation in Silverlight. First you created a Storyboard and then added a couple of Key frames. You changed the properties of the canvas on one key frame and Silverlight automatically interpolated them in between points to create a nice smooth animation. If your animation didn't show up on the initial page load but did when you reloaded the page, then you've just experienced how seriously the Silverlight animation engine respects time. Since our animation length is relatively short (0.7 seconds) it's possible that more than that amount of time elapsed from the call of the Begin method, to the amount of time it took for your computer to render it. Silverlight noticed that and "jumped" ahead to that part of the timeline to keep everything on schedule. Just like we did before, let's take a look at the XAML to get a better feel of what's really going on. You'll find the Storyboard XAML in the UserControl.Resources section towards the top of the document. Don't worry if the values are slightly different in your project: <Storyboard x_Name="introAnimationStoryboard"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="canvas1" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"><EasingDoubleKeyFrame KeyTime="00:00:00" Value="-229"/><EasingDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0"/> </DoubleAnimationUsingKeyFrames><DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="canvas1" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"><EasingDoubleKeyFrame KeyTime="00:00:00" Value="1"/><EasingDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0"/> </DoubleAnimationUsingKeyFrames></Storyboard> There are a couple of things going on here, so let's dissect the animation XAML starting with the Storyboard declaration which creates a Storyboard and assigns the name we gave it in the dialog box: <Storyboard x_Name="introAnimationStoryboard"> That's easy enough, but what about the next node? This line tells the Storyboard that we will be modifying a Double value starting at 0 seconds. It also further specifies a target for our animation: canvas1 and a property on our target: <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="canvas1" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"> Clear enough, but what does the TargetProperty value mean? Here is that value highlight below. (UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y) We know that the net effect of the animation is that the logo moves from above the visible area back to its original position. If we're familiar with X, Y coordinates, where X represents a horizontal coordinate and Y a vertical coordinate, then the TranslateTransform.Y part makes sense. We are changing or, in Silverlight terms, transforming the Y property of the canvas. But what's all this TransformGroup about? Take a look at our canvas1 node further down in the XAML. You should see the following lines of XAML that weren't there earlier: <Canvas.RenderTransform> <TransformGroup> <ScaleTransform /> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup></Canvas.RenderTransform> Blend automatically inserted them into the Canvas when we created the animation. They have no properties. Think of them as stubbed declarations of these objects. If you remove them, Silverlight will throw an exception at runtime like the one below complaining about not being able to resolve TargetProperty: Clearly this code is important, but what's really going on here? The TranslateTransform object is a type of Transform object which determines how an object can change in Silverlight. They are packaged in a TransformGroup, which can be set in the RenderTransform property on any object descending from UIElement, which is the base class for any kind of visual element. With that bit of knowledge, we now see that (TransformGroup.Children)[3] refers to the fourth element in a zero-based collection. Not so coincidentally, the TranslateTransform node is the fourth item inside the TransformGroup in our XAML. Changing the order of the transforms in the XAML will also cause an exception at runtime. That line of XAML just tells the Silverlight runtime that we're going to animation, now we tell it how and when with our two EasingDoubleKeyFrame nodes: <EasingDoubleKeyFrame KeyTime="00:00:00" Value="-229"/><EasingDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0"/> The first EasingDoubleKeyFrame node tells Silverlight that, at zero seconds, we want the value to be -229. This corresponds to when the logo was above the visible area. The second EasingDoubleKeyFrame node tells Silverlight that at 0.7 seconds, we want the value of the property to be 0. This corresponds to the initial state of the logo, where it was before any transformations were applied. Silverlight handles all changes to the value in between the start and the end point. Silverlight's default frame rate is 60 frames per second, but Silverlight will adjust its frame rate based on the hardware that it is running on. Silverlight can adjust the amount by which it changes the values to keep the animation on schedule. If you had to reload the web page to see the animation run, then you've already experienced this. Once again, notice how few lines (technically only one line) of procedural code you had to write.
Read more
  • 0
  • 0
  • 1938

article-image-customizing-kubrik-wordpress
Packt
19 Apr 2010
5 min read
Save for later

Customizing Kubrik with Wordpress

Packt
19 Apr 2010
5 min read
Getting ready The first step is to make a list of the changes that you want to make. Here's what we've come up with: Increase width to 980px Increase font sizes in sidebar Use a graphic header We've picked 980px as our target width because this size is optimized for a 1024 screen resolution and works well in a grid layout. Several CSS adjustments will be necessary to realize this modification, as well as using an image editing program (we will be using Photoshop). How to do it... To increase the page width, the first step is to determine which entries in the CSS stylesheet are controlling the width. Using Firebug to inspect the page (as seen below), we find that the selector #page has a value of 760px for the width property. And #header has a width of 758px (less because there is a 1px left margin). The .narrowcolumn selector gives the main content column a width of 450px. And #sidebar has a width of 190px. Finally, #footer has a width of 760px. So, we will increase #page and #footer to 980px. #header we will increase to 978px. Let's apply all of the additional 220px width to .narrowcolumn. Taking note of the existing 45px left margin, our new value for the width property will be 700px. That means #sidebar width will remain at 190px, but the margin-left will need to be increased from 545px to 765px. Click on Appearance | Editor. In the right-hand column, below the Templates heading, click on style.css. Scroll past the section that says /* Begin Typography & Colors */, until you get to the section that says /* Begin Structure */. Make the following changes to the stylesheet (style.css), commenting as appropriate to document your changes. #page { background-color: white; margin: 20px auto; padding: 0; width: 980px; /* increased from 760px */ border: 1px solid #959596; }#header { background-color: #73a0c5; margin: 0 0 0 1px; padding: 0; height: 200px; width: 978px; /* increased from 758px */ }.narrowcolumn { float: left; padding: 0 0 20px 45px; margin: 0px 0 0; width: 700px; /* increased from 450px */ }#sidebar {margin-left:765px; /* increaseed from 545px */padding:20px 0 10px;width:190px;}#footer { padding: 0; margin: 0 auto; width: 980px; /* increased from 760px */ clear: both; } Adjustments via Photoshop We'll also need to use an image editing program to modify the three background images that create the rounded corners: kubrikbg-ltr.jpg, kubrickheader.jpg, and kubrickfooter.jpg. In this example, we modify kubrik-ltr.jpg (the background image for #page), a 760px image. Open up the image in Photoshop, select all, copy, create a new document (with a white or transparent background), and paste (Ctrl-A, Ctrl-C, Ctrl-N, Ctrl-V). Increase the canvas size (Image | Canvas Size) to 980px, keeping the image centered on the left-hand side by clicking on the left-pointing arrow. Select one half of the image with the Rectangular Marquee Tool, cut and paste. Use the Move Tool to drag the new layer to the right-hand side of the canvas. In this case, it does not matter if you can see the transparent background or if your selection was exactly one half the image. Since the middle of the image is simply a white background, we are really only concerned with the borders on the left and right. The following screenshot shows the background image cut in half and moved over: Save for Web and Devices, exporting as a jpg. Then, replace the existing kubrikbgltr.jpg with your modified version via FTP. The steps are similar for both kubrickheader.jpg and kubrickfooter.jpg. Increase the canvas size and copy/paste from the existing image to increase the image size without stretching or distortion. The only difference is that you need to copy and paste different parts of the image in order to preserve the background gradient and/or top and bottom borders. In order to complete our theme customization, the width of .widecolumn will need to be increased from 450px to 700px (and the 150px margin should be converted to a 45px margin, the same as .narrowcolumn). Also, the kubrikwide.jpg background image will need to be modified with an image editing program to increase the size from 760px to 980px. Then, the individual post view will look as good as the homepage. By following the same steps as above, you should now be prepared to make this final customization yourself. Our next goal is to increase the sizes of the sidebar fonts. Firebug helps us to pinpoint the relevant CSS. #sidebar h2 has a font-size of 1.2em (around line 123 of style.css). Let's change this to 1.75em. #sidebar has font-size of 1em. Let's increase this to 1.25em. To use a graphic in the header, open up kubrickheader.jpg in a new Photoshop document. Use the magic wand tool to select and delete the blue gradient with rounded corners. Now, use the rounded rectangle tool to insert your own custom header area. You can apply another gradient, if desired. We choose to apply a bevel and emboss texture to our grey rectangle. Then, to paste in some photos, decreasing their opacity to 50%. In a short time, we've been able to modify Kubrik by re-writing CSS and using an image-editing program. This is the most basic technique for theme modification. Here is the result:
Read more
  • 0
  • 0
  • 4924
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-bar-reports-zabbix-18
Packt
16 Apr 2010
9 min read
Save for later

Bar Reports in Zabbix 1.8

Packt
16 Apr 2010
9 min read
Bar reports is the most sophisticated built-in data visualization tool in the Zabbix frontend. As such, they are also quite intimidating, thus we will create a couple of reports with all three different bar report types. Bar reports provide more customization options, but they can also take a lot of time to set up. Let's see what reports are available at Reports | Bar reports—see the Reports dropdown at the upper-right corner. As we can see, three report types are available, but it's not trivial to guess by their names which is useful in which situation, so we'll try to apply each of them. Distribution of values for multiple periods This is the first report and there's no need to switch to another, so dismiss the dropdown by clicking in the Title textfield and enter Comparing network traffic there. Let's start by getting some output from the report—click on Add in the Items section. This opens the item configuration dialog, in which you should click the Select button next to the Parameter field. In the upcoming list, find the Incoming traffic on interface eth0 item next to A Test Host and click on it. We won't change any other details, so click on Add. Getting a report as soon as possible was our main goal, right? Let's click on Show. Now that's useless and ugly. There surely must be some way to make this report useful... Take a look at the Scale option—it is currently set to Weekly. If we compare that to the values in the Period section, they are set to one day, thus there's no wonder we got a single huge block. Looking at the Scale dropdown, we can see possible scales of hourly, daily, weekly, monthly, and yearly. Our displayed period is one day, so select Hourly in this dropdown, then click Show to refresh the report. That's way better. Except maybe the x-axis labels... This again is a minor bug in Zabbix version 1.8.1. Now let's add another item—click Add in the Items section and again click on Select next to the Parameter field. Find the item Incoming traffic on interface eth0, but this time for Another Host, and click on it. Change the color for this item by clicking on the colored rectangle and choosing some shade of blue, then click Add. The report is immediately updated and now it looks more useful, we can compare amount of data transmitted for each hour for both hosts. Now, which host had which color? We should enable the legend here, mark the checkbox next to Legend title and click on Show. Let's look at the legend. That's not helpful. As both items have the same name, they can't be distinguished in the legend—that has to be fixed. In the item list, click on the first item that has the green color chosen. Notice how this dialog looks very similar to the graph item configuration. We also have choice of axis, color, and function. But there's one additional feature, though—look at the first option, Caption. As we saw, the one inserted by default doesn't work that well here, so we will have to change it. Enter in the field A Test Host, then click Save. Now click on the bluish color item, and enter Another Host in that textfield, then click Save. What does the legend look like now? Wonderful, that can finally be used to figure out which entry belongs to which host. We can still improve this report a bit. Enter Hourly distribution in the X Label field and Incoming traffic in the Y Label field. The final result should look like this: When you are done, click Show. Our report appears below with labels for axis added. With the help of this report it is quite easy to spot busy hours (or days, or weeks, or months, or years depending on what period and scale you choose) or compare data from several items. This is especially useful with many items, as custom graphs become unreadable with many items. Of course, there are practical limits to how many items can be compared with this bar report, but they are still much easier to read than normal graphs. Ability to choose scale allows for a layout that's better suited to spot important information or make a point. As there are no limits to hosts that items come from, it's possible to create a report that examines several items from a single host or a single item from multiple hosts, or a mix of these in arbitrary combinations. Distribution of values for multiple items We found out what the first report does, and it's time to move to the second one. In the Reports dropdown select Distribution of values for multiple items. This report has a more simple form, at least it looks like that initially. Let's get to creating a new report—enter Comparing CPU Load in the Title field. Now we have to add periods and items. This will be confusing at first, but you'll get the idea when you see the result. Let's start with adding some item. Click on Add in the Items section, then Select next to the Parameter field in the upcoming pop up. Choose CPU Load for A Test Host, then click Add. We should now have an item added like this: Now is the time to move to the time periods. Our test installation probably doesn't have huge amounts of data gathered, so we'd be safer choosing smaller time periods like hours. Click on Add in the Period section, which opens period entering form. Now, set your current date in both date fields and set the latest passed full hour in the Till field time selection, and one hour before in the From field. If your current time is 14:50, that would mean you would use 14:00 for the Till field time value and 13:00 for the From field time value. It would look something like this: When you are done, click Add. We have to add more periods for this report, so click Add in the Period section again. In the period details form set current date just like before, and this time set one hour period just before the previously added period. If you previously added a period of 13:00-14:00, now add 12:00-13:00. Choose another color and click Add. Now repeat this process three more times, each time setting the period one hour before and using a different color. Remember to use current date in both fields as well. Don't worry if you make a mistake. You can easily click any of the added periods and fix it. When you are finished, take a rest, then click Show button. Oh shiny. While your output will look different depending on color choices and actual CPU loads, you'll notice how we can easily compare CPU loads for each defined time period. Sort of. We can observe here the same problem as with the previous report, we can't quite figure out which period is which, so mark checkbox next to the Legend title and click Show. Take a look at the legend. That helped, now we can see which time period each bar represents. The legend is somewhat too verbose though. We know this is a single date and that each period is one hour, so it would be enough if each legend entry would simply list the starting hour. As with the previous report, we can customize captions, so click on the first entry in the Period section. Enter the starting hour in the Caption field (the one in the From field) for this particular period, for example, 13:00, then click Update. Now for some tedious work, do the same with all other periods. Now our legend is more readable and takes up considerably less space as well. But we have only added a single item so far, let's add some more. Again, click on Add in the Items section and click on Select next to the Parameter field in the upcoming pop up. This time, choose CPU Load for Another Host, then click Add. The report is immediately updated and another block for the newly added item appears. We can now see how the load compares during each period for each item (in this case, same item for different hosts). Oh, but we have again hit the same problem as before—the block titles are identical, so we don't even know which host is which. Luckily, for this report we can enter custom titles both for periods and for items. Click on the first item and enter A Test Host in the Caption field, then click Save. Click on the second item and enter Another Host in the Caption field, then click Save. There is one more minor polish we could add; enter CPU Load in the Y Label textfield. The final configuration should look similar to this: If it does, click Show. Our report appears with all the options set and seems to be quite readable. While our test installation does not have that much data, this report is useful for large scale comparisons of data—for example, comparing data with periods spanning a year. Smaller periods can be useful to extract seasonal or other periodic patterns. For example, one could create a report with 12 periods, you guessed it,one for each month and observe how seasonal changes impact data. Such a report is much more readable than common graph. We saw how this report looks like with single item, but would it also be useful with single period? Let's find out. Select all but one checkbox in the Period section and click the Delete selected button just below them. Well, those are huge blocks. But it should be clear now that single period configuration is also very useful. We could create a report on a compile farm, comparing the loads of all involved machines during some specific compilation job or compare the amount of Apache processes started on many web servers. Notice one more option appearing in report configuration, which you might have noticed disappear when we added second period—Sort by. We have a choice to sort either by name or by value. Name, obviously, will sort alphabetically, while value will sort by each item's value in ascending order. You'll be able to easily figure out which systems are overloaded and which are way too idle, for example.
Read more
  • 0
  • 0
  • 5783

article-image-manipulation-dom-objects-using-firebug
Packt
16 Apr 2010
3 min read
Save for later

Manipulation of DOM Objects using Firebug

Packt
16 Apr 2010
3 min read
Inspecting DOM The DOM inspector allows for full, in-place editing of our document structure, not just text nodes. In the DOM inspector, Firebug auto completes property value when we press the Tab key. The following are the steps to inspect an element under the DOM tab: Press Ctrl+Shift+C—the shortcut key to open Firebug in inspect mode. Let's move the mouse pointer over the HTML element that we want to inspect and click on that element. The HTML script of that element will be shown in Firebug's HTML tab. Right-clicking on the selected DOM element will open a context menu. Let's select the Inspect in DOM Tab option from the context menu. As soon as we do that, Firebug will take us to its DOM tab. Filtering properties, functions, and constants Many times we want to analyze whether a function written by us is associated with an HTML element. Firebug provides us an easy way to figure out whether an event, listener, function, property, or constants are associated with a particular element. The DOM tab is not only a tab but also a drop-down menu. When we click on the down arrow icon on the DOM tab, Firebug will show a drop-down list from which one can select the filtering options and inspect the element thoroughly. The following are the options provided by this menu: Show User-defined Properties Show User-defined Functions Show DOM Properties Show DOM Functions Show DOM Constants Refresh There are two kinds of objects and functions: Part of the standard DOM Part of our own JavaScript code Firebug can notify the difference, and shows us our own script-created objects and functions in bold at the top of the list. The text that is bold and green is a user-defined function. The text that is bold and black is a user-defined property. The text whose size is normal and is green in color is a DOM-defined function. The text whose size is normal and is black in color is a DOM-defined property. The upper case letters (capital letters) are the DOM constants. We can see the actual colored depiction in Firebug's DOM tab. In the following code, the onkeyup() event is a user-defined function for <input/> and calculatefactorial() is a user-defined function for the current window. To test this code, let's type the code in an HTML file, open it with Firefox, and enable Firebug by pressing the F12 key. Inspect the input element in the DOM. <html><head><script>function calculateFactorial(num,event){if(event.keyCode!=13){return;}var fact=1;for(i=1;i<=num;i++){fact*=i;}alert ("The Factorial of "+ num + " is: " +fact)}</script><title>code_6_1.html.html</title></head><body><font face="monospace">Enter a number to calculate its factorial<input type = "text" name="searchBox" onkeyup="calculateFactorial(this.value,event)"/></font></body></html> Intuitive DOM element summariesThere are many different kinds of DOM and JavaScript objects, and Firebug does its best to visually distinguish each, while providing as much information as possible. When appropriate, objects include brief summaries of their contents so that we can see what's there without having to click. Objects are color coded so that HTML elements, numbers, strings, functions, arrays, objects, and nulls are all easy to distinguish.
Read more
  • 0
  • 0
  • 3508

article-image-video-blogging-wordpress
Packt
16 Apr 2010
7 min read
Save for later

Video Blogging in Wordpress

Packt
16 Apr 2010
7 min read
Introduction Video is a major component of the Web today. Luckily, WordPress makes it easy to publish and share video. In this article, we will demonstrate ways of working with video in WordPress and in Flash. You will learn how to embed an .flv file, create an .xml video sitemap, and distribute your videos to sites such as YouTube and Blip. We will also show you how to set up Free WP Tube, a free video blogging theme that allows you to run a video web log (vlog). FLV Embed (Version 1.2.1) If you want to embed .flv files, use a Flash video player, and/or publish a video sitemap, this compact plugin does all three. The homepage is http://www.channel-ai.com/blog/plugins/flv-embed/. FLV Embed uses standards compliant, valid XHTML, and JavaScript. It is based on the JW FLV Media Player, whose homepage is http://www.longtailvideo.com/players/jw-flvplayer/ FLV Embed supports Google video sitemap generation, allowing you to describe, syndicate, and distribute your video content, facilitating indexing in Google video search. If a user is missing Flash or has disabled JavaScript, he or she is provided unobtrusive and appropriate on-screen instructions to correct the problem. Getting ready When a page with video loads, the player displays either the first frame of the video or a thumbnail (referred to as a poster image). The poster image is preferable, especially when a user is choosing between many videos—the first frame of a video may not offer the most representative or compelling description. Your poster image can be a poster or any image you like. Here is an example of our finished product: You will want to think about where you will upload the video files and poster images and,how you will name them. A good place might be wp-content/uploads/video. This plugin requires that you name your poster images the same as your video files. The default image type is jpg, but you can use any valid image file format. All your images must be in the same file format. A batch resize and rename utility is a useful tool. For PC, one free option is the Fast Stone Image Resizer, which you can download at http://www.faststone.org/FSResizerDetail.htm. How to do it... In your dashboard, navigate to Plugins | Add New. Search for "FLV Embed". Click on Install, then on Activate. Visit the plugin configuration panel at Settings | FLV Embed. In the Sitemap menu, check the first box to Enable sitemap feature and automatic custom field addition. FLV Embed will now be able to create your video sitemap by automatically adding a custom field each time you use FLV Embed to insert a video. In the Poster menu, check the box to Display poster image for embedded FLV movies. For both of the fields, Path to poster directory and Path to FLV directory, we suggest you leave these blank, and instead use absolute URLs. If you do use relative (site-specific) URLs, keep in mind that a trailing slash is required. An example is /wp-content/uploads/videos/. In the Player menu, you may want to change the colors or add your site logo as a linkable watermark to the video. Review all the Settings, and click on Save Changes. To embed an FLV file, use the following shortcode in HTML view: [flv:url width height]. For example, you could insert a YouTube video at 480 by 360 (using the absolute URL) like this: [flv:http://youtube.com/watch?v=fLV3MB3DpWN 480 360] A YouTube video cannot use a poster image because the file name of a jpg cannot contain a question mark. You can also insert an FLV that you have uploaded (using the relative path) like this: [flv:http://www.wordpressandflash.com/wp-content/uploads/video/swfobject_test.swf 480 360] Once you have inserted the video, FLV Embed automatically populates the FLV custom field with two URLs, as you can see below. The first is the location of the video, and the second is the location of the poster image: To use a custom poster image, upload any image to wp-content/uploads/video, and rename it to match the filename. You can also use an absolute URL if the poster image file is in another location—the filename must still match. To configure your video XML sitemap, visit the Video Sitemap Options menu by clicking on Settings | Video Sitemap. Here, you can get or modify the feed address. Our example is http://www.wordpressandflash.com/ videofeed.xml You can also adjust additional optional settings, and if you have made any changes to the settings or content and need to rebuild the sitemap or update your custom fields, you can do that here too. How it works... The video sitemap is an extension of the XML sitemap. A video sitemap allows you to publish and syndicate online video content, including descriptive metadata to tag your content for Google Video search. Adding details, such as a title and description, makes it easier for users who are searching to find a given piece of content. Your poster image will also be included as a clickable thumbnail image. The user will be directed to your website to see the video. If FLV Embed cannot automatically generate the XML file, you can simply copy the XML file from the demo and save it to your server. Make sure to set the file permissions to write (664 or 666) by context-clicking in your FTP client and modifying the File Attributes, as seen below: Then, make the appropriate changes to the Video sitemap filename field in the Video Sitemap Options menu, directing the plugin to the XML file you have prepared, and rebuild the sitemap. Here is what your finished feed will look like: There's more... The videofeed.xml file has a simple structure. The first three tags specify encoding, styling, and the video sitemap protocol: <?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl"href="http://www.wordpressandflash.com/wp-content/plugins/flv-embed/sitemap.xsl"?><urlset > Next, a <url> tag wraps each piece of content, which includes a <loc> tag (a link to the content on your site) and a <videogt; tag. The <videogt; tag contains additional tags that specify the video location, the video player location, the poster image location, a title, and description: <url> <loc>http://www.wordpressandflash.com/flv-embed/</loc> <video:video> <video:content_loc>http://www.wordpressandflash.com/wp-content/uploads/video/swfobject_test.swf</video:content_loc> <video:player_loc allow_embed="No">http://www.wordpressandflash.com/wp-content/plugins/flv-embed/flvplayer.swf?file=/wp-content/uploads/video/swfobject_test.swf</video:player_loc> <video:thumbnail_loc>http://www.wordpressandflash.com/wp-content/uploads/videos/swfobject_test.jpg</video:thumbna il_loc> <video:title><![CDATA[FLV Embed]]></video:title> <video:description><![CDATA[FLV Embed is a great plugin thatallows you to display FLV files &#8212; and most other video formats&#8212; in a compact Flash video player. Visit the homepage at:http://www.channel-ai.com/blog/plugins/flv-embed/. Check out thevideo sitemap!Get the latest Flash Player to see this player.[Javascript required to view Flash movie, please turn it [...]]]></video:description> </video:video></url></urlset> With this info, you can manually create a .xml video feed for any site, without a plugin. Commercial use? Commercial use does require a license. A free alternative for commercial use is the Hana FLV Player, whose homepage is http://www.neox.net/w/2008/05/25/hana-flv-playerwordpress-plugin/.
Read more
  • 0
  • 0
  • 2734

article-image-understanding-expression-blend-and-how-use-it-silverlight-4
Packt
16 Apr 2010
5 min read
Save for later

Understanding Expression Blend and How to Use it with Silverlight 4

Packt
16 Apr 2010
5 min read
Creating applications in Expression Blend What we've done so far falls short of some of the things you may have already seen and done in Silverlight. Hand editing XAML, assisted by Intellisense, works just fine to a point, but to create anything complex requires another tool to assist with turning our vision into code. Intellisense is a feature of Visual Studio and Blend that auto-completes text when you start typing a keyword, method, or variable name. Expression Blend may scare off developers at first with its radically different interface, but if you look more closely, you'll see that Blend has a lot in common with Visual Studio. For starters, both tools use the same Solution and Project file format. That means it's 100% compatible and enables tighter integration between developers and designers. You could even have the same project open in both Visual Studio and in Blend at the same time. Just be prepared to see the File Modified dialog box like the one below when switching between the two applications: If you've worked with designers on a project before, they typically mock up an interface in a graphics program and ship it off to the development team. Many times, a simple graphic embellishment can cause us developers to develop heartburn. Anyone who's ever had to implement a rounded corner in HTML knows the special kind of frustration that it brings along. Here's the good news: those days are over with Silverlight. A crash course in Expression Blend In the following screenshot, our CakeNavigationButton project is loaded into Expression Blend. Blend can be a bit daunting at first for developers that are used to Visual Studio as Blend's interface is dense with a lot of subtle cues. Solutions and projects are opened in Blend in the same manner as you would in Visual Studio. Just like in Visual Studio, you can customize Expression Blend's interface to suit your preference. You can move tabs around, dock, and undock them to create a workspace that works best for you as the following screenshot demonstrates: If you look at the CakeNavigationButton project, on the left hand side of the application window, you have the toolbar, which is substantially different from the toolbox in Visual Studio. The toolbar in Blend more closely resembles the toolbar in graphics editing software such as Adobe Photoshop or Adobe Illustrator. If you move the mouse over each button, you will see a tooltip that tells you what that button does, as well as the button's keyboard shortcut. In the upper-left corner, you'll notice a tab labeled Projects. This is functionally equivalent to the Solution Explorer in Visual Studio. The asterisk next to MainPage.XAML indicates that the file has not been saved. Examine the next screenshot to see Blend's equivalent to Visual Studio's Solution Explorer: If we look at the following screenshot, we find the Document tab control and the design surface, which Blend calls the art board. On the upper-right of the art board, there are three small buttons to control the switch between Design view, XAML view, or Split view. On the lower edge of the art board, there are controls to modify the view of the design surface. You can zoom in to take a closer look, turn on snap grid visibility, and turn on or off the snapping to snap lines.   If we then move to the upper-right corner of the next screen, we will see the Properties tab, which is a much more evolved version of the Properties tab in Visual Studio. As you can see in this screenshot, the color picker has a lot more to offer. There's also a search feature that narrows down the items in the tab based on the property name you type in.   At the lower left side of the next screen, there is the Objects and Timeline view, which shows the object hierarchy of the open document. Since we have the MainPage.XAML of our CakeNavigationButtons project, the view has StackPanel with six Buttons all inside a grid named LayoutRoot inside of a UserControl. Clicking on an item in this view selects the item on the art board and vice versa. Expression Blend is an intricate and rich application. Time for action – styles revisited Earlier in this chapter, we created and referenced a style directly in the XAML in Visual Studio. Let's modify the style we made in Blend to see how to do it graphically. To do this, we will need to: Open up the CakeNavigationButtons solution in Expression Blend. In the upper right corner, there are three tabs (Properties, Resources, and Data). On the Resources tab, expand the tree node marked [UserControl] and click on the button highlighted below to edit the [Button default] resource. Your art board should look something like this:
Read more
  • 0
  • 0
  • 2313
article-image-control-templates-visual-state-manager-and-event-handlers-silverlight-4
Packt
16 Apr 2010
7 min read
Save for later

Control templates, Visual State Manager, and Event Handlers in Silverlight 4

Packt
16 Apr 2010
7 min read
Skinning a control So far, you've seen that while styles can change the look of a control, they can only go so far. No matter how many changes we make, the buttons still look like old-fashioned buttons. Surely, there must be a way to customize a control further to match our creative vision. There is a way, its called skinning. Controls in Silverlight are extremely flexible and customizable. This flexibility stems from the fact that controls have both a VisualTree and a LogicalTree. The VisualTree deals with all the visual elements in a control, while the Logical tree deals with all the logical elements. All controls in Silverlight come with a default template, which defines what a control should look like. You can easily override this default template by redefining a control's visual tree with a custom one. Designers can either work directly with XAML in Blend or use a design tool that supports exporting to XAML. Expression Design is one such tool. You can alsoimport artwork from Adobe Illustrator and Adobe Photoshop from within Blend. In our scenario, let us pretend that there is a team of graphic designers. From time to time graphic designers will provide us with visual elements and, if we're lucky, snippets of XAML. In this case, the designers have sent us the XAML for a rectangle and gradient for us to base our control on: <Rectangle Stroke="#7F646464" Height="43" Width="150"StrokeThickness="2" RadiusX="15" RadiusY="15" VerticalAlignment="Top"> <Rectangle.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFEE9D9D" Offset="0.197"/> <GradientStop Color="#FFFF7D7D" Offset="0.847"/> <GradientStop Color="#FFF2DADA" Offset="0.066"/> <GradientStop Color="#FF7E4F4F" Offset="1"/> </LinearGradientBrush> </Rectangle.Fill></Rectangle> After inputting the above XAML, you will be presented with this image: We need to make this rectangle the template for our buttons. Time for action – Skinning a control We're going to take the XAML snippet above and skin our buttons with it. In order to achieve this we will need to do the following: Open up the CakeNavigationButtons project in Blend. In the MainPage.XAML file, switch to XAML View, either by clicking the XAML button on the upper-right corner of the art board or choosing View|Active Document View|XAML from the menu bar. Type in the following XAML after the closing tag for the StackPanel: (</StackPanel>)<Rectangle Stroke="#7F646464" Height="43" Width="150" StrokeThickness="2" RadiusX="15" RadiusY="15" VerticalAlignment="Top" > <Rectangle.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFEE9D9D" Offset="0.197"/> <GradientStop Color="#FFFF7D7D" Offset="0.847"/> <GradientStop Color="#FFF2DADA" Offset="0.066"/> <GradientStop Color="#FF7E4F4F" Offset="1"/> </LinearGradientBrush> </Rectangle.Fill></Rectangle> Switch back to Design View, either by clicking on the appropriate button on the upper right corner of the art board or choosing View|Active Document View|Design View from the menu bar. Right-click on the rectangle and click on Make Into Control. In the dialog box, choose Button, change the Name (Key) field to navButtonStyle and click OK. You are now in template editing mode. There are two on-screen indicators that you are in this mode: one is the Objects and Timeline tab: And one is the MainControl.xaml at the top of the art board: Click on the up button to exit template editing mode. Delete the button that our Rectangle was converted into. Select all the buttons in the StackPanel by clicking on the first one and then Shift+clicking on the last one. With all the buttons selected, go to the Properties tab, type Style into the search box. Using the techniques you've learned in this chapter, change the style to navButtonStyle, so that your screen now looks like this: The result is still not quite what we're looking for, but it's close. We need to increase the font size again; fortunately, we know how easy that is in Blend. Click on one of the buttons and choose Object|Edit Style|Edit Current from the menu bar to get into style editing mode. Make note of all the visual indicators. In the Properties tab, change the FontSize to 18, the Cursor to Hand, the Height to 45, and the Width to 200. You should see the changes immediately. The cursor change will only be noticeable at run time. Exit the template editing mode. There is a slight problem with the last button; the font is a little too large. Click on the button and use the Properties tab to change the FontSize to 12. Run the project and your application will look something like this: Run your mouse over the buttons. The button no longer reacts when you mouse over it, we'll fix that next. What just happened? We just took a plain old button and turned it into something a little more in line with the graphic designers' vision but how did we do it? When in doubt, look at the XAML The nice thing about Silverlight is that you can always take a look at the XAML to get a better understanding of what's going on. There are many places where things can "hide" in a tool like Blend or even Visual Studio. The raw naked XAML, however, bares all. For starters, we took a chunk of XAML and, using Blend, told Silverlight that we wanted to "take control" over how this button looks. This data was encapsulated into a Style and we told all our buttons to use our new style. When the new style was created, we lost some of our formatting data. We then inserted it back in and added a few more properties. If you're really curious to see what's going on, let's take a closer look at the XAML that Blend just generated for us: <Style TargetType="Button"> <Setter Property="FontSize" Value="18.667"/> <Setter Property="Background" Value="Red"/> <Setter Property="FontStyle" Value="Italic"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Margin" Value="5"/></Style><Style x_Key="smallerTextStyle" TargetType="Button"> <Setter Property="FontSize" Value="9"/> </Style><Style x_Key="navButtonStyle" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <Rectangle RadiusY="15" RadiusX="15" Stroke="#7F646464" StrokeThickness="2"> <Rectangle.Fill> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFEE9D9D" Offset="0.197"/> <GradientStop Color="#FFFF7D7D" Offset="0.847"/> <GradientStop Color="#FFF2DADA" Offset="0.066"/> <GradientStop Color="#FF7E4F4F" Offset="1"/> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="FontSize" Value="24"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Height" Value="45"/> <Setter Property="Width" Value="200"/></Style> You'll immediately notice how verbose XAML can be. We've not done a great deal of work, yet we've generated a lot of XAML. This is where a tool like Blend really saves us all those keystrokes. The next thing you'll see is that we're actually setting the Template property inside of a Setter node of a Style definition. It's not until toward the end of the Style definition that we see the Rectangle which we started with. There's also a lot of code here devoted to something called the Visual State Manager. Prior to us changing the control's template, you'll remember that when you moved your mouse over any of the buttons, they reacted by changing color. This was nice, subtle feedback for the user. Now that it's gone, we really miss it and so will our users. If you carefully study the XAML, it should come as no surprise to you that the button doesn't do anything other than just sit there: we've not defined anything for any of the states listed here. The nodes are blank. Let's do that now.
Read more
  • 0
  • 0
  • 2366

article-image-getting-started-development-environment-using-microsoft-content-management-server
Packt
15 Apr 2010
8 min read
Save for later

Getting Started with the Development Environment Using Microsoft Content Management Server

Packt
15 Apr 2010
8 min read
Visual Web Developer Websites The key difference between developing MCMS applications with Visual Studio .NET 2003 and Visual Studio 2005 is that ASP.NET applications (and therefore MCMS applications) are now built using the Visual Web Developer component of Visual Studio 2005. Visual Web Developer introduces a new "project system", which no longer uses the project (*.csproj) files and simply accesses web applications via HTTP or the file system. In Visual Studio .NET 2003, MCMS applications were created by choosing the MCMS Web Application project type. This project type was effectively a regular ASP.NET web application project with some modifications required by MCMS, such as additional references, the web authoring console, and modifications to the web.config. In Visual Studio 2005, developing web applications has been separated from developing other project types. The feature to develop a web application has been moved into the Visual Web Developer component. To reflect this design change, you are no longer using New Project but New Web Site from the File menu in Visual Studio 2005 to create a new website. Visual Studio 2005 ships with several website templates. The installation of the developer tools for MCMS extends the list of website templates with three additional templates: MCMS Empty Web Project, MCMS Web Application, and MCMS Web Service. These templates are actually modified versions of the similarly named standard templates shipped with Visual Studio 2005. Creating an MCMS Web Application Let's create an MCMS web application using Visual Studio 2005. Open Visual Studio 2005. From the File menu, choose New, followed by Web Site… In the New Web Site dialog, select the MCMS Web Application within the My Templates section. If the MCMS Web Application template does not appear in the My Templates section, the MCMS Visual Studio 2005 templates have not been correctly installed. Please refer to the Visual Studio Templates section of Article 1 for installation details. In the Location combo box, select HTTP, and in the textbox, enter http://localhost/mcmstest. MCMS applications have to be created using a local installation of IIS and do not support being created using the file system, which makes use of the built-in Visual Web Developer Web Server. Note that the New Web Site wizard will not prevent you from configuring an invalid website using the File System and Visual Web Developer Web Server. In the Language combo box (shown in the following figure), select Visual C#, and click on OK. If you wish, you can also choose VB.NET. The samples in this article series are all written in Visual C#. Visual Studio 2005 will create your project and initialize the MCMS Template Explorer. When it's done, you will be presented with an MCMS website with the basic foundation files. The MCMS Template Explorer within Visual Studio 2005 logs on to the MCMS repository using the credentials of the currently logged-on user. If this operation fails, check your MCMS Rights Groups configuration. The Template Explorer does not allow you to specify alternative credentials. Click on the MCMS Template Explorer tab at the bottom of the Solution Explorer, and note that the Template Gallery is accessible. If you don't see the Template Explorer, it is likely you didn't select HTTP in the Location combo box in step 4. You may also not see the Template Explorer if you are using a locale other than US English, in which case you need to install hotfix 914195 as detailed in Article 1. Click on the Solution Explorer tab at the bottom of the MCMS Template Explorer, and click on the Refresh button. Notice that unlike the web applications from ASP.NET 1.x days, the 'CMS' virtual directory is now part of the website. If you examine the contents of the website, its references, and web.config file, you will see that the necessary MCMS files and configuration changes have been added. Checking the Website Configuration Settings in IIS We can verify that Visual Studio 2005 has configured the MCMS application correctly by using the Internet Information Services snap-in. First, let's ensure that the mcmstest website is indeed running on ASP.NET 2.0. From the Start Menu click on Run, enter inetmgr in the Run textbox, and click on OK. In Internet Information Services, expand the tree view to display the mcmstest application. Right-click the mcmstest application and click on Properties. Click the ASP.NET tab and note that the ASP.NET version is correctly configured as 2.0.50727. When developing on Windows Server 2003, the Virtual Website root must run in the same worker process (that is Application Pool) as all MCMS applications so that the MCMS ISAPI Filter can work as expected. This filter cannot route requests across worker-process boundaries. In effect this means that all MCMS applications will share the same ASP.NET version, as ASP.NET does not support side-by-side execution of different versions inside the same worker process. This is not necessary with IIS on Windows XP as it does not use Worker Process Isolation mode. Next, we will check the authentication settings. For now, we will configure the website to use integrated Windows authentication. Only users with a domain or local user account will have access to the site. Later in Article 6 we will show alternative authentication methods such as Forms Authentication. Click on the Directory Security tab followed by the Edit... button, and note that the permissions are correctly inherited from the Virtual Web Site settings. In this example, we will use integrated Windows authentication. Note that we configured the Virtual Web Site to use Windows authentication in Article 1. Authentication methods can be configured on a per-application basis. Click on Cancel and close Internet Information Services. Developing MCMS Web Applications We are now ready to get started on developing our ASP.NET 2.0-based MCMS applications. There are a number of quirks with the MCMS web application templates, which we need to bear in mind during development. Switch back to Visual Studio 2005. In Solution Explorer, right-click on the website (http://localhost/mcmstest), and click on New Folder. Enter Templates as the folder name. Right-click on the Templates folder and click on Add New Item… In the Add New Item dialog, select the MCMS Template File item and enter Basic.aspx in the Name textbox. Click on Add. The new Basic.aspx template file is created and opened in Source View. Examine the contents of Basic.aspx. Correcting Basic.aspx Notice that the Basic.aspx file has a few problems. Some elements are highlighted by IntelliSense "squiggles", and if we attempt to build the website, a number of errors will prevent a successful build. Let's correct the Basic.aspx template file. In the CodeFile attribute of the Page directive on line one, replace CodeFile="~/Basic.aspx.cs" with CodeFile="basic.aspx.cs" The MCMS Web Application New Item template doesn't recognize that our new template file has been created in a subdirectory, and therefore the CodeFile attribute is incorrect. New templates in the web root are not affected. From the Build menu, choose Build Web Site. Notice that the website now builds, but still includes a number of errors. Correct the DOCTYPE. On line 19, replace <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> with <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Correct the <html> element. On line 20, replace <html> with <html >. Delete the comments on lines 4 through 17. The comments within an inline ASP script block (<% %>) are unnecessary. Delete the <meta> tags on lines 10 through 13. <meta name="GENERATOR" content="Microsoft Visual Studio .NET 8.0"><meta name="CODE_LANGUAGE" content="C#"><meta name="vs_defaultClientScript" content="JavaScript"><meta name="vs_targetSchema"content="http://schemas.microsoft.com/intellisense/ie5"> These <meta> tags are unnecessary. Correct the WebControls Register directive. On line 2, replace: <%@ Register TagPrefix="cms" Namespace="MicrosoftContentManagement.WebControls" Assembly="Microsoft.ContentManagement.WebControls"%> with <%@ Register Assembly="Microsoft.ContentManagement.WebControls,Version=5.0.1200.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="Microsoft.ContentManagement.WebControls"TagPrefix="cms"%> The original Register directive is not correctly recognized by Visual Studio 2005, and prevents IntelliSense from including the cms tag prefix. From the Build menu, choose Build Web Site. Notice that the website now builds free of any errors and that the cms tag prefix is understood. Your template file should now be as follows: <%@ Page language="c#" AutoEventWireup="false" CodeFile="Basic.aspx.cs" Inherits="Basic.Basic"%><%@ Register Assembly="Microsoft.ContentManagement.WebControls,Version=5.0.1200.0, Culture=neutral, PublicKeyToken= 31bf3856ad364e35"Namespace="Microsoft.ContentManagement.WebControls"TagPrefix="cms"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html > <head> <title>Basic</title> <cms:RobotMetaTag runat="server"></cms:RobotMetaTag> </head> <body> <form id="Form1" method="post" runat="server"> </form> </body></html>
Read more
  • 0
  • 0
  • 2354

article-image-creating-vm-using-virtualbox-ubuntu-linux
Packt
15 Apr 2010
12 min read
Save for later

Creating a VM using VirtualBox - Ubuntu Linux

Packt
15 Apr 2010
12 min read
Packt are due to launch a new Open Source brand, into which future VirtualBox titles will be published. For more information on that launch, look here. In this two-part article by Alfonso V. Romero, author of VirtualBox 3.1: Beginner's Guide, you shall: Create your first virtual machine in VirtualBox, using Ubuntu Linux Learn about your virtual machine's basic configuration Download and install Ubuntu Linux on your virtual machine Learn how to start and stop your virtual machine So let's get on with it... Getting started In this article, you'll need to download the Ubuntu Linux Desktop Live CD. It's a pretty big download (700 MB approximately), so I'd recommend you to start downloading it as soon as possible. With a 4 Mbps Internet connection, you'd need approximately 1 hour to download a copy of Ubuntu Linux Desktop. That's why I decided to change the order of some sections in this article. After all, action is what we're looking for, right? Downloading the Ubuntu Linux Live CD After finishing the exercise in this section, you can jump straight ahead into the next section while waiting for your Ubuntu Live CD to download. That way, you'll have to wait for less time, and your virtual machine will be ready for some action! Time for action – downloading the Ubuntu Desktop Live CD In the following exercise I'll show you how to download the Ubuntu Linux Desktop Edition from the official Ubuntu website. Open your web browser, and type http://www.ubuntu.com in the address bar. The Ubuntu Home Page will appear. Click on the Ubuntu Desktop Download link to continue: The Download Ubuntu page will show up next. Ubuntu's most recent version will be selected by default (Ubuntu Desktop 9.10, at the time of this writing). Select a location near you, and click on the Begin download button to continue. The Ubuntu Download page lets you download the 32-bit version automatically. If you want the 64-bit version of Ubuntu 9.10, you'll need to click on the Alternative download options link below the Download locations list box. The exercises in this article use the 32-bit version. You'll be taken to the download page. After a few seconds, your download will start automatically. Select the Save File option in your browser, and click on OK to continue. Now you just have to wait until the download process finishes. What just happened? I think the exercise pretty much explains itself, so I just want to add that you can also order a free Ubuntu CD or buy one from Ubuntu's website. Just click on the Get Ubuntu link at the front page and follow the instructions. I ordered mine when writing this article to see how long it takes to arrive at my front door. I hope it arrives before I finish the book! Have a go hero – doing more with the thing You can try downloading other Ubuntu versions, like Ubuntu 8.10 Hardy Heron. Just click on the Alternative download options link below the Download locations list box, and explore the other options available for download. Creating your Ubuntu Linux VM Now that you installed VirtualBox, it's time to learn how to work with it. I've used other virtualization products such as VMware besides VirtualBox, and in my humble opinion, the user interface in VirtualBox is a delight to work with. Time for action – creating a virtual machine At last you have the chance to use Windows and Linux side by side! This is one of the best features VirtualBox has to offer when you want the best of both worlds! Open VirtualBox, and click on the New button (or press Ctrl+N) to create a new virtual machine: The Welcome to the New Virtual Machine Wizard! dialog will show up. Click on Next to continue. Type UbuntuVB in the Name field, select Linux as the Operating System and Ubuntu as the Version in the VM Name and OS Type dialog. Click on Next to continue. You can leave the default 384 MB value in the Memory dialog box or choose a greater amount of RAM, depending on your hardware resources. Click on Next to continue. Leave the default values in the Virtual Hard Disk dialog, and click on Next twice to enter the Create New Virtual Disk wizard. Leave the default Dynamically Expanding Storage option in the Hard Disk Storage Type dialog, and click on Next to continue. Leave the default values chosen by VirtualBox for your Ubuntu Linux machine in the Virtual Disk Location and Size dialog (UbuntuVB and 8.00 GB), and click on Next to continue. A Summary dialog will appear, showing all the parameters you chose for your new virtual hard disk. Click on Finish to exit the Create New Virtual Hard Disk wizard. Now another Summary dialog will appear to show the parameters you chose for your new virtual machine. Click on Finish to exit the wizard and return to the VirtualBox main window: Your new UbuntuVB virtual machine will appear on the VirtualBox main screen, showing all its parameters in the Details tab. What just happened? Now your Ubuntu Linux virtual machine is ready to run! In this exercise, you created a virtual machine with all the parameters required for a typical Ubuntu Linux distribution. The first parameter to configure was the base memory or RAM. As you saw in step 3, the recommended size for a typical Ubuntu Linux installation is 384 MB. Exercise caution when selecting the RAM size for your virtual machine. The golden rule of thumb dictates that, if you have less than 1 GB of RAM, you can't assign more than one half of your physical RAM to a virtual machine because you'll get into trouble! Your host PC (the one that runs VirtualBox) will start to behave erratically and could crash! With 2 GB, for example, you can easily assign 1 GB to your virtual machine and 1 GB to your physical PC without any problems. Or you could even have three virtual machines with 512 MB of RAM each and leave 512 MB for your host PC. The best way to find out the best combination of RAM is to do some experimenting yourself and to know the minimum RAM requirements for your host and guest operating systems. Don't assume that assigning lots of RAM to your virtual machine will increase its performance. If, for example, you have 2 GB of RAM on your host and you assign 1 GB to an Ubuntu virtual machine, it's very unlikely there will be a bigger performance increase than if you were assigning only 512 MB to the same Ubuntu virtual machine. On the contrary, your host PC will work better if you only assign 512 MB to the Ubuntu virtual machine because it will use some of the extra RAM for disk caching, instead of recurring to the physical hard disk. However, it all depends on the guest operating system you plan to use and what applications you need to run. If you look closely at the Base Memory Size setting in the Memory dialog when creating a virtual machine, you'll notice that there are three memory areas below the slider control: the green-colored area indicates the amount of memory range you can safely choose for your virtual machine; the yellow-colored area indicates a dangerous memory range that you can choose, but nobody knows if your virtual machine and your host will be able to run without any problems; and the red-colored area indicates the memory range that your virtual machine can't use. It's wise to stick with the default values when creating a new virtual machine. Later on, if you need to run a memory-intensive application, you can add more RAM through the Settings button, as we'll see in the following section. Another setting to consider (besides memory) when creating a virtual machine is the virtual hard drive. Basically, a virtual hard disk is represented as a special file on your host computer's physical hard disk, and it's commonly known as a disk image file. This means that your host computer sees it as a 'large' file on its system, but your virtual machine sees it as a 'real' hard disk connected to it. Since virtual hard drives are completely independent from each other, there is no risk of accidental overwriting, and they can't be larger than the free space available on your real computer's physical hard drive. This is the most common way to handle virtual storage in VirtualBox; later on, we'll see more details about disk image files and the different formats available. VirtualBox assigns a default value based on the guest operating system you plan to install in your virtual machine. For Ubuntu Linux, the default value is 8 GB. That's enough space to experiment with Ubuntu and learn to use it, but if you really want to do some serious work —desktop publishing or movie production, for example—you should consider assigning your virtual machine more of your hard disk space. You can even get two hard drives on your physical machine, and assign one for your host system and the other one for your virtual machine! Or you can also create a new virtual hard disk image and add it as if it were a second hard drive! Before going to the next section, I'd like to talk about the two virtual hard disk storage types available in VirtualBox: dynamically expanding storage and fixed-size storage. The Hard Disk Storage Type dialog you saw in step 4 of the previous exercise contains a brief description for both types of storage. At first, the dynamically expanding option might seem more attractive because you don't see the space reduction in your hard drive immediately. When using dynamically expanding storage, VirtualBox needs to expand the storage size continuously, and that could mean a slight decrease in speed when compared to a fixed-size disk, but most of the time this is unnoticeable. Anyway, when the virtual hard disk is fully expanded, the differences between both types of storage disappear. Most people agree that a dynamically expanding disk represents a better choice than a fixed one, since it doesn't take up unnecessary space from your host's hard disk until needed. Personally, when experimenting with a new virtual machine, I use the dynamically expanding option, but when doing some real work, I like to set apart my virtual machine's hard disk space from the beginning, so I choose the fixed-size storage option in these cases. Have a go hero – experimenting with memory and hard disk storage types When creating a virtual machine, you can specify the amount of RAM to assign to it instead of using the default values suggested by VirtualBox. Create another virtual machine named UbuntuVB2, and try to assign the entire RAM available to it. You won't be able to continue until you select a lower value because the Next button will be grayed out, which means you're in the red-colored memory range. Now move back the slider until the Next button is active again; you'll probably be in the yellow-colored memory range. See if your virtual machine can start with that amount of memory and if you can use both your host PC and your VM without any problems. In case you encounter any difficulties, keep moving back the memory range until all problems disappear. Once you're done experimenting with the memory setting, use the UbuntuVB2 virtual machine with the same exact settings as the one you created in the previous exercise, but this time use a fixed-size hard drive. Just take into account that since VirtualBox must prepare all the storage space at once, this process may take a long time depending on the storage size you selected and the performance of your physical hard disk. Now go and try out different storage sizes with both types of disks: dynamically expanding and fixed size. Configuring basic settings for your Ubuntu Linux VM All right, you created your Ubuntu virtual machine and downloaded a copy of Ubuntu Desktop Live CD. Can you start installing Ubuntu now? I know you'll hate me, but nope, you can't. We need to tell your virtual machine where to boot the Live CD from, as if we were using a real PC. Follow me, and I'll show you the basic configuration settings for your VM, so you can start the Ubuntu installation ASAP! Time for action –basic configuration for your VM In this exercise you'll learn how to adjust some settings for your virtual machine, so you can install Ubuntu Linux on it. Open VirtualBox, select your UbuntuVB virtual machine, and click on the Settings button: The UbuntuVB – Settings dialog will appear, showing all the settings in the General tab. Click on the Storage category from the list in the left panel. Then select the Empty slot located just below the UbuntuVB.vdi hard disk image, under the IDE Controller element inside the Storage Tree panel, and click on the Invoke Virtual Media Manager button: The Virtual Media Manager dialog will appear next. Click on the Add button to add the Ubuntu Linux Live CD ISO image: The Select a CD/DVD-ROM disk image file dialog will show up next. Navigate to the directory where you downloaded the Ubuntu Desktop ISO image, select it, and click on the Open button to continue. The Ubuntu Desktop ISO image will appear selected in the CD/DVD Images tab from the Virtual Media Manager dialog. Click on the Select button to attach the Ubuntu ISO image to your virtual machine's CD/DVD drive. Next, the Ubuntu ISO image file will appear selected on the ISO Image File setting from the UbuntuVB – Settings dialog. Click on OK to continue. Now you're ready to start your virtual machine and install Ubuntu!
Read more
  • 0
  • 0
  • 22691
article-image-creating-your-first-virtual-machine-ubuntu-linux-part-2
Packt
15 Apr 2010
6 min read
Save for later

Creating Your First Virtual Machine: Ubuntu Linux (Part 2)

Packt
15 Apr 2010
6 min read
Running your Ubuntu Linux VM This is going to be the most entertaining section of the article: you'll get to play with your brand-new Ubuntu Linux virtual machine! If you haven't used Linux before, I'd definitely recommend that you browse through the Ubuntu documentation at https://help.ubuntu.com/9.10/index.html. Time for action – running Ubuntu Linux The best way to test your new virtual machine is experimenting, so let's get on with it! Open VirtualBox (in case you closed it after the last section's exercise), select your UbuntuVB virtual machine, and click on Start to turn it on: Ubuntu will start to boot in your virtual machine. Eventually, the Ubuntu logo will show up along with the progress bar and, after a few seconds (or minutes, depending on your hardware), the Ubuntu login screen will show up. Click inside the virtual machine screen to capture the mouse and keyboard, type the username you assigned in the installation process, and hit Enter to continue. Now type the password for your username, and hit Enter again. Ubuntu will start to load. When finished, you'll see the Ubuntu GNOME Desktop screen: One of the first things you'll notice is the Update Manager dialog. This dialog shows up when your Ubuntu system needs software updates. Click on Install Updates to start the updating process. Normally, the Update Manager will ask for your administrator password. Type it, press Enter, or click on OK and then wait for the Update Manager to finish its job so you can work with your Ubuntu system fully updated. If the Update Manager asks you to restart your Ubuntu system after updating, click on the Restart Now button, and wait for your Ubuntu virtual machine to reboot. What just happened? Isn't it cool to have a little Ubuntu system running inside your real PC? Just like a pregnant mother feeling her baby's first movements! Well, not as touching, but you get the point, right? Ubuntu is one of the friendliest Linux distributions available. That's why I decided to use it for this article's exercises. Now let's go and test the Internet connection on your new Ubuntu virtual machine! Web browsing with Mozilla Firefox One of the best things about the Ubuntu Desktop edition is that you can use Mozilla Firefox out of the box. And the Ubuntu Update Manager keeps it updated automatically for you! Time for action – web browsing in your Ubuntu VM You have your virtual machine installed. What's next? Let's surf the web! After all, what could be more important than that? Open the Applications menu on your Ubuntu virtual machine, and select Internet | Firefox Web Browser from the menu: The Mozilla Firefox window will show the Ubuntu Start Page. Type virtualbox.org on the address bar and press Enter: The VirtualBox homepage should appear as an indication that you have Internet access in your virtual machine. You can close Mozilla Firefox now. If you cannot connect to Internet from your virtual machine, check your host's network settings. If you can connect from your host, try using another virtual network adapter type in your virtual machine to see if the problem disappears. What just happened? Well, this exercise is not really hard, right? But this is a cool way to test if your new virtual machine has Internet enabled by default. Later on, we'll talk about the different settings related to virtual network interfaces and VirtualBox. You can also know if your virtual machine can connect to Internet through the Ubuntu Update Manager because it will issue a warning if it cannot access the Ubuntu software sources. For now, it's good to know we can surf the web! Now let's see how you can do some real work inside your Ubuntu VM… Using OpenOffice.org in your virtual machine Ok, we have Internet enabled on our Ubuntu virtual machine; what else could we ask for? How about some word processing, a spreadsheet, and some presentations, for starters? I know it's boring, but some of us also use VirtualBox to work! Time for action – using OpenOffice.org Ubuntu comes with OpenOffice.org, the open source productivity suite that has proven to be an effective alternative to MS Office for Linux users. Now let's try it out on your new Ubuntu virtual machine... Open the Applications menu on your Ubuntu virtual machine, and select Office | OpenOffice.org Word Processor from the menu: The Untitled 1 – OpenOffice.org Writer window will appear. You can use OpenOffice Writer as if you were on a real machine: Now go to the Applications menu again, and this time select the Office | OpenOffice.org Spreadsheet option. The Untitiled 2 – OpenOffice.org Calc window will show up, overlapping the Writer window. You can also work with it as in a real PC: And now, go back to the Application menu, and select the Office | OpenOffice.org Presentation option. The Presentation Wizard screen will show up. Select the Empty Presentation option, click on Next twice, and then click on Create to continue. The Untitled 3 – OpenOffice.org Impress window will show up, overlapping the other two windows: Now you can close all the application windows inside your virtual machine. What just happened? How about that? A complete office productivity suite inside your main PC! And Internet access too! So, if you always wanted to learn about Linux or any other operating system but were afraid of messing up your main PC, VirtualBox has come to your rescue! Now let's see how to turn off your virtual machine… Have a go hero – trying out Ubuntu One: your personal cloud Now that you have an Ubuntu virtual machine, you would likely benefit from trying out the Ubuntu One service, where you can back up, store, sync, and share your data with other Ubuntu One users. And the best of all, it's free! To open an account, select Applications | Internet | Ubuntu One, and follow the instructions on screen. Have a go hero – sharing information between your VM and your host PC Use your Ubuntu One account to transfer some files between your virtual machine and your host PC. If you're using Windows, you can work with the Ubuntu One web interface at http://one.ubuntu.com. Shutting down your virtual machine I know you're thinking, "Geez, I can't believe this guy! He's actually going to spend an entire subsection of this article just to show us how to shutdown a virtual machine! Aw, come on!" Now it's my turn: Remember we're talking about a virtual machine here, not a real PC! You need to consider several things before shutting this baby down!
Read more
  • 0
  • 0
  • 2994

article-image-creating-tumblr-theme
Packt
15 Apr 2010
13 min read
Save for later

Creating a Tumblr Theme

Packt
15 Apr 2010
13 min read
At this moment, surely, you must have heard something about Tumblr, but in case you haven't, we can summarize by telling it's a platform for microblogging. We can publish texts, audio, photos, quotes, links etc in a very easy way. As other users can follow our posts, comment on them or ask questions to us, Tumblr can be considered a great social tool. Apart from being very easy to use, we can also customize it's appearance, so it shares our business look and feel, or simply because we prefer some other appearance. Not only can we customize it's appearance, but also design our own customized themes; that's exactly what we are going to do in this article: What we have and what we want First steps, a basic html template Generating the Tumblr theme from our template Adding a bit of jQuery Keep with us and by the end of the article, you will learn how to create very interesting Tumblr themes, and use also them. What we have and what we want For this article, we are going to use my own account as an example. For now, I'm using a theme that looks this way: This is a great theme, very clean, centered on showing our content. The theme we are going to create is going to be very clean too, and also enough for us to see how we can create a template. Let's take a look at it: As you can see, it's a quite easy design; hope you like it too. Also, you can download the PSD if you wish, maybe it will help you follow the article. Well, once we know which design we want to use, our next step will be to generate a plain html template. First step, a basic html template A basic html template is a good place to start our theme, and that's where we are going to start. First the basic structure: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html ><head> <title>Our first theme</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> </head> <body id="theme"> <div id="container"> <div id="menu"> <a href="#" class="menu_link">About me</a> | <a href="#" class="menu_link">Archives</a> | <a href="#" class="menu_link">Random</a> | <a href="#" class="menu_link">Mobile</a> | <a href="#" class="menu_link">RSS</a> </div> <div id="right_col"> <div class="post"> <div class="post_type"> <div class="blue_box">Text</div> <a href="#" class="content_link">Permalink</a> </div> <div class="date"> <div class="blue_box">Mar 22</div> Posted at 7:54am </div> <div class="post_contents"> <h1>Codeigniter 1.7</h1> <p> <img src="sample_image.jpg" /> <br/> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean fermentum  vestibulum nisl vitae placerat. Praesent nec massa neque. Nam dictum commodo posuere. Sed vitae est risus. Nunc suscipit justo vitae mi faucibus cursus. Morbi eu arcu erat. Nam venenatis, urna non tempus pretium, felis nunc blandit risus, non elementum elit turpis in diam. Proin ullamcorper blandit lacinia. Nulla nibh metus, lacinia at luctus vel, tincidunt et mauris. Sed rutrum, felis in tincidunt porttitor, nulla nunc placerat elit, ac tempor magna arcu non nisi. Proin ac sagittis lorem. Morbi imperdiet consectetur ipsum, volutpat convallis arcu pulvinar in. Nulla eget quam elit, vitae molestie ligula. Praesent rhoncus diam id lorem sagittis consequat ac et magna. </p> <hr> </div> </div> </div> <div id="left_col"> <div id="description"> <h1>Jose Argudo's Blog!</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean fermentum vestibulum nisl vitae placerat. Praesent nec massa neque. Nam dictum commodo posuere. Sed vitae est risus. Nunc suscipit justo vitae mi faucibus cursus. Morbi eu arcu erat. Nam venenatis, urna non tempus pretium, felis nunc blandit risus, non elementum elit turpis in diam. </p> </div> <div class="banner"> <img src="codeigniter_book.gif" /> &nbsp;&nbsp; Check my Codeigniter book </div> </div> <div id="footer"> <div id="left_footer"> Jose Argudo´s Blog </div> <div id="right_footer"> <img src="arrow.gif" /> </div> </div> </div> </body></html> We have our basic html structure here, quite simple by now, all html without any styling as of now. Our next step will be to add some css to our basic page, which, by now, looks more or less this way: Some reset css will be useful here, I usually use Eric Meyer's one, which you can find here: http://meyerweb.com/eric/tools/css/reset/ We are going to place this code in the head section of our page, just like this: ... <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <style type="text/css" media="screen"> /* CSS reset from Eric Meyer */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } :focus { outline: 0; } ins { text-decoration: none; } del { text-decoration: line-through; } table { border-collapse: collapse; border-spacing: 0; } </style> We have included this css styles in our html file, instead of including it from an external source. Why have we done that? Mostly because we have no ftp access to our Tumblr account, also themes are not packed in a zip file and installed somehow. Soon we will be answering all these questions; for now, placing our css styles directly in our html is the best solution. Now that we have added our reset styles, we can start working in the theme own styles, let's see: /* Theme's own styles */ #theme{ font-family: arial, sans-serif; font-size: 12px; color: #333333; background-color: #F5F5F5; } #container{ width: 960px; margin: 20px auto; } #menu{ height: 22px; } #left_col{ float: left; width: 320px; } #right_col{ float: right; width: 630px; } #footer{ float: none; clear: both; height: 20px; } #description, .banner{ background-color: #0087C5; padding: 12px; color: #ffffff; margin-bottom: 5px; } #description h1{ font-size: 24px; margin-bottom: 15px; } #description p{ line-height: 18px; } .banner{ font-style: italic; font-size: 10px; } .post_type{ width: 54px; float: left; margin-left: 10px; } .date{ width: 54px; float: left; color: #0087C5; font-style: italic; font-size: 10px; } .post_contents{ margin-left: 10px; margin-bottom: 22px; width: 500px; float: right; } .blue_box{ height: 54px; background-color: #0087C5; color: #ffffff; font-size: 14px; padding: 6px; padding-bottom: 0px; margin-bottom: 10px; } .post_contents h1{ font-size: 18px; color: #0087C5; margin-bottom: 22px; } .post_contents img{ margin-bottom: 24px; } .post_contents p{ line-height: 18px; } hr{ height: 1px; color: #0087C5; border: 1px solid #0087C5; } a.content_link:link, a.content_link:visited{ color: #0087C5; font-style: italic; font-size: 10px; text-decoration: none; } a.content_link:hover{ text-decoration: underline; } #menu{ color: #0087C5; } a.menu_link:link, a.menu_link:visited, a:link, a:visited{ color: #0087C5; font-size: 12px; text-decoration: none; } a.menu_link:hover, a:hover{ text-decoration: underline; } #left_footer{ width: 332px; height: 20px; float: left; background-color: #0087C5; color: #ffffff; } #right_footer{ width: 43px; float: right; } .padd{ padding: 4px; } .clear{ clear: both; float: none; } With these styles our template will be looking very similar to our design, maybe later we will need some small changes, but that's not so important. With all this in place, we can start with the interesting work, the Tumblr part. Generating the Tumblr theme from our template Converting this template into a working Tumblr theme is not going to be that hard, mostly we will be using some special tags to determine where some specific contents will be placed. Tumblr uses two type of tags Variable tags Block tags But we will see that better by working with our theme, for example, our page title: <title>Our first theme</title> We will change that for this code: <title>{Title}</title> In bold, we can see a {Title} tag. This tag, when rendered will be substituted by the title of our blog, without any html tag. Easy, isn't it? Most of our work will be quite similar, we are going to see the main tags to use. One of our main work will be showing the posts, after all, our main objective is to show these posts. Tumblr divides posts into eight possible types: Text posts, with only text and html. Photo posts, with one photo and its description Photosets, for when you need to show more than one photo Quote, used when we want to quote other site or source Link to other sites or online resources Chat, interesting option, for showing conversation, where each line, separated be a carriage return, is show in a different color. Audio, from an uploaded or external source Video, similar to audio but with videos. In our html code, we have prepared a zone for showing posts: <div class="post"> <div class="date"> <div class="blue_box">Mar 22</div> Posted at 7:54am </div> <div class="post_type"> <div class="blue_box">Text</div> <a href="#" class="content_link">Permalink</a> </div> <div class="post_contents"> . . . <hr> </div> </div> <br class="clear" /><br/> Now we need to generate one of these post zone for each post type. It's important to note that this is absolutely necessary for the theme to be correct, all post type must be present in our code. Firstly, we need to define these tags: {block:Posts} … {/block:Posts} All the other types of posts will go into these tags, let's summarize it a bit: {block:Posts} {block:Text} Text posts will go inside these tags {/block:Text} {block:Photo} Photo posts will go inside these tags {/block:Photo} {block:Photoset} Photoset posts will go inside these tags {/block:Photoset} {block:Quote} Quote posts will go inside these tags {/block:Quote} {block:Link} Link posts will go inside these tags {/block:Link} {block:Chat} Chat posts will go inside these tags {/block:Chat} {block:Audio} Audio posts will go inside these tags {/block:Audio} {block:Video} Video posts will go inside these tags {/block:Video} {/block:Posts} Now, we will be working on each one of these blocks. Remember that we will be placing them between {block:Posts} … {/block:Posts}, so we will have more or less this code: <div id="right_col"> {block:Posts} All the other block types will go here {/block:Posts}</div> Text Posts We will start with this type of posts, I will put the code and after we take a look at the different options {block:Text} <div class="post"> <div class="date"> {block:Date} {block:NewDayDate} <div class="blue_box">{Month} {DayOfMonth}</div> Posted at {12Hour}{AmPm} {/block:NewDayDate} {block:SameDayDate} <div class="blue_box">{Month} {DayOfMonth}</div> Posted at {12Hour}{AmPm} {/block:SameDayDate} {/block:Date} </div> <div class="post_type"> <div class="blue_box">Text</div> <a href="{Permalink}" class="content_link">Permalink</a> </div> <div class="post_contents"> {block:Title} <h1>{Title}</h1> {/block:Title} <p> {Body} </p> <hr> </div> </div> <br class="clear" /><br/> {/block:Text} Here we have some interesting tags, let's talk a bit about them: {block:Date} — this will render the date, with the options we are defining inside. {block:NewDayDate} — this is used for showing the date, but it's only show for the first post of the day. {block:SameDayDate} — If we want to show the date in each post, we need to use this tag. {Month} — with this tag we will show the day of the post {DayOfMonth} — and with this other we will show the day {12Hour} — the hour in a 12 hour format {AmPm} — and the am or pm text, where applicable {Permalink} — we used this inside our link href in order to generate a permalink {block:Title} — the code inside these tags will only be shown if the article has a title. {Title} — this is the title of the post. {Body} — and the content of the same. Most of the options are in fact very self explanatory, and quite easy to use. The next blog types are similar, but with some differences. Photo Posts The code for photo posts is quite similar, let's take a look to it: {block:Photo} <div class="post"> //same as before <div class="post_contents"> <img src="{PhotoURL-500}" alt="{PhotoAlt}"/> <p> {block:Caption}{Caption}{/block:Caption} </p> <hr> </div> </div> <br class="clear" /><br/>{/block:Photo} As you can see, we have changed the title tag for caption tag, but the structure remains mostly the same. The other main difference is the img tag we have used: <img src="{PhotoURL-500}" alt="{PhotoAlt}"/> The {PhotoAlt} tag will show the alt attribute of the photo, if there's any. {PhotoURL-500} is the more important one, as it will create the url of the image, but for a photo equal or smaller to 500px width. There are other options for this tag, which are as follows: {PhotoURL-400} — just the same tag, but will create a url for a image equal or smaller to 400px. {PhotoURL-250} — a smaller image, this time of 250px. {PhotoURL-100} — just the same as before, but will make urls for images of 100px width or less. {PhotoURL-75sq} — this one is a bit different, as will make a url for a reduced, squared image of the post, of 75px. {PhotoURL-HighRes} — this last tag will create a url for the high resolution image.
Read more
  • 0
  • 0
  • 3973
Modal Close icon
Modal Close icon