Why Profiling is necessary for Performance Benchmarking?

40% of users abandon a website that takes more than 3 seconds to load.

Websites are typically viewed on a large variety of devices with various systems, it may be handheld device or desktops, might run a Mac OS or have Windows but the bottom line is when a visitor is on the homepage of your website or loading items on the e commerce portal or using some other functionality on the website they expect it to be fast and move with the speed of their finger swaps.

What affects Website Performance?

Performance of a website depends on a lot of factors, the performance of the code, factors that have been kept in mind while making that code, number of visitors currently viewing the website, connections to database and so on. To ensure smooth functioning of a website according to expectations it is necessary that it goes through performance testing.

Performance Testing gives the power to analyze your code and find bottlenecks and determine which parts of your code needs a tweak to boost the speed. It helps to determine the points of breakage of the technology stack used in the development of the application. It also helps to find the limit to the number of users the website can handle in case of a spike, like media and publishing websites when Presidential Elections were running.

How does performance boosting help?

  1. Wal-Mart trailed its competitors online until they made improvements. For every 1 second of improvement to load time, the site experienced up to a 2% improvement in conversion rate.

  2. Intuit cut load time in half and saw an increase of 14% in conversions.

  3. GQ decreased its average load time from 7 to 2 seconds and saw an 83% increase in traffic.

Source

You might have added some new functionalities to your website and now the server load has increased and also the memory usage and also the page is slow to load. But does that mean you change the hardware? Even if that is an option it is not a viable solution and this is exactly where performance profiling comes into the picture, to analyse and understand what makes the system slower and fix them.

Performance profiling is to investigate and analyse a code’s runtime behavior to understand the areas that need improvement and how to optimize a program’s performance. The data collected during the execution of a program helps developers to analyze the code.

It helps apps run faster, at different stages of deployment, Performance Testing helps to determine which particular feature addition to your web application has made it slower or analyse the behavior of apps.

How do Profilers work?

Developers say that different profilers work in different ways, however in general profilers examine programs during the runtime to find which assembly instruction is currently being executed (the program counter) and which routines called the current function (the call stack). This kind of sampling profiler can work with standard binaries, but are more useful if you have debugging symbols to work out lines of code given addresses in the program.

As well as sampling regularly, you can also use processor performance counters to sample after a certain number of events such as cache misses, which will help you see which parts of your program are slowing down due to memory accesses.

Other profilers involve recompiling the program to insert instructions (known as instrumentation) to count how often each continuous set of instructions (basic blocks) are executed, or maybe even record the sequence in which basic blocks are executed, or record the content of variables at certain places.

The instrumentation approach can give you all the precision and data you might want, but will slow down the program and that will change its performance characteristics. By contrast, with sampling based approaches you can tune the performance impact against the length of time you need to run the program against the accuracy of the profile data you obtain.

Why Profiling for Performance Benchmarking is necessary ?

Performance profiling is pivotal to the performance of the website it helps to understand the client-server response time. Performance issues during a spike or in peak times. It helps to understand if any database connections or the technology is a holdup in your web application and help change any components causing so. It also determines behavioral changes in applications caused with a new release.

Performance profiling works as a benchmark against coding changes and efficiency  of the website.

How to Migrate a Website to Drupal 8

We all know that now is the time to move into Drupal 8 from the other Drupal versions.  And it is very important for a Drupal developer to know about Migrating into Drupal 8 and Website Migration in general. This was a session presented at the DrupalCamp Mumbai 2017, I spoke about the experience of migrating a Legacy System which built on Adobe ColdFusion.

Website migrations occur now and then for numerous reasons and now that we are working on Drupal 8, it is absolutely necessary to migrate from Drupal 6 or 7 to Drupal 8 to fully utilize the power of Drupal.

The session focuses on:

  • Case Study of  Migrating a Legacy System into Drupal8.

  • Migration in Drupal 8 Core.

  • D6 to D8 migration.

  • D7 to D8 migration.

  • Migrating from JSON and CSV data.

  • Migrate Source Plugin

    • Why or When we need to write Migrate Source plugin?

    • How to Write Migrate source plugin?

  • Migrate Process Plugin

    • Why or When we need to write Migrate Process plugin?

    • How to Write Migrate Process plugin?

  • Migration using Drush.

 

Related:

Why & How to Migrate Drupal 8

