Friday, 21 April 2017

Drupal 8 - Steps to Create a Custom Form

Drupal 8 form API is similar to Drupal 7 Form API. Only difference is, we will be having separate validation and submission forms. 
Drupal 8 even has some new (HTML 5) elements like "color, email, date, url, range, tel, time, week, month etc. 
Reference Link for HTML5 elements supported in Drupal 8: https://www.drupal.org/node/1183606
In Drupal 8 Form classes implement the \Drupal\Core\Form\FormBuilderInterface and the basic workflow of a form is defined by the buildForm, validateForm, and submitForm methods of the interface.
There are a different classes to choose depending on the type of form that we are creating.
  • ConfigFormBase : For creating system configuration forms like the one found at admin/config/system/site-information.
  • ConfirmFormBase : For providing users with a form to confirm an action such as deleting a piece of content.
  • FormBase : The most generic base class for generating forms.
Folder Structure




Create a simple Addressbook custom form in Drupal 8

  • Create a folder with the name "addressbook" in \Root\modules\custom\ folder.
  • Create addressbook.info.yml file with below code.

name: Addressbook
description: An address book form to enter addresses.
core: 8.x
package: Custom
type: module

In Drupal 8 important part of module, theme, or profile is the .info.yml file. It stores metadata about the project. This is almost similar to .info file in Drupal 7.
.info file contains name, description, core, package, dependencies, type values in it. The type key, is something new in Drupal 8. It is required and indicates the type of extension, e.g. module, theme or profile.
  • Create addressbook.routing.yml file with below code.

addressbook.form:

 path: '/addressbook/infoform'
 defaults:
   _title: 'Addressbook form'
   _form: '\Drupal\addressbook\Form\AddressbookForm'
 requirements:
   _permission: 'access content'

Drupal 7 hook_menu() got replaced with this routing system [Creating menus, tabs etc.]. 
A route is a path which return some sort of content on top of it.
For example,  '/about-us' is a route. When Drupal receives a request, it tries to match the requested path to a route it knows about. If the route is found, then the route's definition is used to return content. Otherwise, Drupal returns a 404.
  • Create AddressbookForm.php file in \Root\modules\custom\addressbook\src\Form\ folder with below code.

<?php
/**
* @file
* Contains \Drupal\addressbook\Form\AddressbookForm.
*/
namespace Drupal\addressbook\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class AddressbookForm extends FormBase {

public function getFormId() {
return 'addressbook_form';
}

public function buildForm(array $form, FormStateInterface $form_state) {
$form['full_name'] = array(
'#type' => 'textfield',
'#title' => t('Full Name:'),
'#required' => TRUE,
);
$form['email_id'] = array(
'#type' => 'email',
'#title' => t('Email ID:'),
'#required' => TRUE,
);
$form['contact_number'] = array (
'#type' => 'tel',
'#title' => t('Mobile no'),
);
$form['date_of_birth'] = array (
'#type' => 'date',
'#title' => t('Date of Birth'),
'#required' => TRUE,
);
$form['gender'] = array (
'#type' => 'select',
'#title' => ('Gender'),
'#options' => array(
'Female' => t('Female'),
'male' => t('Male'),
),
);
$form['age_confirmation'] = array (
'#type' => 'radios',
'#title' => ('Are you above 18 years old?'),
'#options' => array(
'Yes' =>t('Yes'),
'No' =>t('No')
),
);
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Save'),
'#button_type' => 'primary',
);
return $form;
}

public function validateForm(array &$form, FormStateInterface $form_state) {
if (strlen($form_state->getValue('contact_number')) < 10) {
$form_state->setErrorByName('contact_number', $this->t('Contact number is too short.'));
} else if (strlen($form_state->getValue('contact_number')) > 10) {
$form_state->setErrorByName('contact_number', $this->t('Contact number is too long.'));
}
}

public function submitForm(array &$form, FormStateInterface $form_state) {
drupal_set_message($this->t('Addressbook Information is being submitted!'));
foreach ($form_state->getValues() as $key => $value) {
drupal_set_message($key . ': ' . $value);
}
}
}


In the above code,

First, we are declaring the namespace, the other classes we want to use, and extend the FormBase class.
Second we are getting code from some other classes, using the use PHP keyword and then the namespace, using the PSR-4 standard, It autoload the classes in the files that correspond to these namespaces
Third we are declaring our AddressbookForm Class which extends FormBase.
Fourth, we are building a Form using buildForm function.
Fifth, we are Validating Form values using validateForm function
Sixth, on successful entry of form data, we are submitting the form using submitForm function

  • Login to Drupal Backend.
  • Go to Extend Menu Item "/drupal8/admin/modules"
  • Enable Addressbook Module.
  • Access addressbook/infoform URL.







