Sunday, July 23, 2017

Playing with template in Joomla 3.x

Template is the heart of Joomla. Almost of things which you need for your website, just do them in your template. In the template, you can override other extensions (components & modules)  without touching to their source code. So you can easily update new versions of the extensions or Joomla without impacting to the front end of your website. This is very important because Joomla community often releases security fixes which you should update immediately for your website if any.

In this article, I will collect & introduce to you some tips which you can play with Joomla's template to setup your website beautifully, quickly and security.

1. Uninstall unnecessary templates

If you don't use a template, let remove it. Less code that means your website is more lightweight, faster and more security. Below the steps to install a template:
  • Go to menu Extensions >> Manage >> Manage
  • Click Search Tools button >> select type as Template >> click the check box of a template wanted to install >> click Uninstall button.

This will remove permanently all source code of the template from your site.

2. Edit source code of a template, code your website on mobile devices

Joomla 3.x provides an editor for editing source code of any template. It is very powerful. I think it is a strength of Joomla against the other CMS. With this editor, you can code your website when you are travelling on mobile devices like smart phone or tablet.
To open the editor for your template, go to Extensions >> Templates >> Templates >> click on the template name:
It will open a screen with files & folders of source code in left side. Here you can do many actions via buttons on the top. Click Documentation button if you want to learn more about this editor. To edit a file, click on its name:


Above are buttons I often use. The right side is source code of selected file. To change for editing the other file, just click on its name. Soo cool 👍

3. Compile LESS file

Another weapon of Joomla is it supports to compile LESS file directly on the template editor. You don't need to install any extra tool. To know what is LESS, let read: http://lesscss.org.

LESS files are often in less folder. If you open a LESS file on the editor, it will show Compile LESS button. After compiling, it will translate into a CSS file corresponding with LESS file in css folder. The template file uses CSS file to present its styles.


4. Create overrides for extensions

In manual way, you must copy the original PHP file from the source of extension into a proper place in your template directory. The correct directory structure for your override file is:
templates/TEMPLATE_NAME/html/EXTENSION_NAME/VIEW_NAME/FILE_NAME.php
You can read here for an example.

However in Joomla 3.x, you can also create overrides for extensions by clicking Create Overrides tab then click an extension (module, component, layout) which you want to override in the template manager.


5. Customize Protostar template

As a beginner of Joomla template coding, one of the fastest way is studying & customizing an existing template. What is good template for you starting? I recommend the Protostar template. It is one of the two front-end templates included with a Joomla 3.x source code. Protostar likes a blank responsive template, it is simple but displays well on many devices. So you can build your own template from this template with a basic knowledge about PHP, JavaScript & CSS.

In this section, I give an example on how to create a mobile menu which displays all submenus without touching on parent menu. By default, a submenu will be showed when hovering on parent menu. You can do this action on desktop with mouse, but cannot in a mobile with touching screen. It causes your submenu is never reached on the mobile.

By adding below code into template.less file (in @media query for mobile screen) and re-compile it in the template editor, you will have a proper menu on mobile:

@media (max-width: 480px) {
//start changes
    .navigation .nav-child {
        display: block;
        position: unset;
        float: unset;
        border: unset;
        box-shadow: unset;

        &:before {
            display: none;
        }
    }
    .navigation .nav > li > .nav-child {
        &:before {
            display: none;
        }
    }
//end changes
    .item-info > span {
        display:block;
    }
    .blog-item .pull-right.item-image {
        margin:0 0 18px 0;
    }
    .blog-item .pull-left.item-image {
        margin:0 0 18px 0;
        float:none;
    }
}

Here are screens for desktop and mobile:

It's time to go to bed. Bye everyone! Any comment is welcome.

Friday, July 14, 2017

Learn Selenium (a Test Automation Tool) with C# - Part 2

In this part, we will learn how to a test application to do login Facebook automatically.

For beginning, I want to introduce about XPath. It is a major element in the XSLT standard. XPath can be used to navigate through elements and attributes in an XML document. You can read more about it on here.

In Selenium we will use XPath to find element(s) then make action according to the scenarios for testing.

If you are familiar with FireFox, you can use Firebug and FirePath add-on. They are very popular and strong tools for FireFox web developer. You just need to install them, open a website which you want to test, open Firebug >> click FirePath tab >> click the pointer and select an element on the page for getting its XPath value. See the following picture for example:


If your are familiar with Chrome, you can use XPath-Helper extension. But I recommend you use a built-in function of Chrome DevTools. Just open the website, press F12 then press Ctrl + F to enable DOM searching box. Using pointer to point an element then key a XPath value in to searching box for finding matched elements. If the matching is only 1, it is the XPath for this element.


For searching, you can try the first search with syntax:  .//*[@attribute-name='value']
For example a element having id="email", you can try: .//*[@id='email']

Another way on Chrome is using Console panel of Chrome DevTools with the function $x("XPath value"). For example: $x(".//*[@id='email']")