Porting drupal 7 module to drupal 8 using Drupal Module Upgrader

How to migrate Users from a CSV file in Drupal 8?

 

How to Write PHP Unit Tests for Drupal 8

We all know that PHPunit testing framework has been added into Drupal 8. More than that SimpleTest in Drupal 8 is deprecated now. So let’s learn about, how to write the PHPUnit test for our requirement. The following Topics were covered during DrupalCamp Mumbai 2017 session. We are covering in the slides.

  • Why PHPUnit?

  • Things we need to know before writing PHPUnit Test Case?

    • Files Structure and namespace

    • PHPUnit Base Classes

  • How to write a PHPUnit Test?

  • Running PHPUnit tests

  • How to integrate with PHPStorm?

 

How to start your Drupal Contribution?

I am presenting at DrupalCamp Mumbai 2017 about the personal experience, about my Drupal Contributions. Will be covering following topics during the session -

  • What is Contribution?

  • Why Contribution is needed ?

  • What all are ways you can contribute to Drupal community?

  • What is important of contribution?

  • When  you can start the Contribution?

  • How can  you keep contribution going with your work?

  • What is the benefits of a contributor?

  • How to work on Issue queues?

  • How to select the issues?

  • Contribution, contribution and contribution

Stay tuned, will upload the slides next week.

Console your Drupal 8 Module Development

Drupal Console is a scaffolding tool built for Drupal 8 automatic code generation.  During this session will be doing live demo on creating module in Drupal 8 and showing how to take the  advantage of the Symfony Console Component. And we we will be covering  following topics during session at DrupalCamp Mumbai 2017.

  • What is Drupal Console?

  • Why Drupal Console?

  • How to speed up your drupal 8 development using Drupal Console?

  • How to create a new console command?

  • How to create a custom module using Drupal Console?

Stay tuned, will upload the slides next week.

9 ways Unit Testing improves your product quality

Testing and development have forever been in war. It is obvious that Testing helps reduce errors and redundant tasks, but the amount of effort required to be put be each one is different and there is where the pressure to implement unit testing into the development process comes into action and actually makes more sense.

Testing helps to find out bugs and move the development of new functionalities. And unit testing validates that your functionalities work well in the best and worst of use cases.

unit testing

What freedom does Unit Testing give you?

1. Reduce Time

Piled up dev and QA cycles slow down legacy systems. Codes written without detailed tests make it easier to change codes making it difficult to stick to timelines

2. Flexible

Agility comes as a difficult thing with most legacy systems. Most of the times it becomes a burden to change codes on which applications and businesses run. Properly tested codes do very little to break existing functionality.

3. Quality Assured

To ensure that development teams do not release buggy codes so that QA doesn’t come up to be expensive and heavy on the pocket, unit testing helps to avoid this exact scenario where we take prevention to be better than cure. Unit testing helps to improve performance of product

4. Documentation

Test case scenarios are much better than 1000s of lines of technical documentations. Developers need to work with code examples and snippets rather than documents which hold a lot less practical value.

5. Practical Value

Unit test gives you much needed practical visual information whether that button is giving you the kind of result its supposed to when you click on it. The best thing about unit tests is that the documentation also shows  how your code is supposed to behave. It is like e reference point and standard for your teammates, that come in handy very often.

6. Scalability

Testing helps in easy change of codes because you know exactly at what point it will break the functionality. With extensive  test coverage it is easier to explore new functionalities and features without fearing about introducing new bugs, you know where to roll back to. Legacy systems that have poorly tested units keep making systems more bulky to the point of breakage and it becomes utterly difficult to scale the platform.

7. Code Refactoring

Testing helps in restructuring existing code —changing the factoring— without changing its external behavior. It speeds up system without any visual changes so that you can changes the way your program is designed but with little or no effect to existing functionalities.

8. Tests actually help Programmers

Ideal scenarios are very very different than practical ones and real world issues make it difficult to deal with them. Difference in operating systems, mini and micro bugs, stupid rules often make peculiar errors which is avoidable with Unit Testing

9. Testing is way important than you think

Testing is considered to be less important when you think about development and are given to the less experienced programmers. But coming up with various test scenarios can be tough too. Testing is not ticking on a written checklist, it is not  monkey job. In a lot of cases writing automated tests is harder than coding and requires experience.