Thursday, 20 April 2017

SonarQube with Mysql Setup in Windows along with Steps to Project Analysis

SonarQube Server with Mysql Prerequisites:

Software Requirement:

  • Java (Oracle JRE 8 onwards or OpenJDK 8 onwards)
  • Mysql (5.6 or higher versions)
    • Use UTF-8 charset.
    • Only InnoDB Storage Engine.
    • mysql-connector-java jar is supported.
  • Web browser to Run http://localhost:9000 after SonarQube Installation and server Start.

Hardware Requirement:
1. 1GB of free RAM for the OS.
2. 2GB of RAM to run SonarQube Server.

Mysql Installation:
  • Download Mysql 5.6
    • https://dev.mysql.com/downloads/mysql/5.6.html 
  • Install Mysql.
  • Set Username and Password for the root.
  • Create a Database called "sonarqube"
  • Create a user called sonarqube with All Privileges on sonarqube database.


SonarQube Installation & Starting Server:
  • Download SonarQube 6.3 version.
  • Unzip Downloaded file.
  • Place SonarQube 6.3 folder at any place as per your convenient. 
  • I have kept that folder in D:/softwares/Sonar/ folder.
  • Open sonar.properties file in D:/softwares/Sonar/SonarQube 6.3/conf/ folder.
  • Un comment below lines and set Username and Password of Mysql (Line numbers - 14 & 15).
    • sonar.jdbc.username=sonarqube
    • sonar.jdbc.password=sonarqube
  • Un comment "sonar.jdbc.url" line related to MySQL 5.6 or greater comments (Line Number - 23) and set that line as below.
    • sonar.jdbc.url=jdbc:mysql://localhost:3306/sonarqube?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false
  • Apart from those 3 lines, all other lines should be in commented mode. 
  • Based on your processor specific to OS, you will be having different BIT wise operation folders in BIN directory. in my case, i am using 32 bit processor. so, my folder name will be "windows-x86-32".
  • Start Sonar
    • There are 2 ways to start sonar.
      • Add Sonar specific *.bat files location in Environment Variable.
        • We can find different shell scripts files (*.bat) such as InstallNTService.bat, StartNTService.bat, StartSonar.bat etc in D:/softwares/Sonar/SonarQube 6.3/bin/<OS_BIT_Processor>/ folder.
        • Copy the path of this folder, which may look like D:\softwares\Sonar\sonarqube-6.3\bin\windows-x86-32, and append it to “Path” environment variable.
        • Open a command prompt, type “StartSonar” command and execute. This would start a web server at default port of 9000.
        • Open a web browser and access the page, http://localhost:9000.
      • Open a command prompt.
        • Move to OS_BIT_Processor folder.
          • D:\softwares\Sonar\sonarqube-6.3\bin>
          • Type “StartSonar.bat” command and execute. This would start a web server at default port of 9000.
        • Open a web browser and access the page, http://localhost:9000.
SonarQube Runner Setup
  • Download Sonar Runner.
    • http://repo1.maven.org/maven2/org/codehaus/sonar/runner/sonar-runner-dist/2.4/sonar-runner-dist-2.4.zip
  • Unzip Downloaded file.
  • Place sonar-runner-2.4 folder at any place as per your convenient. 
  • I have kept that folder in D:/softwares/Sonar/ folder.
  • Update the global settings (database connection, server URL) by editing sonar-runner.properties file in D:/softwares/Sonar/sonar-runner-2.4/conf/ folder.
  • sonar-runner-2.4 file code should look like below.
  • set "SONAR_RUNNER_HOME" Environment variable which points to sonar-runner-2.4 folder.
    • Open Control Panel.
    • Click on System Link
    • Click on Advanced System Settings link on Left Navigation.
    • Click on Environment Variables button on System Properties window.
    • Under System Variables Create a New variable with below name and Value.
      • Variable Name-  SONAR_RUNNER_HOME
      • Variable Value-  D:\softwares\Sonar\sonar-runner-2.4\
    • Append this Environmental variable with Path variable data under user variables for <Username>
      • Edit Path Variable under User variables for <Username Section>
      • Append this value to other data.
        • ;%SONAR_RUNNER_HOME%\bin
  • Test Sonar Runner
    • Close all Command Prompt Windows
    • Open New Command Prompt Window
    • Run "sonar-runner.bat -h" command.
    • You should be able to see below data if setup is successful. 