OK, that's enough for XPath. It's time to code our test application. Yes, let see the code first and I will explain later:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumTutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver wd = new ChromeDriver(@"E:\working\abc\SeleniumTutorial");
            wd.Url = "https://www.facebook.com/";
            wd.Manage().Window.Maximize();
            wd.FindElement(By.XPath(@".//*[@id='email']")).SendKeys("your_email@domain.com");
            wd.FindElement(By.XPath(@".//*[@id='pass']")).SendKeys("your_password");
            wd.FindElement(By.XPath(@"//input[@value='Đăng nhập']")).Click();

        }
    }
}


Comparing with Part 1, the blue codes are new. In which:
wd.Manage().Window.Maximize(); ==> to maximize the browser window

Next 2 lines are for finding email box, password box and input (SendKeys) its values. The last line is for finding login button (it depends on the language used on the browser, mine is Vietnamese ). See below picture for more understanding:


Why I don't use @id to find login button? Because I recognize that Facebook changes this id frequently. So I use its value instead of.

Walking through Part 1 & Part 2, I believe that you have enough basic knowledge to start your automation test application with Selenium. Let's practice.

Happy coding! Any comment is welcome.



Thursday, July 6, 2017

Learn Selenium (a Test Automation Tool) with C# - Part 1

Selenium is a set of different software tools each with a different approach to supporting test automation. You can read more about Selenium via its website: http://www.seleniumhq.org/docs/01_introducing_selenium.jsp#introducing-selenium

Selenium has 2 version 1.0 and 2.0. During this article, I just mention about Selenium 2.0. Basically, it is used for testing web application by automation program written by Java, C#, Python... To do that, the test application (created by a tester) will control the browser which the web application (need to be tested) runs on via Selenium webdriver. The browser can be Chrome, FireFox, Internet Explorer... Each browser has a corresponding webdriver to control it.

In this post, I want to introduce Selenium with C#. To start, you must install MS Visual Studio - MSSV (2015 community is preferred) and download Selenium client & webdriver. Below are steps to create

1. Open MSVS and create new C# Windows project, see the following picture for example:

2. Add references for Selenium client & webdriver. There are 2 ways.
     2.1 Use Add Reference menu:



     2.2 Use Manage NuGet Packages menu:



I prefer 2.1 way. If you use Chrome Webdriver, you need to download the latest version from: http://chromedriver.storage.googleapis.com/index.html and unpack it into your project folder. Now you can create a simple test application.

3. Code your test application. Below is simple code for opening Chrome with google.com website
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumTutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver wd = new ChromeDriver(@"E:\working\abc\SeleniumTutorial");
            wd.Url = "http://google.com";
        }
    }
}


In which, @"E:\working\abc\SeleniumTutorial" is the folder containing Chrome Webdriver (chromedriver.exe).

Yeah! We already knew how to start a C# project with Selenium. I think that's enough for Part 1. In Part 2, we will learn more details how to code a test application with some real test scenarios, for example how to login Facebook automatically.

Any comment is welcome. Have a great day!

Friday, June 30, 2017

Prevent Petya/Petwrap/NotPetya Ransomware Attack

This week, new ransomware called Petrwrap (NotPetya) attacked Windows PC across the globe today. It locks hard drive MFT and MBR sections and preventing computers from booting. Unless victims opted to pay hacker $300 by BitCoin (which is not recommended), there was no way to recover their systems.


Unfortunately Amit Serper (a security expert) has found a way to prevent the Petya(NotPetya/SortaPetya/Petna) ransomware from infecting computers. The solution is create C:\Windows\perfc file and make it read only. This batch file can help you for quickly: https://github.com/vnheros/utilscripts/blob/master/nopetyavac.bat. It also creates perfc.dat and perfc.dll for more secure. Let run it with Administrator right:




Here are emails which are used to send infected attached files (don't open email when receiving from theses emails):
  • wowsmith123456@posteo.net
  • iva76y3pr@outlook.com
  • carmellar4hegp@outlook.com
  • amanda44i8sq@outlook.com
Another required actions are:
  • Let update your Windows, especially patches for MS17-010, CVE 2017-0199.
  • Disable SMB port: 445/137/138/139
  • Remove WMIC (Windows Management Instrumentation Command-line) tool
Hope you are safe after this attack storm!

Thursday, June 22, 2017

Create a Luis Chat Bot on Azure Bot Service - Part 2

In Part 1, you already knew how to create an Azure Chat Bot and deploy it from a local repository. In this article, I'll show you how to apply a Luis app into the bot and how to integrate it with Facebook Messenger.

1. Go to luis.ai website and create an app.
This Luis app will be used for a Pizza shop, so we create 3 intents: greeting, pizza and noservice. We also create an simple entity named topping:


And below are utterances for intents:
Here are another samples of utterances for pizza intent (you should map label topping every time inputting):
can i have pizza with pineapple and bacon
i would like a pizza with cheese bacon and pineapple
may i have pizza with pineapple and sausage
can i get tomato with cheese on my pizza
my pizza should have goat cheese and mozzarella on it

You can add more utterances. After inputting data, click Train & Test link and click Train Application button. Then keying sentences into Interactive Testing box:

If the training & test are ok, let publish the app:



2. Congratulation! You already had first Luis app, let link it with your bot service on Azure. Open the bot on Azure, click on SETTINGS tab and select the Luis app then click Save changes button:

Now, we will enhance the bot with power from the Luis app. Below is the code of the bot, it will recognize intents & entities from chat message to make corresponding response:

"use strict";
var builder = require("botbuilder");
var botbuilder_azure = require("botbuilder-azure");
var useEmulator = (process.env.NODE_ENV == 'development');
var connector = useEmulator ? new builder.ChatConnector() : new botbuilder_azure.BotServiceConnector({
appId: process.env['MicrosoftAppId'],
appPassword: process.env['MicrosoftAppPassword'],
stateEndpoint: process.env['BotStateEndpoint'],
openIdMetadata: process.env['BotOpenIdMetadata']
});

var bot = new builder.UniversalBot(connector);
var luisAppId = process.env.LuisAppId;
var luisAPIKey = process.env.LuisAPIKey;
var luisAPIHostName = process.env.LuisAPIHostName || 'api.projectoxford.ai';

const LuisModelUrl = 'https://' + luisAPIHostName + '/luis/v2.0/apps/' + luisAppId + '?subscription-key=' + luisAPIKey + '&verbose=true';

var recognizer = new builder.LuisRecognizer(LuisModelUrl);

var intents = new builder.IntentDialog({ recognizers: [recognizer] })
.matches('None', (session, args) => {
    session.send('Hello, welcome to Pizza Shop. How may I help you?');
})
.matches('greeting', (session, args) => {
    session.send('Hello, welcome to Pizza Shop. How may I help you?');
})
.matches('pizza', (session, args) => {
    var topping = builder.EntityRecognizer.findEntity(args.entities, 'topping');
    if(topping) session.send('Thank you for ordering. Your pizza with %s will be delivered to you in 30 minutes.', topping.entity);
    else session.send('Thank you for ordering. Would you like your pizza with anything else?');
})
.matches('noservice', (session, args) => {
    session.send('Thank you for ordering but we only sell pizza. Comeback later if you want a pizza.');
})
.onDefault((session, args) => {
    session.send('Sorry! I am a support bot, I did not understand \'%s\'. Please call XXXXX, our staff will be happy to help you.', session.message.text);
});

bot.dialog('/', intents);

if (useEmulator) {
    var restify = require('restify');
    var server = restify.createServer();
    server.listen(3978, function() {
        console.log('test bot endpont at http://localhost:3978/api/messages');
    });

    server.post('/api/messages', connector.listen());

    } else {
        module.exports = { default: connector.listen() }
}

Ok, let see our bot working:



3. We now have a bot serving our Pizza Shop, let connect it with Facebook so our customers can order pizza via Facebook messenger :)

To do that, you must have a Facebook Page and a Facebook Application. In the case of you don't have your Facebook Page, you can read this article for how to. If you don't have any Facebook Application, you can read here to register one.

Assuming that you already had your Facebook Application, go to link https://developers.facebook.com and open the application. Below is mine for example:

(Picture 1)

In the above picture, I already added Messenger product into my app. If you don't add yet, click + Add Product link >> find Messenger product then click Get Started button to add (see the following picture).


After that, go to https://dev.botframework.com/bots, open your bot on MS Bot Framework, find Facebook Messenger in Add a channel section then click to add and configure it. Scroll down to Callback URL and Verify Token for Facebook and copy values of Callback URL and Verify Token. They will be used for configuring Webhooks on your Facebook Application.

(Picture 2)

Back to the Facebook Application, click Setup Webhooks button to verify the callback URL of your bot:
(Picture 3)

Provide values copied from your bot (Picture 2) in to the opened box, select Subscription Fields (events) you want:


And click Verify and Save button. When done, let select your Facebook Page and click Subscribe button to subscribe the webhook to the page events:


To enable your app to send and receive messages using your Facebook Page for everyone coming to your page (public), you must add pages_messaging and submit to review (see this link https://developers.facebook.com/docs/messenger-platform/app-review for more info on this process) :


Otherwise you must add Developers or Testers for testing. You can do via Roles function:


Yeah! You finished necessary steps on Facebook. Return to the configuration of Facebook Messenger on your bot, let key values from Facebook into:



Facebook Page ID: find on the About menu of your Facebook Page:
Facebook App ID & App Secret: get from the dashboard of your Facebook App (Picture 1).
Page Access Token: get from Picture 3 when you select your page.

After keying above values, click Save button, your bot now is connected with Facebook Messenger:
It's time for talking with your bot. You can try via https://www.messenger.com/t/<Your Page ID> or use Facebook Messenger on your mobile:

Those are basic steps for creating your bot with MS Bot Framework and connect it with channels like Facebook Messenger. I hope you have a quick start for your bot.

Good luck! Any comment is welcome.


Subscribe to RSS Feed Follow me on Twitter!