Testing tends to slow you down if you are doing units testing class-by-class or methods. You need to invest good time to write some quality tests. But with time it becomes a more trusted method because you worry less about breaking existing codes while you add new functionalities.

"Imperfect tests, run frequently, are much better than perfect tests that are never written at all"

What helped to write this blog : Stackoverflow, Unit Testing

How to create .info file for themes in Drupal 7

The .info files is most important part of Drupal themes. The .info file in a Drupal theme configures the theme. Drupal 7 Support PHPTemplate engine which is needed to powered theming system. This file has a configuration function and syntax similar to a .ini file. 

The .info file is a collection of static text file, used to define and configuring a theme. Each line in the .info file has a key-value pair with the key on the left and value on the right hand side, with an "equals sign" between them (e.g. name = my_new_theme). Semicolons are used to comment out a line. As we do follow # symbol or /* */ symbols to comment out or to provide developer comment. Some keys uses a syntax with square brackets for building a list of associated values, represent to as an "array". If you are not aware with arrays, have a look at the default .info files that come with Drupal and read the explanations of the examples that follow. Even though the .info file is not natively opened by an Application, you can use TextEdit or Notepad on a Windows computer in order to view, edit, and save your changes.

Let’s look at an example of what you might have found in an .info file

name = My Theme
description = A description of my theme
core = 7.x

# Add a base theme, if you want to use one.
base = mybasetheme

# Define regions, otherwise the default regions will be used.

regions[header] = Header
regions[navigation] = Navigation
regions[content] = Content
regions[sidebar] = Sidebar
regions[footer] = Footer

 

# Define which features are available. If none are specified, all the default 
# features will be available.

features[] = logo
features[] = name
features[] = favicon

# Add stylesheets

stylesheets[all][] = css/reset.css
stylesheets[all][] = css/mytheme.css
stylesheets[print][] = css/print.css

 

# Add javascript files

styles[] = js/mytheme.js

 

 

There are some of the most needed information that need to be in every Drupal .info file

name – This should be human-friendly name that will be displayed on the theme select page.
and it can be set independently from the internal "machine" readable name. This imposes fewer restrictions on the allowed characters.

name =  A fancy theme

description (recommended) – This is a short description of the theme that helps identifying it on the theme select page. This description is displayed on the theme select page at "Administer > Site building > themes".

description = multi column row for fancy theme

core – earlier version of Drupal 6.x .info file should state which major core version of Drupal it is compatible with, just  to avoid compatibility issues. The value set here is compared with the DRUPAL_CORE_COMPATIBILITY constant. If it does not match, the theme will be disabled.

But in Drupal 7.x packaging script automatically sets this value based on the Drupal core compatibility setting on each release node. So people downloading packaged themes from drupal.org will always get the right thing. 

On top of that we also have other key value pair which is needed optionally.

core= 7.x

version (discouraged)
The version string is automatically be added by drupal.org when a release is created and a tarball packaged. So you may omit this value for contributed themes. However, if your theme is not being hosted on the drupal.org infrastructure, you can give your theme whatever version string makes sense.

version = 1.0 

base theme
When you are about to create a new theme in that scenario Sub-themes can declare a base theme. This allows theme to inherit, reusing the resources from the "base theme" will cascade and be reused inside the sub-theme. Sub-themes can declare other sub-themes as their base, allowing multiple levels of inheritance. Use the internal "machine" readable name of the base theme. 

base theme = bootstrap

region
If you overriding regions in D7, you are obliged to declare the line regions[content] = Content. If you want any of the default regions in your theme, you have to declare them as well.

In Drupal, we have block regions. Block regions are dynamic content areas that hold different content (block) that you can set through the Drupal administrator dashboard. The important thing is, these regions are set in the .info file of a Drupal theme.

regions[left] = Left sidebar
regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer

The above is a list of default regions in Drupal 7. To use those regions in the theme’s page.tpl.php file, all you need to do is something similar to this:

/* Display blocks in "Left sidebar" */

Features
In Drupal 7, features are not inherited from the base theme. If you are using features other than the default, you should copy the features declarations from the parent theme's .info file.
Various page elements output by the theme can be toggled on and off on the theme's config page. The "features" keys control which of these check boxes display on the theme's config page. 

The example below lists all the available elements controlled by the features key.

Drupal 7 features