Analyze A Project with SonarQube Runner:
  • Open your project root folder.
  • Create a configuration file with the name sonar-project.properties
  • file should contain values representing project name, unique key, what files should test, what files should exclude etc.
  • Example sonar-project.properties file.
  • Run Sonar on Project
    • Open Command Prompt
    • Move to Project Root Folder.
    • Run "sonar-runner" command.
  • Now go to http://localhost:9000/ URL.
  • Click on Projects link from Navigation Menu.
  • There you can see your Project Name after tests.
  • You can see overall status of project. Either pass or Fail beside to Project Name.

  • Click on that project name link and see fill set of test results as per files.
Note: Whenever you want to execute Sonar Tests, make sure,
  • Mysql is up and Running.
  • Sonar Server is up and Running
    • StartSonar.bat
In case of any issues with Sonar Sever, you can find logs in LOGS folder.
Sonar.log & web.log helps you alot in this process.

java.lang.IllegalStateException: Cannot stop. Current container state was: CONSTRUCTED

This represents, one or more of our plugins are not compatible with Installed Sonar Version.

In my case,

after keeping "sonar-governance-plugin-1.2.0.1659" file in my sonarqube-6.3\extensions\plugins folder, i encountered an issue starting Sonar Server.

Error That i got on running StartSonar.bat

java.lang.IllegalStateException: Cannot stop.  Current container state was: CONSTRUCTED
at org.picocontainer.lifecycle.DefaultLifecycleState.stopping(DefaultLifecycleState.java:72)
at org.picocontainer.DefaultPicoContainer.stop(DefaultPicoContainer.java:794)
at org.picocontainer.DefaultPicoContainer.stop(DefaultPicoContainer.java:799)
at org.picocontainer.DefaultPicoContainer.stop(DefaultPicoContainer.java:799)
at org.sonar.core.platform.ComponentContainer.stopComponents(ComponentContainer.java:174)
at org.sonar.core.platform.ComponentContainer.stopComponents(ComponentContainer.java:169)
at org.sonar.server.platform.platformlevel.PlatformLevel.stop(PlatformLevel.java:97)
at org.sonar.server.platform.Platform.stopLevel234Containers(Platform.java:227)
at org.sonar.server.platform.Platform.doStop(Platform.java:256)
at org.sonar.server.platform.web.PlatformServletContextListener.stopQuietly(PlatformServletContextListener.java:57)
at org.sonar.server.platform.web.PlatformServletContextListener.contextInitialized(PlatformServletContextListener.java:50)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
2017.04.20 09:02:59 ERROR web[][o.a.c.c.C.[.[.[/]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.web.PlatformServletContextListener
java.lang.IllegalStateException: Fail to load plugin Governance [governance]
at org.sonar.server.plugins.ServerExtensionInstaller.installExtensions(ServerExtensionInstaller.java:73)
at org.sonar.server.platform.platformlevel.PlatformLevel4.start(PlatformLevel4.java:527)
at org.sonar.server.platform.Platform.start(Platform.java:203)
at org.sonar.server.platform.Platform.startLevel34Containers(Platform.java:177)
at org.sonar.server.platform.Platform.doStart(Platform.java:100)
at org.sonar.server.platform.Platform.doStart(Platform.java:79)
at org.sonar.server.platform.web.PlatformServletContextListener.contextInitialized(PlatformServletContextListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

at java.lang.Thread.run(Unknown Source)

After Removing that plugin from the plugins folder, i am able to run StartSonar.bat and able to see SonarQube in http://localhost:9000.

Tuesday, 18 April 2017

JIT vs AOT Compilation [Just in Time vs Ahead of Time Compilation]

JIT - JUST in TIME Compilation

  • Compiled in the browser.
  • Each file compiled separately.
  • No need to build after changing your code and before reloading the browser page.
  • Suitable for local development.
AOT - Ahead of Time Compilation

  • Compiled by the machine itself, via the command line (Faster).
  • All code compiled together, inlining HTML/CSS in the scripts.
  • No need to deploy the compiler (Half of Angular size).
  • More secure, original source not disclosed.
  • Suitable for production builds.

Thursday, 31 March 2016

GIT Flow Steps

  1. Create GIT Account
  2. Install GIT [https://git-scm.com/download/win]
  3. Open GIT Bash
  4. Check GIT Version [git --version]
  5. Generate ssh key [ssh-keygen -t rsa -C "OUR-EMAIL_ID"]
  6. Move to .ssh directory in command line [cd C:\users\YOUR_NAME\.ssh]
  7. Copy Public key to Clipboard [clip < ida_rsa.pub>]
  8. Configure Public Key in GIT Account [https://github.com/settings/keys]
  9. Clone GIT Repository: [git clone <YOUR_REPOSITORY_URL>]
  10. Move to your project folder [cd "MYPROJECT_FOLDER" - This is Repository Name]
  11. Check Existing Branches [git branch]
  12. Checkout to Master / Respective branch [git checkout master]
  13. Check Branch Status to Pull / Rebase updates [git status]
  14. Pull updates fron Branch [git pull origin master] - Here master is a branch name.
  15. Create a Feature [git flow feature start "YOUR_FEATURE_NAME"] - Generally features will be used to accomplish a small tasks. If git flow feature start forces an error, please execute "git flow init" first
  16. Publish Feature Branch into GIT [git flow feature publish "YOUR_FEATURE_NAME"]
  17. Make all necessary file changes or creation or deletions as per your task.
  18. Before commiting your changes, pull if any updtaes available.
  19. Add your updated files to GIT [git add "CREATED_OR_UPDATED_FILE"]
  20. Commit added files into GIT [git commit -v] - Provide test and save changes and commit.
  21. Then push your branch changes [git push origin "YOUR_FEATURE_NAME"]
  22. Then Pull Request in GIT.
  23. Merge Branch Changes into Master. 
  24. Check out to Master branch and delete all unnecessary local Branches. [git branch -d "YOUR_FEATURE_NAME"]

Thursday, 14 January 2016

Drupal 7 - Open Graph Selected images are not sharing into Facebook when both Image field and Description box contains images.

Basic Configuration to test and solve this problem:
Create a content type with One Image Field and Body Field (Those are needed to replicate it)

Successful Scenarios:
Scenario 1:
1. Add new content for the above content type with images upload by Image Tool only (Image Field)
3. Select image from those uploaded images using Open Graph Configuration and saved the node.
4. If we are sharing that article, whatever the image that we have shared, that will get shared in Facebook

Scenario 2:
1. Add new content for the above content type with images upload by body field only (Through Text Editor Media / IMCE)
3. Select image from those uploaded images using Open Graph Configuration and saved the node.
4. If we are sharing that article, whatever the image that we have shared, that will get shared in Facebook

Unsuccessful Scenario:
1. Add new content for the above content type with images upload by both image tool and body field (Editor).
2. Select an image from those uploaded images using Open Graph Configuration and saved the node.
3. If we are sharing that article, whatever the image that we are trying to share, will not get shared into Facebook.

The original problem behind this is opengraph_meta module will generate images array with URL, alt and title sort of text using a function called "harvest_images_from_node". this function definition is available in opengraph_meta.common.inc file. after forming the array of images, if we remove duplicate images and order them as needed by system, this image sharing issue will get resolved. To do that follow below steps.

Solution:
1. Open file opengraph_meta.common.inc
2. Search for function "harvest_images_from_node".
3. there replace return of result stagement with below code.
    Existing Line: return $ret;
    Update TO:
        $ret = array_map("unserialize", array_unique(array_map("serialize", $ret))); // Remove Duplicates
        $result = array_values($ret); // Reorder them
        return $result; // Return Result images.
       
Now check Unsuccessful Scenario. It will work fine. if it is not working, please clear Facebook cache for existing web pages.

Drupal 7 - Avoid sending thumbnail images to Facebook using Open Graph Meta Tags

Using Default Open graph Meta tags module, if we select an image from the list and trying to send to facebook, it tag og:image with thumbnail version. Facebook won't allow lesser dimension images while sharing. So, whatever that we want to display in facebook won't be shared in this case. It might take Logo or any image from Web Page.

To Resolve this problem, we can have a below patch code.

STEP1:
1. Open file opengraph_meta.common.inc
2. Search for a function which is used to render meta tag data for the given node. function name is "render_data". Line Number:249
3. Add below code after 258 line [i.e., after if (array_key_exists($field, $this->tags_already_output)) {}]
$images = OpenGraphMeta::instance()->harvest_images_from_node($node);
if (!empty($images)) {
  $image_selector_options = array();
  foreach ($images as $url => $image) {
    $image_selector_options[$url] = $image;
  }
}
4. Add below code after 264 line [i.e., After "case self::IMAGE:" line]
    $imageId = is_numeric($v) ? $v : 0;
5. Change below line to specified one
    Existing line: $v = url(ltrim($v,'/'), array('absolute' => TRUE));
    Update to: $v = $image_selector_options[$imageId]['url'];
6. Save Changes
   
STEP2:
1. In the same opengraph_meta.common.inc file there is a function to extract image fields. change them to form image from file_create_url instead of image_style_url
2. Search for a function "extract_image_fields"
3. Change below line to specified one.
    Existing line: $url = image_style_url('thumbnail', $fields[$_uri_field]);
    Update to: $url = file_create_url($fields[$_uri_field]);
4. Save Changes
   
STEP3:
1. In opengraph_meta.module, there is a function which will be used to display thumbnails in admin panel while creating or updating node. we have to update that to take original URL and also update the function to taken first image as default one if nothing got selected.
2. Open opengraph_meta.module file
3. Change below code to specified one
    Existing Code
        foreach ($images as $image) {
            $image_selector_options[$image['url']] = OpenGraphMetaDrupalLayer::theme_selector_image($image);
          }
    Update to:
        foreach ($images as $url => $image) {
            $image_selector_options[$url] = OpenGraphMetaDrupalLayer::theme_selector_image($image);
        }
        $old_value = !empty($node->opengraph_meta) ? $node->opengraph_meta[OpenGraphMeta::IMAGE] : '';
        $default = $old_value && isset($image_selector_options[$old_value]) ? $old_value : key($image_selector_options);

4. Change below line to specified one for taking default value in admin configurations section of node add/update.
    Existing Line:
        '#default_value' => !empty($node->opengraph_meta) ? $node->opengraph_meta[OpenGraphMeta::IMAGE] : '',
    Update To:
        '#default_value' => $default,
1. Save changes.

Now we can check from both frontend and backend whether images are sending with full width and height or not. After updating these also if you could not able to see changes in sharing image to FB, we have to clear cache from Facebook using Developer link.

Create a user with only access to SFTP and not to SSH (Shell Executions)

STEP 1:-
Create a Group, which restricts users created under that group are not to move out of their Home Directory. This one we have to do it in sshd_config file.

This example is with SSH and VSFTPD modules. make sure those are installed in your linux box.

SSHD_CONFIG location would be in /etc/ssh/sshd_config

Enable / Add below line in  sshd_config file.
Subsystem sftp internal-sftp

# This section must be placed at the very end of sshd_config
Match Group sftpaccessonly
    ChrootDirectory /home/%u
    ForceCommand internal-sftp
    AllowTcpForwarding no

STEP2:
Create a Group with the name "sftpaccessonly"
$ groupadd sftpaccessonly

STEP3:
Go to HOME directory
$ cd /home

Create a User in home directory

$ adduser <your_user_name>

It prompts you a screen to enter password of the user along with other details like their Full Name, Room Number etc.
Enter all details and Confirm that those details are correct.
Now user got created.

STEP4:
Add user to the Group "sftpaccessonly"
$ usermod <your_user_name> -g sftpaccessonly

STEP5:
Restrict that specific user to execute any shell commands. To deny SSH shell access, run the following command:
$ usermod <your_user_name> -s /bin/false

STEP 6:
It is very important that root user is having full access on newly created user account.
$ sudo chown root /home/<your_user_name>

STEP 7:
Add write permissions to the directory <your_user_name> and all its contents for user and deny write access for everybody else.
$ sudo chmod go-w /home/<your_user_name>

OTHER STEPS:
create a directory / directories where user wants to have access to them.
sudo mkdir /home/<your_user_name>/<your_directory_name>

Give Permissions to the user with the specified group
sudo chown <your_user_name>:sftpaccessonly /home/<your_user_name>/<your_directory_name>

Give writable permissions.
sudo chmod ug+rwX /home/<your_user_name>/<your_directory_name>

Final STEPS:
Restart SSH
$ service ssh restart

Restart vsftpd
$ service vsftpd restart

Now you can login with the created credentials using SFTP. user can only access to their home directory specific folders which you have provided permissions.

Same users you can not login through SSH.









Thursday, 15 October 2015

504 Gateway Timeout Error in Nginx Server

When we are dealing with large Drupal / Wordpress setup in Nginx Server with limited resources, then we will be facing the “504 Gateway Time-out” error.

There are 2 ways to control / fix this problem.
  • By Increasing PHP Execution Time from Nginx level.
  • Minimize the Code execution time by optimizing server calls (This is with respect to programming).
In this Article, i would like to show First point of Increasing PHP Execution Time from Nginx Level.
We can follow below steps to increase the php timeout value. By default it's max execution time will be 30s. Now we will increase that to 500 (These seconds depends on your usage). 

In General of Apache server, if we increase max_execution_time in php.ini file and restart php server will work. but in Nginx, we have to do changes in 2 more places and restart both PHP-FPM & Nginx.

  • Change max_execution_time in php.ini file.
    • Connect to Linux -> Nginx Server Command Prompt
    • Open PHP.INI file -> vim /etc/php5/fpm/php.ini
    • Change Max Execution Time to 500 seconds -> max_execution_time = 500 
  •  Change request_terminate_timeout in PHP-FPM
    • This change needs to be done only if we have un commented request_terminate_timeout line before. As it is commented by default, it takes value of max_execution_time from php.ini
      • Open www conf file - vim /etc/php5/fpm/pool.d/www.conf
      • Change Request Terminate Timeout value to 500 -> request_terminate_timeout = 500
  • Change fastcgi_read_timeout value in Nginx Config
    • If we want to increase timeout value only for one site, follow below steps.
      • vim /etc/nginx/sites-available/oursitename.com
      • location ~ \.php$ {
                include /etc/nginx/fastcgi_params;
                fastcgi_pass  unix:/var/run/php5-fpm.sock;
                fastcgi_read_timeout 300;
          }
    • If we want to increase time limit for all sites in our server, we can edit main nginx.conf file itself
      • vim /etc/nginx/nginx.conf
      • Add 'fastcgi_read_timeout' in http{} section
      • http { 
           ---Other Lines of code --  
           fastcgi_read_timeout 500; 
           ---Other Lines of code -- 
        }
  • Reload PHP-FPM and Nginx
    • Reload PHP-FPM -> service php5-fpm reload 
    • Reload Nginx -> service nginx reload

Thursday, 28 May 2015

Linux Commands

Mostly Used Commands:

vi filename.extension                                                        - Open a file in editing mode.
:42   (or) vi +42 filename.extension                                  - Move to a particular in a file
Ctrl-Shift-g                                                                     - To check the line number where we are in.
/searchstring                                                                   - Search for a string in a file [Next Occurance of String - Press 'n'  ,  Previous Occurance of string - Press 'Shift-n']

Quitting

:x    Exit, saving changes
:q    Exit as long as there have been no changes
ZZ    Exit and save changes if any have been made
:q!    Exit and ignore any changes

Inserting Text

i    Insert before cursor
I    Insert before line
a    Append after cursor
A    Append after line
o    Open a new line after current line
O    Open a new line before current line
r    Replace one character
R    Replace many characters

Motion

h    Move left
j    Move down
k    Move up
l    Move right
w    Move to next word
W    Move to next blank delimited word
b    Move to the beginning of the word
B    Move to the beginning of blank delimted word
e    Move to the end of the word
E    Move to the end of Blank delimited word
(    Move a sentence back
)    Move a sentence forward
{    Move a paragraph back
}    Move a paragraph forward
0    Move to the begining of the line
$    Move to the end of the line
1G    Move to the first line of the file
G    Move to the last line of the file
nG    Move to nth line of the file
:n    Move to nth line of the file
fc    Move forward to c
Fc    Move back to c
H    Move to top of screen
M    Move to middle of screen
L    Move to botton of screen
%    Move to associated ( ), { }, [ ]

Deleting Text

Almost all deletion commands are performed by typing d followed by a motion. For example, dw deletes a word. A few other deletes are:
x    Delete character to the right of cursor
X    Delete character to the left of cursor
D    Delete to the end of the line
dd    Delete current line
:d    Delete current line

Search for strings

/string    Search forward for string
?string    Search back for string
n    Search for next instance of string
N    Search for previous instance of string

Replace

The search and replace function is accomplished with the :s command. It is commonly used in combination with ranges or the :g command (below).
:s/pattern/string/flags    Replace pattern with string according to flags.
g    Flag - Replace all occurences of pattern
c    Flag - Confirm replaces.
&    Repeat last :s command

Regular Expressions

. (dot)    Any single character except newline
*    zero or more occurances of any character
[...]    Any single character specified in the set
[^...]    Any single character not specified in the set
^    Anchor - beginning of the line
$    Anchor - end of line
\<    Anchor - begining of word
\>    Anchor - end of word
\(...\)    Grouping - usually used to group conditions
\n    Contents of nth grouping

[...] - Set Examples [A-Z]    The SET from Capital A to Capital Z

[a-z]    The SET from lowercase a to lowercase z
[0-9]    The SET from 0 to 9 (All numerals)
[./=+]    The SET containing . (dot), / (slash), =, and +
[-A-F]    The SET from Capital A to Capital F and the dash (dashes must be specified first)
[0-9 A-Z]    The SET containing all capital letters and digits and a space
[A-Z][a-zA-Z]    In the first position, the SET from Capital A to Capital Z
In the second character position, the SET containing all letters

Regular Expression Examples /Hello/    Matches if the line contains the value Hello

/^TEST$/    Matches if the line contains TEST by itself
/^[a-zA-Z]/    Matches if the line starts with any letter
/^[a-z].*/    Matches if the first character of the line is a-z and there is at least one more of any character following it
/2134$/    Matches if line ends with 2134
/\(21|35\)/    Matches is the line contains 21 or 35
Note the use of ( ) with the pipe symbol to specify the 'or' condition
/[0-9]*/    Matches if there are zero or more numbers in the line
/^[^#]/    Matches if the first character is not a # in the line
Notes:
1. Regular expressions are case sensitive
2. Regular expressions are to be used where pattern is specified

Counts

Nearly every command may be preceded by a number that specifies how many times it is to be performed. For example, 5dw will delete 5 words and 3fe will move the cursor forward to the 3rd occurence of the letter e. Even insertions may be repeated conveniently with thismethod, say to insert the same line 100 times.

Ranges

Ranges may precede most "colon" commands and cause them to be executed on a line or lines. For example :3,7d would delete lines 3-7. Ranges are commonly combined with the :s command to perform a replacement on several lines, as with :.,$s/pattern/string/g to make a replacement from the current line to the end of the file.
:n,m    Range - Lines n-m
:.    Range - Current line
:$    Range - Last line
:'c    Range - Marker c
:%    Range - All lines in file
:g/pattern/    Range - All lines that contain pattern

Files

:w file    Write to file
:r file    Read file in after line
:n    Go to next file
:p    Go to previos file
:e file    Edit file
!!program    Replace line with output from program

Other

~    Toggle upp and lower case
J    Join lines
.    Repeat last text-changing command
u    Undo last change
U    Undo all changes to line

Tuesday, 8 July 2014

Drupal 7 - CKEditor - Create Custom Styles.

To Create Our Own Styles to display them in CKEditor, we have to follow below mentioned steps.

Adding Styles Drop down to CKEditor:
  • By default, CKEditor will not be having option to select styles.
  • Add styles down to editor by configuring CKEditor Settings.
    • Go to Configuration -> Content Authoring -> CKEditor (admin/config/content/ckeditor)
    • Select Edit option related to the Profile Which you are using in your application. In my case i am using Full Profile. So, clicking on Edit option related to Full Profile (admin/config/content/ckeditor/edit/Full)
    • Expand Edit Appearance fieldset by clicking on  Edit Appearance toggle set.
    • Place Styles Drop down into Used Buttons region from Full Buttons Region
    •  Click on Save button at the bottom of page.
Create Custom Styles:
  • Custom CSS can be created from ckeditor.styles.js file.
  • This file by default got located in /sites/all/modules/ckedior/ckeditor.styles.js.
  • Copy the file and place it in your user current theme folder. In my case my UI theme is bartik. So, i am placing ckeditor.styles.js file into /themes/bartik/ckeditor.styles.js.
  • Open the file.
  • Remove unnecessary styles from list.

  • Add your own styles.
    • Example: If you want add "cinimatography" class to selected text with an additional div added to it, use below code.
      • { name : 'Cinematography' , element : 'div', attributes : { 'class' : 'cinimatography' } },
    • Name: This value will get displayed in CKeditor's Styles Drop down.
    • Element: Tag will be added to the selected text.
    • attributes: We can able add classes to the elements.
    • styles: We can able to add property value pairs. Example, color, background-color etc.
  • After adding all the necessary styles, you can Save the file.
Make sure our Custom Styles get displayed in CKEditor Properly:
    • To Display our custom CSS in Styles drop down, first we have to tell the CKEditor to consider ckeditor.styles.js file from our theme folder. To do that,
    •  Go to Configuration -> Content Authoring -> CKEditor (admin/config/content/ckeditor)
    • Select Edit option related to the Profile Which you are using in your application. In my case i am using Full Profile. So, clicking on Edit option related to Full Profile (admin/config/content/ckeditor/edit/Full)
    • Expand CSS fieldset by clicking on CSS toggle set.
    • There you could able to see different options. We have to configure them.
      • Change Predefined styles to
        Define path to ckeditor.styles.js
      •  Set Predefined styles path to %tckeditor.styles.js?v1 (%t – path to current user theme. By Default Drupal 7 uses bartik theme. If you did not enable any other theme, your theme would be bartik only.)
    • Expand Advanced Options fieldset by clicking on Advanced Options toggle set.
    • There you could able to see Custom JavaScript configuration Text area.
    • Add config.allowedContent = true; line into that text area. This option is used to allow CKEditor to hold the classes, styles that we are adding using editor.
    • After making all changes. Save the Configuration form.


Go to Content Add / Edit Page. See that new updates available under Styles Drop Down.

Tuesday, 1 April 2014

HTML5 LocalStorage vs Cookies?

Cookies are having limited Storage Capacity upto 4096 Bytes.
Local Storage is having capacity to store data upto 5MB

Using Local Storage we no need to parse a string to get data. Instead you can make a call for the variable name and it's value is returned. The same applies with creating and deleting data as well.

Local Storage Is not sent with every HTTP request.
Cookies are sent with every HTTP request.

Each domain stores all its cookies in a single string, which can make parsing data difficult.

JQuery $ vs $.fn?

$.fn points to the jQuery.prototype. Any methods or properties we add to it become available to all instance of the jQuery wrapped objects.



$.fn we will be using to create plugins and can be called using $(<someselector>).pluginname();

$.something adds a property or function to the jQuery object itself.

Use the first form $.fn.something when we're dealing with DOM elements on the page, and our plugin does something to the elements.

Use $.something When the plugin has nothing to do with the DOM elements.

Tuesday, 4 March 2014

IIS - NON WWW to WWW URL Redirection.

URL Redirection using IIS 7.0 / 7.5.
In IIS server, we have an option called URL Rewrite.

Steps to Redirect an URL:
--------------------------

  • Open IIS Manager (Internet Information Services Manager).
  • Double Click on URL Rewrite Icon.

  • Click on Add Rules link under Actions Pane on Right Side bar.
  • Select Blank Rule option from the Popup window and click on OK
  • Provide Rule Name as "Non www mysitename.com to www"
  • Select Match URL using "wildcards".
  • Expand Conditions box
    • Click on Add Condition link on right sidebar.
    • Make Condition input as {HTTP_HOST}
    • Select Input string as "Matches the Pattern"
    • pattern as mysitename.com
    • Click on OK
  • Set Action under Action Box
    • Select Action Type as "Redirect"
    • Fill Redirect URL as "http://www.mysitename.com/{R:0}" under Action Properties Section.
    • Check Append Query String Checkbox
    • Select Redirect Type as "Permanent 301"
  • Click on Apply link on Right Side bar

Using Simple Text Editor Also we can Redirect the URL:
---------------------------------------------------------------

Wildcard based redirection:

<rewrite>
    <rules>
        <rule name="Non www mysitename.com to www" patternSyntax="Wildcard" stopProcessing="true">
            <match url="*" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="mysitename.com" />
            </conditions>
            <action type="Redirect" url="http://www.mysitename.com/{R:0}" />
        </rule>
    </rules>
</rewrite>

Regular Expression based URL redirection:

<rewrite>
    <rules>
        <rule name="Non www mysitename.com to www" patternSyntax="ECMAScript" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^mysitename.com$" />
            </conditions>
            <action type="Redirect" url="http://www.mysitename.com/{R:0}" />
        </rule>
    </rules>
</rewrite>

Saturday, 1 March 2014

Explain lifecycle of a JSP?

A JSP Lifecycle consists of following phases:
  • Compilation: When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
    The compilation process involves three steps:
    • Parsing the JSP.
    • Turning the JSP into a servlet.
    • Compiling the servlet.
  • Initialization: When a container loads a JSP it invokes the jspInit() method before servicing any requests
  • Execution: Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
  • Cleanup: The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method for servlets.

What are the advantages of JSP over Server-Side Includes (SSI)?

SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like.

What are the advantages of JSP over Pure Servlets?

JSP is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. Other advantages are:
  • Embedding of Java code in HTML pages.
  • Platform independence.
  • Creation of database-driven Web applications.
  • Server-side programming capabilities.

What are the advantages of JSP over Active Server Pages (ASP)?

JSP is portable to other operating systems and non-Microsoft Web servers.

What are advantages of using JSP?

JSP offer several advantages as listed below:
  • Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself.
  • JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
  • JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
  • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.

What are JSTL formatting tags ?

The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web sites.

Following is the syntax to include Formatting library in our JSP:
<%@ taglib prefix="fmt" 
           uri="http://java.sun.com/jsp/jstl/fmt" %>