features[] = logo 
features[] = name 
features[] = slogan 
features[] = node_user_picture 
features[] = comment_user_picture 
features[] = comment_user_verification 
features[] = favicon 
features[] = main_menu 
features[] = secondary_menu 


Stylesheets
To Override inherited style sheets: Specify a stylesheet with the same filename in the sub-theme. For instance, to override style.css inherited from a parent theme, add the following line to your sub-theme's .info file:

stylesheets[all][] = style.css

On drupal 6.x version themes default to using style.css automatically and could add additional stylesheets by calling drupal_add_css() in their template.php file. Whereas in Drupal 7, themes no longer default to using style.css if it is not specified in the .info file.


Scripts
All JavaScript files defined in the parent theme will be inherited.

Overriding inherited JavaScript: Specify a JavaScript file with the same filename in the sub-theme's .info file. For instance, to override script.js inherited from a parent theme, add the following line to your sub-theme's .info file:

On drupal 6.x version themes could add Javascripts by calling drupal_add_js() in their template.php file. if a file named script.js exists in the theme directory then it is automatically included. However, in Drupal 7.x version, this behavior has been changed again so that script.js is only included if it has been specified in the .info file:

scripts[] = myscript.js 

Conclusion: Drupal theme development could be a bit complicated at first time, but learning about Drupal themes in general and learning about what each file does and How functionality work and what type of function call does it make could help you a lot to set you on the right direction to becoming a Drupal Front End developer.
 

How to make Drupal Custom Templates for Content Types in Drupal 7

Drupal Custom Templates go a long way to help UI developers in Drupal, it gives an edge to easily create drupal custom pages with new templates and get the desired HTML output. You don't have to rely on any templates because it might not match up with the vision, requirement or content and expands the limits set by Drupal themes.

From the Beginning of time while doing Drupal theme development we prefer to use the own custom template to render page/block/ field/view. Overriding a template file is one of the common tasks for a front-end developer, but depending on the base theme used it’s not always clear how to go about doing it.

Most Drupal themes come with a minimum of 3 default template files: html.tpl.php, page.tpl.php and node.tpl.php. And many other template files used to control the display of more specific elements such as comments or individual fields. Each of these files can be overridden for a specific condition simply by creating a new drupal tpl file in the theme folder with the correct name. These file names are called “drupal template” and there is a standard set of these suggestions built into Drupal and listed in the documentation as Drupal Template Suggestions( drupal theme hook).

Page Template Per Content Type

The most common and overriding concept we used to follow is to not includ in the default list is the page.tpl.php override based on the content type being displayed. There is a node.tpl.php override based on the same condition which leads to confusion as to where the page override exists. On top of that, themes like Zen add this type of override to the Template Suggestions, which leads those using Zen to believe that this is part of the default list. Check the theme documentation to see if this override has been added to the Template Suggestions by the theme. If it hasn’t, you need to add it manually.

The process is straightforward. We can create additional Template Suggestions simply by adding them to the ‘theme_hook_suggestions array in our template.php file.

Open the template.php file in your theme for editing.
Look for a function called yourthemename_preprocess_page (replace the yourthemename with your theme’s name).
If this function already exists, you will need to add the if statement to the end of the function just before the closing bracket. Otherwise, you’ll need to create a new function to look like this:

function THEME_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
   // If the content type's machine name is "my_machine_name" the file
   // name will be "page--my-machine-name.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
   }
} 


Now you can create a template file called page--content-type.tpl.php and all nodes with that type will use the new template file.

Filename Notes:

Use two dashes after the word ‘page’ in the filename.
If your content type is two or more words, replace the underscore ( _ ) with a short dash ( - ) in the content type machine name.

Using page--content-type.tpl.php we have the feasibility to create multiple layouts for each and every bundle. And on the same layout, you can add design/functionality of your choice.

How to send custom formatted HTML mail in Drupal 8 using hook_mail_alter()

As you can understand from name itself it’s basically used to Alter an email created with drupal mail in D7/ MailManagerInterface->mail()in D8.  hook_mail_alter() allows modification of email messages which includes adding and/or changing message text, message fields, and message headers.

Email sent rather than drupal_mail() will not call hook_mail_alter(). All core modules use drupal_mail() & always a recommendation to use drupal_mail but it’s not mandatory.

Syntax: hook_mail_alter(&$message)

Parameters

$message: Array containing the message data. Below are the Keys in this array include:

  • 'id': The id of the message.
  • 'to': The address or addresses the message will be sent to. 
  • 'from': This address will be marked as being from, which is either a custom address or site-wide default mail address.
  • 'subject': Subject of the email to be sent. Subject should not contain any newline characters.
  • 'body': An array of strings containing the message text. message body created by concatenating individual array strings into a single text string.
  • 'headers': Associative array containing mail headers, such as From, Sender, MIME-Version, Content-Type, etc.
  • 'params': An array of optional parameters supplied by the caller of drupal_mail() that is used to build the message before hook_mail_alter() is invoked.
  • 'language': The language object used to build the message before hook_mail_alter() is invoked.
  • 'send': Set to FALSE to abort sending this email message.

Why i am discussing on hook_mail_alter() ?

Recently i was doing one of the Drupal 8 project where client was looking for formatted HTML mail that also works for contact form. So whenever an anonymous user fill up and submit the contact form, It triggers an automated mail to the admin user. If you ever get a chance then just look at that weird formatted Email. Mail related to contact form is being triggered from core contact module in D8.

Just to alter the email format in Drupal 8 we have decided to write a custom module using hook_mail_alter() which alters the outgoing email message using drupal_mail().


Let’s start with code:

To implement hook_mail_alter() whether you can write your own custom module or put it in any of the custom module.

Sample Source code:

/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(&$message) {
  if (isset($message['id']) && $message['id'] == 'contact_page_mail') {
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];
    // Get sender's name.
    $sender_name = $contact_message->getSenderName();
    // Get sender's mail.
    $sender_mail = $contact_message->getSenderMail();
    // Get subject.
    $subject = $contact_message->getSubject();
    // Get message.
    $message_body = $contact_message->getMessage();
    // Get the value of "field_request" field.
    $request_value = $contact_message->get('field_request')->getValue();
  }
}

In Above source code  as you can see that we have added conditional statement so the changes will be impact only on specific mail.  

$message['params']['contact_message']: The message entity stored in the variable and it contains all the values from the contact form. Where contact_message is the type of entity. We can also fetch all the custom field value using get() method.

Source code

hook_mail_alter is solution to customize your mail body send through drupal mail. In this blog i have shared my idea of how can we send custom HTML formatted mail which triggers from Core drupal 8 contact form.  
 

4 Big Data Strategies That Will Transform Media Businesses

Media companies are facing new business challenges with increased pressure to execute new digital production and utilise big data strategies to monetise the opportunities at hand. The media companies need to adopt digital and data strategy, not only to move towards profitability but also to achieve operational efficiency.

Adopting a Multi-distribution Model

In order to deliver content for a variety of platforms/devices, it is critical that companies to establish platforms that can scale up and support this multi-distribution model. Most of the media companies rely on extensive networks of freelancers and subcontractors, thus media companies need resource scheduling toolsets to manage the same.

Insights

Utilising a variety of data sources and operational intelligence  can help media companies gain a better understanding of future customer demands. These data sources include social media, web browsing patterns, advertising response data, demographic data etc. to anticipate demand for more efficient content management, revenue generation and overall profitability. The rise in new tools and analytics, such as cohort are helping drive a better understanding of audience preferences.

Personalised Experiences

Through the captured data, customer needs and wants can be analysed and customised offerings are being offered to enhance customer experiences. Big data and operational analytics is also used to determine the business opportunity linked to the acquisition of new content and gain more advertising revenue growth through better targeting.

Data Management System

Big data management systems are needed to be deployed to analyse different forms of data and to ensure that the business can become more agile. There is always a need to deploy the right tools and capabilities to the right users, thus an optimal technology needs to be chosen depending on the data needs; bridging the gap between data collection and application.

For most publishers of online content, striking the right balance of advertising and operations revenue is an objective, and can be achieved with capturing and analysing accurate big data and analytics.

Combining analytics with operational intelligence will yield good results in the long run. Today’s business environment requires flexibility, speed and accuracy and media companies are making considerable investments in data capabilities to achieve agility. As data volume, velocity and variety grows, investment in data infrastructure and architecture becomes a necessity. By using operational analytics, and coupling it with big data along with available resources will drive the business to achieve efficiencies and deliver better customer experiences.

 

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch