NodeJS – Kickstart

In this tutorial i am gonna talk about Node.js so that you will kick your engine to start developing Node.js Applications.

After this lesson, you will be able to:

  • Install Node.js.
  • Create Node.js webpage.
  • Understand Node.js basics.
  • Understand how data is sent to the server.
  • Understand to write Node.js websites.
  • Create Node.js Modules.
  • Create Node.js Package.
  • Create package.json file.
  • Create account in node package manager.
  • Publish the package.
  • Install and use the package.
  • Uninstall the package.
Estimated lesson time: 2 hours 45 minutes

Before you begin

You must have some understanding of web development and specially for Node.js . But do not worry i am here now we will talk about nitty gritty of essential components of Node.js.

Getting started with Node.js

The back bone of Node.js is Google Chrome Javascript runtime for building easy, fast scalable network applications. The platform is perfect for real time data driven applications because for applications that runs across distributed devices needs efficiency and lightweight non-blocking I/O model.
Node.js uses Google’s V8 virtual machine to interpret and execute your javascript code.

Installation

First, install the latest stable version of Node.js, download the version for your machine from Nodejs.org and run the installer. You will find the primary executable node.exe in the installation folder.

To verify that Node is set up correctly, by typing the below commands on the command line. This should output a version number:

C:> node -v

Creating Hello World from Node.js

After the installation has been done successfully, now you are able to write your first ever NodeJs application. Nothing is better getting starting with “Hello World” app. It’s kind of mandatory saying hello to the world before you ever jump in to something (kidding). So without further a do lets do this…

Open up your favorite text editor you wanna write into and write the following script:

var http=require('http');

http.createServer(function(request, response)){

response.writeHead(200,{'Content-Type':'text/plain'});

response.end('Hello World ! n');

console.log('Request Handled');

}).listen(8080,'localhost');

console.log('Server Running !!'); 

This is pure javascript, As you are going to make HTTP request from Node.js you need handler for that, so we need to include the http module. The http module is core built-in, low-level module that is highly optimized for performance.
With the help of http object we create a server object. the creatServer function takes the anonymous function as a parameter and has request and response objects. For the sake of simplicity i am using just the response object. This example does nothing with the request object (will talk later). Using response object to write the write HTTP header in which 200 means success and plain text content type means just to tell the user format of the response gonna write in the browser. The next line respond with the ‘Hello World’ and ‘Request Handled’ message is send to the console window. After when the createServer object is created it calls the listen function with port number and IP address, in this case it is our local server with IP 127.0.0.1. The last console message to assist the user to write on the console that server is running at the moment.
Save the file with ‘any-name.js’. After you save the file run the following in command prompt to start running your server.

C:NodeExamples> Node any-name.js

Quick Info: Change your directory path in which you saved the file  
 C:> cd path 


Leave the command prompt open and open any browser and hit

http://localhost:8080/

Request has been made from your browser to the newly created server (on command prompt) you can see the response sent back from the server. Response will be writing on the browser window and similarly you can see the command prompt for log text which says :

Server Running !!
Request Handled

Yupee !! Congratulations, you have written you first Node.js website and successfully running.
You can refresh the browser window to send another request to the server and server responds with same string and will be display on the browser.
Press Ctrl+C to stop server.

Personalized Response

As you have said Hello to the whole world, now you want to say hello to the specific person who hits your server.
Next example listens the request come from the users and say hello to them. Of course, the next thing we want to do is to process the request data to produce a response based on the request.

Same as for HTTP request we included HTTP module, for request base response we need to parse the QueryString for that we require URL module which provide help for parsing the QueryString. Url object has a parse method that accepts the actual URL, and second parameter value of true parse the QueryString.

var http = require('http');

var url = require('url');

http.createServer(function (request, response) {

var parsed_url = url.parse(request.url, true);

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Hello ' + parsed_url.query.name + '!n');

console.log('Request Handled for ' + parsed_url.query.name);

}).listen(8080, 'localhost');

console.log('Server Running !!');

Save the application in ‘hello_asim.js’. Run the application and start the browser to hit the following url:

http://localhost:8080/?name=Asim

When the request is recieved successfully, you can see the response on the command prompt with something like this:

C:NodeExamples> node hello_asim.js
Server Running !!
Request Handled for Asim

And on browser window, you will see something like this:

Hello Asim
Quick Info: Return status codes:
■ 1** Informational Message
■ 2** Success
■ 3** Redirect
■ 4** Client error
■ 5** Server error

Create a Node.js Module

When ever you write code it’s best to reuse the code where possible. For usability perspective in Node.js we create modules. Module are single entity that can hold some functionality and can be reuse.
In the previous examples, require function were used to load module, which provide code reuse when developing Node.js applications. So you can create module by wrapping your code in a function and exporting it so it can be called from other code.

var http= require('http');

var url= requrie('url');

function anyFunction(){

http.createServer(function (request, response) {

var parsed_url = url.parse(request.url, true);

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Hello ' + parsed_url.query.name + '!n');

console.log('Handled request for ' + parsed_url.query.name);

}).listen(8080, 'localhost');

console.log('Server running !!');
}
exports.start= anyFunction;

In the example, code is wrapped with in a function. At the very last line, function is assigned to start property of exports object.
Save the code in ‘any_name.js’ file, and your module is created.

Create another file ‘index.js’ in which you will gonna include your newly created module and execute it, by using the require function. Enter the following code in ‘index.js’ file

var hello= require('./any_name.js');
hello.start();

The module is ‘./any_name.js’. As this is relative path that’s why we use ‘ ./any_name.js ‘ . The require function return the object that is assigned to the hello variable, and then the start method is executed.

Run the following code using command prompt.

C:NodeExamples>node index.js

This code works the same way as ‘hello_asim.js’ but this time it uses your new module.

Creating Node.js Package

Package is actually your application, it is basically the collection of your modules. Packages have dependencies over other modules and can be available publicly for others to use. You will use node package manager (npm) for publish your package or to install others package.
Package folder contains bin, and lib sub folders this is actually the typical hierarchy of the Node.js Package. With one package.json file with ReadMe.md.
bin folder contains the entry point for your application and lib folder is used for the modules files.

Practical example:

First create the following directory structure:

 packageName
     bin
     lib

Create the first module and save this to the lib folder with file name “counter.js” file name

var count=0;
function counter(){
      ++count;
      console.log(count+" Call(s) are made !");
}
module.export= counter;

First we have a count variable with counter function that will call each time you will made any call. export property of module, exports the function for the modules that wishes to call the function counter.

A next module with basic mathematics consider it as a module and save into the lib folder.

var counter = require('./counter');
function add(x, y){
counter();
return x + y;
}
function subtract(x, y){
counter();
return x - y;
}
module.exports = {
addition: add,
subtraction: subtract
}

Save this as math.js. In the newly created module in lib folder, we just reference the counter.js module so that we can use their exported function from here. As the counter module is present is the local module and present in the current folder of the package so that is why we use this ./counter.js syntax. The reference is assign to the variable counter with the help of this we can access the methods of the counter module. As counter() has been called from the add and the subtract function. From the other math module.
Same as for the math.js the two add and subtract function are exported with the help of object. Like if there is a situation where you need to export two or more function for the others modules to use, you must need to create the object for that. In this example addition represents the add function and subtraction represents the subtract function. Method name must not to be same as the function name. This won’t be necessary. You can give any method name to that.

Creating External module

After the all the modules is created, then you must need one entry point for your package so that others outsiders can access your whole packages functionality from one gateway. so for this we need to create the main.js file that can access the whole package.

var path = require('path');
var fs = require('fs');
var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
var math = require(lib + '/math.js');
module.exports = {
addition: math.addition,
subtraction: math.subtraction,
}

Save this file as main.js in the root folder.
In this module, path and fs these are the build in packages in Node.js helps us to get the path of the lib folder. These are basically helpers. Then refer to the math.js using this path.
At the end module.export assigns the object a two function that we need to exported by the package.

Creating the package.json file

Now it’s time to publish your package for the use. First you need to create the package.json file of your package so that it will become easier for the node package manager to publish your package into npmjs.org
Node package manager is already installed when you install the Node.js for quick check you can see the version number:

C:mypackage> npm -v

Type the following to generate the package.json of your package

C:mypackage> npm init

It will ask you for the values for the keys.
At the end package.json would look like this

{
"name": "mypackage",
"version": "0.0.0",
"description": "My first package",
"main": "bin/main.js",
"repository": "",
"keywords": [
"math",
"addition",
"subtraction",
],
"author": "khawaja Asim",
"license": "AFL-1.1"
}

Create account

Once you have done with the package.json file it’s time to publish the package but before going for the publish create the account in the npmjs.org manually or you can create account using the cmd node package manager. Type the following to add new user:

C:mypackage> npm adduser

Once you created the account now are able to publish the package.

Publish the package

As your package.json file is ready and you are already logged in. You are all setup for going for the publish. It’s time for the world to see your talent, it’s time for the world to see your first ever package you have developed. It’s time to get the applause 😉

Type following in the cmd to publish your package. Remember you must be in the root where package.json file is saved and others package folders.

C:mypackage> npm publish

Install and Use the package

As your package is published you can install and use your package now. You can install the package globally or local for specific application. Installing package globally gives all the application same version, whereas for locally installed you must have to install for each application and same for the updates.

To install the package locally

C:installedpackage> npm install mypackage

For globally:

C:installedpackage> npm install -g mypackage

Now you have install package you just publish in the registry then write some code that access the installed package and access it’s methods. Create the main.js and write this code:

var math = require('mypackage');
console.log();
console.log('addition(2,14)'+ math.addition(2,14));
console.log();
console.log('addition(25,19)'+ math.subtraction(25,19));

The code requires the package and access it’s main file. You can run this by typing following in command prompt:

C:installedpackage> node main

Output

You will get this kind of output when you run the main file using command prompt:

C:installedpackage> node main
1 Call(s) are made!
addition(2,14)= 16
2 Call(s) are made!
subtraction(25,19)= 6

UnInstalling the package

You can also install the package from the local directory by just typing this command in command prompt window:

C:installedpackage> npm uninstall mypackage

To uninstall a global package:

C:installedpackage> npm uninstall -g mypackage

There you go !
That’s all from my side, must go for this create the little more complex applications and share with the community so it’ll help others to learn from you.

I will wait for your comments and suggestion, do suggest changes if you find any.
Thank You !

What do you think of this tutorial?
We want to hear from you! Please leave us a comment below and if you have any query please ask.
Experts are waiting for your queries ;) Cheers ! 
read more
AsimNodeJS – Kickstart

WordPress useful Plugins

This list contains most useful plugins for WordPress for various purposes, including development, debugging, management, writing, etc.

Best WordPress Plugins for Developers

Essential plugins for developers include:

  • WP-Server : To show the current server load
  • WP-Downloader : To download any plugin or theme directly from within WordPress dashboard
  • Adminer : A fully functional phpmyadmin inside WordPress admin dashboard
  • W3 Total Cache : One of the best minification and cache plugin for WordPress
  • Easy WP SMTP : For sending contact or comment reply mail through a different server from the one your site is hosted on, using SMTP
  • HTACCESS editor : To edit htaccess file right with in your WordPress dashboard
  • WP-Filemanager : One of the rare entity, a functional file manager for current version of WordPress (4.4.1 at the time of writing)
  • Theme My Login : A plugin to not only theme and give url to your WordPress login and related pages, but also help in securing it (needs more info and knowledge though, beyond the scope of this post)
  • NoSpamNx : helpful in preventing spam without adding a lot of load on the server, however might not be sufficient in some cases, but try it as first line of defense.
  • Broken Link Checker : Does what its name says!
  • Comment Email Reply : Sends an email to the commenter when someone replies to him, including admin
  • Disable Trackbacks : Make your life easy by disabling trackbacks and pings!
  • PS Auto Sitemap : Create a post with all the sitemap links, good for SEO, sometimes!
  • WP First Letter Avatar : I prefer it instead of blank image when the user doesn’t have any avatar at gravatar!
  • Backup – https://wordpress.org/plugins/backup-wp/
  • SSL fixing: ssl-insecure-content-fixer

These plugins might come in other categories too.

How to load all images from Photon (wordpress cdn for images)

To load the images on your site using the wordpress official cdn, add this code to your functions.php file:

function callback($buffer) { 
 $buffer = preg_replace("/(<img[^>]+?//)(.+)?([^>]+?)/", "$1i1.wp.com/$2$3", $buffer);
 return $buffer; 
}
function buffer_start() { ob_start("callback"); } 
function buffer_end() { ob_end_flush(); }
add_action('after_setup_theme', 'buffer_start');
add_action('shutdown', 'buffer_end');

Debug WordPress

For debugging, add this code to wp-config.php (make sure that the same settings aren’t repeated after this code)

define ('WPLANG', '');
define('WP_DEBUG', false);
//define('WP_MEMORY_LIMIT', '1024M');
ini_set('log_errors',TRUE);
ini_set('error_reporting', E_ALL);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);
define('ip_POST_REVISIONS', 5);
define('AUTOSAVE_INTERVAL', 300);
define('EMPTY_TRASH_DAYS', 3);

Anyway, we’ll be revising this list and improving plus expanding it too. The plugins will be explained further too with images.

Add your feedback or suggestions in the comments regarding the best WordPress plugins for various purposes!

read more
khanWordPress useful Plugins

PowerShell -From Noob to Ninja

I have searched and read many articles about Windows PowerShell but did not find any comprehensive article that take you from basic to advance knowledge specifically related to Internet Information Server and PowerShell Remoting. So i tried to make things easy for you, lets get started

This article is about

  • Introduction
  • Extensions
  • Basics
  • Cmdlets
  • Working with IIS
  • Working with Windows Servers/VMs
  • Deep dive into PowerShell Remoting

You can download it from here

Introduction

Advancing command prompt, Microsoft released Windows Powershell in 14th November 2006, designed by Jeffrey Snover, Bruce Payette and James Truher providing more interactive, powerfull, Multi-paradigm that includes Imperative, pipeline, object-oriented, functional, reflective, providing strongly typed and type safe implicit and dynamic environment. The stable version was released on 29th July, 2015.

Extensions

Following are the supported extensions in powershell

  • .ps1 for Script
  • .psc1 for Console file
  • .psd1 for Data file
  • .ps1xml for XML Document
  • .psm1 for Script Module
  • .pssc for Session Configuration File
  • .cdxml for Cmdlet Definition XML Document

Basics

PowerShell introduced over hundreds of new commands to make powershell more powerful. There are many command that are same as MS-DOS commands.

Hello World

The tradition of programming forefathers is “Hello World”. How we can start without it, So to write this on your terminal use

PS C:> Write-Host Hello World

or

PS C:> echo Hello World

You can create variables in powershell by using $ sign for example

PS C:> $message = 'Welcome to PowerShell'

and then print that variable using

PS C:> echo $message

Getting used to with help is most important in be an expert. To get help in powershell use

PS C:> get-help

You can use get-help command by passing arguments too. For example to get help specifically for “dir” (explained below) use can use

PS C:> get-help dir

This will give you detailed description about using dir command, its name, its syntax, aliases and remarks. For the above command it will give you

  • Name: Get-ChildItem
  • SYNTAX: Get-ChildItem [[-Path]…….
  • Aliases: gci, ls, dir
  • Remarks: Get-Help cannot find files……..

To open the Microsoft site that explains the key word you want to get help of in browser use

PS C:> get-help dir -online

Manipulation with Directories

To list all the item that are in the current directory use the same command as in MS-DOS

PS C:> dir

To change the current directory use the same command as in MS-DOS

PS C:> cd d:

CD stands for Change Directory
To go backwards from current directory again use the same command as in MS-DOS command.

PS C:> cd..

To navigate back to the root directory use

PS C:> cd

you can also use alternative to goto specific directory

PS C:> Set-Location D:

or

PS C:> Set-Location 'D:New FolderNew Folder'

To make new directory use

PS C:>md testDirectory

To delete directory use

PS C:> del testDirectory

System Information

You can get the machine name by using

PS C:> [System.environment]::MachineName

Getting the directory of command line (powershell)

PS C:> [System.environment]::CommandLine

To get the information that whether you system is 64-Bit or not use

PS C:> [System.environment]::Is64BitOperatingSystem

Getting Operating system version use

PS C:> [System.environment]::OSVersion

To get current user name use

PS C:> [System.environment]::UserName

Network Information

Same as MS-DOS you can get your network information using

PS C:> ipconfig

For specifically getting IP address and its detailed information you can use

PS C:> Get-NetIPAdress

or

PS C:> Get-NetIPAdress |  Format-Table

or to only get a single property of IP Address use

PS C:> Get-NetIPAddress | Format-Table -Property IpAddress

for getting mac address you can use

PS C:> GetMac

Looping

To execute loops in powershell use

PS C:> 1..2 | % { // Do Stuff here }

For example

PS C:> 1..2 | % { echo 'In-Loop' }

or

PS C:> 1..2 | % { GetMac }

Cmdlets

There are special commands in powershell that are called cmdlets. They are always typed after the prompt and execute on pressing enter. Cmdlets follow the naming convention of “Verb-Noun”. Cmdlets actually return the object but it appears that they are writing in console. The method of passing cmdlets returned object to another cmdlets is called piping
For example
This will give you the operating system version

PS C:> [System.environment]::OSVersion

but you want to pass this to another cmdlet as an input to display a list for you. For this you will be doing

PS C:> [System.environment]::OSVersion | Format-List

In above command the symbol “|” is piping sign. The above command will get the output of first command and pass it as a pipeline to the second command as an input, So result will be displayed by the second command not the first one.
Few other examples are

PS C:>dir | Get-ItemProperty | Format-List

or use can pass the output of second pipeline to the third and write its output in the text file for example

PS C:> Get-NetIPAddress | Format-Table | Out-File 'D:powerShellOutput.txt'

Working with IIS

To start with remoting we need to import a web administration module, to do that use

PSc C:>Import-Module 'WebAdministration'

May be you wont need that if already imported to check that if module already installed or not use

PS C:>Get-Module -ListAvailable

above command will list all the installed modules in it and you need to search for the web administration module. To make it quick command written below, this will only give you the module information of the given name if it exists

PS C:> Get-Module -ListAvailable webadministration

To get Web Administration related cmdlets use

PS C:> Get-Command -Module WebAdministration

or to be specific for website related cmdlets use

PS IIS:> Get-Command -Module WebAdministration -Noun '*website*'

Changing to IIS directory

To change the current directory to IIS use

PS C:> IIS:

This will change you working directory from local drive to IIS and will now looks like

PS IIS:>

If you check all the directories in IIS by using dir/ls/gci you will get Sites, WebApplications ApplicationPools, and other directories.

PS IIS:> ls

Now change you current directory to Site by using

 PS IIS:> cd Sites

Working with Site in IIS

to view all sites try listing all sites in it by using

PS IISSites:>dir

you will get all the list of already created sites whether they are stopped or running. To get details of specific site use the site name as an argument with the below written command

PS IIS:Sites> Get-Item 'TestSite'

or to be very specific use

PS IIS:Sites> Get-Item 'TestSite' | Select-Object *

To Start a site use

PS IIS:Sites> Start-WebSite 'TestSite'

and to stop it use

PS IIS:Sites> Stop-WebSite 'TestSite'

Creating New Site

PS IIS:Sites> New-Item TestSite

The above command will create the new site but there are many other information associated with the site you need to configure that too, So let use the complete command and i will explain it after that

PS IIS:Sites> New-Item IIS:SitesTestSite -Bindings @{protocol="http"; bindingInformation=":80:www.TestSitePowerShell.com"} -physicalPath C:inetpubwwwrootnewFolder

In above site you are specifying Bindings, Protocol and Physical path. Protocol can be ‘ftp’, ‘https’ or what ever your requirements are. Binding Information include the port number and the binding address that you want to give to a site and physical address the the path of the folder where it physically located in the drive.

Updating properties of Site

To update properties of existing site for example to update binding information of a site or a protocol or port number or physical address the command that is used is

PS IIS:Sites> Set-ItemProperty IIS:SitesTestSite -Name bindings -Value @{protocol="http";bindinginformation="*:80:www.abc.com"}

In above command we use Set-Property to Update property of the element and then we will specify the name of the property that we are updating in above case we are updating bindings and then we are providing its new values

Adding new properties

To add new properties to existing site we use the command written below

PS IIS:> New-ItemProperty IIS:SitesTestSite -Name bindings -Value @{protocol="http";bindinginformation="*:8080:www.xyz.com"}

The above is the example in which i assume that the site is already created but its binding properties are not given at the time of creation, so we are adding it now. Its simple, we just need to use New-Property function with Property name and its values as an argument.

Removing properties

To remove/Clear specific property form existing site use

PS IIS:> Clear-ItemProperty IIS:SitesTestSite -Name bindings

Given the Name of the Property it will be removed from the specified object given as a first argument of the Clear-Property function

Renaming the Site

To rename the site use

PS IIS:> Rename-Item IIS:SitesTestSite TestSiteFromPowerShell

Deleting Site

To delete site from IIS use

PS IIS:Sites> Remove-Item 'TestSiteFromPowerShell'

Working with Servers/VMs

Now that seems thrilling but let me surprise you. To work with any Virtual Machine you just need to connect with it and then you are able to do whatever we have already done above. So lets connect to the server

PS C:> Enter-PSSession -ComputerName abc.xyz.net -Credential abc.xyz.netusername -UseSSL

You need to run this and then a password dialog prompt appears, Enter your password and that all you need to do. You are now connected with the server, for example

[abc.xyz.net]: PS C:UsersusernameDocuments>

you can run same command that to get information like

[abc.xyz.net]: PS C:UsersusernameDocuments> dir
[abc.xyz.net]: PS C:UsersusernameDocuments> Get-NetIPAddress
[abc.xyz.net]: PS C:UsersusernameDocuments> cd
[abc.xyz.net]: PS C:> Write-Host 'Welcome to the Virtual Machine'

You can create sites remotely using powerShell on your servers. Now we are done with commands, lets develop some scripts to see the strength of powershell. Below is the example of a powershell script that creates a new ApplicationPool, create new physical directory and then creates a site in it with all the relevant configuration.

Import-Module WebAdministration
$dirName = 'PowerShellMagic'
$siteName = 'PowerShellSite'
$poolName = 'DemoPool'
New-Item C:inetpubwwwroot$dirName -ItemType Directory
New-Item IIS:Sites$siteName -Bindings @{protocol="http";bindinginformation="*:80:www.firstapplication.com"} -PhysicalPath C:inetpubwwwroot$dirName
New-Item IIS:AppPools$poolName
Set-ItemProperty IIS:Sites$siteName -Name applicationPool -Value $poolName
Write-Host "All Done"

Before executing the above script, You need to make sure that your powershell is configured to run multi-line scripts. For this first check your execution policy by running the following command

[abc.xyz.net]: C:> Get-ExecutionPolicy

if the above command gives you the output of “RemoteSigned” then you are good to go for executing scripts otherwise run the following command

[abc.xyz.net]: C:> Set-ExecutionPolicy remotesigned

Save the above written script with any name, i am using siteSetup.ps1. Let execute the script

[abc.xyz.net]: C:> Invoke-Expression D:setupSite.ps1

or

[abc.xyz.net]: C:> .setupSite.ps1

Deep dive into PowerShell Remoting

Let’s dive more deepen into PowerShell remoting.

Legacy VS PowerShell Remoting

In legacy approach all the commands will execute in sequential manner that may take a huge time in many scenarios.
For example: you have 10 servers and you want to configure few setting on them remotely and then you want to deploy you application on them.
In the scenario explained above legacy approach will take a lot of time as already explained it executes your commands or scripts sequentially.
So there comes the power of PowerShell remoting where you can do all this in parallel for all 10 servers. Yeah! That’s cool.

Protocols

One other aspect that I want to share is the underline protocols used.
Legacy approach use DCOM or RPC protocols whereas PowerShell remoting use WSMan protocol.
DCOM and RPC protocol are designed in the era where the firewall concept was not well grown so these protocol were designed with not considering the firewall concept in mind that means they are not firewall friendly and if you are using these any services that uses these protocols then you need a lot of complex firewall configurations. Moreover the security in these protocols are questionable and I addition to this they may not work with cloud based environment. Keeping the above scenario in mind where you are running a long scripts on multiple server all these scripts would process locally.
Contrary to that approach powerShell uses WSMan protocol that is based on “Industrial Standard Network Protocol” and is managed by WinRM services is a firewall friendly and designed in keeping the firewall concept in mind. That mean you don’t need any kind of complex firewall configuration. They are secured and all the communication is encrypted, so no packet sniffing using any tool like wireshark. They connect over a single port that is 5985 but you can configure SSL over 5986 and uses Kerberos authentication. In addition to this they are ideal for cloud environment and they process the scripts remotely. They connect to a defined endpoints where service listens to incoming connection and the endpoint passes the control to the defined application (PowerShell). PowerShell needs admin privileges for managing all the stuff you are doing remotely.

PSSessions

PSSession are used to make a connection between 2 machines. These sessions are maintained at the remote end with powerShell runspace for running cmdlets functions and scripts.
There are many types of PSSessions

  • Interactive PSSessions
  • Disconnected PSSessions

Enabling PSRemoting

To configure remoting you need to start the service named WinRM and discussed above. So we will configure WinRM to auto start. To do that use

[abc.xyz.net]: C:> Start WinRM

Then to enable remoting use

[abc.xyz.net]: C:> Enable-PSRemoting –Force

To test the connectivity and WinRM is running use

[abc.xyz.net]: C:> Test-WSMan 

You may need to restart the machine to properly pick the configuration, for that use

[abc.xyz.net]: C:> Restart-Computer computername.net –Force –Wait WinRM –Credentials

The above command will wait for the WinRM service to start and then will show its status
To disable remoting use

[abc.xyz.net]: C:> Disable-PSRemoting 

One-TO-One Remoting

One to one remoting is the case where you have only one server that you want to connect with and want to do some actions. For that lets have an interactive session with the server.

[abc.xyz.net]:  C:> Enter-PSSession –ComputerName comutername.net –Credential username –UseSSL

This will prompt the dialogue where you will enter your password to connect.
Now we are connected with the server remotely with interactive session. All the command that you execute are processed remotely and only return the result in de serialized XML objects.
To check the user session use

[abc.xyz.net]:  C:> Get-Process wsmprovhost –IncludeUserName | Select Username, startime

To get Installed Windows Features on Server use

[abc.xyz.net]:  C:> Get-WindowsFeature web* | where installed

To getting Running Windows Services use

[abc.xyz.net]:  C:> Get-Service | Where { $_.status –eq ‘Running’ }

To get specific Service use

[abc.xyz.net]:  C:> gsv WinRM

To getting installed Modules use

[abc.xyz.net]:  C:> Get-Module web* -List

To get all process use

[abc.xyz.net]:  C:> Get-Process

To filter the process result use

[abc.xyz.net]:  C:> Get-Process | sort WS –Descending | Select –First 5

PSSession

As mentioned above the Enter-PSSession is an interactive session that we have used above to connect to server. But there are also other kind of sessions. lets discuss them

New-PSSession

Using this we can save the session in a variable to use that in future and connect to it whenever we want to

PS C:> $s = New-PSSession -ComputerName abc.xyz.net -Credential username -UseSSL

Now you can connect to this session whenever you need to like

PS C:> Enter-PSSession -Session $s 

In this approach the command

[abc.xyz.net]:  C:> Exit

cannot remove the session.
You can also execute scripts and command using this session variable like

[abc.xyz.net]:  C:> icm -ScriptBlock { $p = Get-Process | Sort WS -Descending } -Session $s 

and print them in other script because the scope of variable $p is stick to the Session variable now that is $s in this case. these variables are created on the remote site. So if you want to use $p locally or in other session other then $s you cannot get it because $p is only created on one server yet.
SO ultimately that mean you can use the variable created before in future commands like below we are printing the result from the variable that we created in previous command

[abc.xyz.net]: C:> icm -ScriptBlock { $p[0..4] } -Session $s 

The above command is not possible without “-Session $s” because $p only exist in the $s session

You can get deserialized XML or version of Process from server by using

PS C:> icm -ScriptBlock { $p[0] } -Session $s | Get-Member 

Removing Session

To remove this offline kind of session use

PS C:> Remove-PSSession -Session $s 

One to Many Remoting

Fanning out

To connect with many server form one machine is knows as “Fanning out”.
Lets take an example that we have all server names in a text file, Lets read them

$computer = get-content D:computers.txt | New-PSSession –Credential username

Now you have all the server names in a variable $computer.
Lets now execute a script in all servers.

PS C:> Invoke-Command –ScriptBlock {get-service wuauserv } –Session $computer

The above command will take the sessions from $computer variable and execute the script/command on each of the server. or you can pick a script from local drive and execute it on all servers

PS C:> Invoke-Command –filepath D:script.ps1 –Session $computer

One thing to remember that you can use/pass local variable to server as demonstrated below

PS C:> $log = 'System' 
PS C:> icm { Get-EventLog $using:log -Newest 5 } –ComputerName $computer

Or pass by creating function and passing parameter

PS C:> $sb = {param($log, $count) Get-EventLog $log -Newest $count} 

here $sb is the function that we have defined that takes two arguments, lets call it

PS C:> icm $sb -ArgumentList "System", 3 

Background Jobs

If there are some scripts that takes time and you have like 10 servers, so you prefer to use the background jobs to do the task

PS C:> icm { Get-HotFix } -Session $computer -AsJob | tee -Variable hot 

In above statement we are executing a command “Get-HotFix” as a Job defined by “-AsJob” and passing its output in variable named “hot”. once the execution is done we can fetch result from this variable, lets check the status of that Job

 PS C:> $hot 

or

PS C:> $hot.childjobs  

We canalso wait from the specific job to complete by using

PS C:> Wait-Job $hot 

lets receive data from that job

PS C:> $result = Receive-Job $hot -Keep 
PS C:> $result.count 

The function that we have created before named “$sb” run locally, lets redefine the function and run it remotely as a Job

PS C:> $sb = { Start-Job { Get-EventLog system -EntryType Error } -Name SysErr }

We have defined the function as a Job and named it “SysErr”, lets execute it

PS C:> icm $sb -Session $computer

When you get the status of this job. you should get same ids on all servers because this is not running on servers. By running locally you will get unique id’s for all server and that is obvious. To get status of this job use its name

PS C:> icm { get-job SysErr } -Session $all 

You can measure the command execution time using

PS C:> Measure-Command { Get-Service }

Removing all PSSessions

To remove all alive sessions use

PS C:> Get-PSSession | Remove-PSSession 

Adding Server as a Trusted Host

PS C:> $cred = Get-Credential abc.xyz.net 

PS C:> Get-Item wsman:localhostclienttrustedhosts 

PS C:> Set-Item wsman:localhostclienttrustedhosts -Value abc* -Concatenate 

PS C:> test-wsman codingbots.cloudapp.net -Authentication Default -Credential $cred 

2nd Hope Problem

If you are on server A and creates a PSSession to connect to server B. That is the first hope. Moving further if you want to connect to Server C from Server B that will be your 2nd hope and that says “Operation failed”. This is because powershell do not allow server B to delegate your credentials to other machines. But you can enable it using the following configuration.

PS C:> icm { Get-WSManCredSSP } -computername c
PS C:> enable-wsmancredssp -Role Client -DelegateComputer server2 

It is considered as a besk practice to disable multi hoping whenever you are done with your tasks. To do so, use

PS C:> Disable-WSManCredSSP -Role Client 
PS C:>  icm { Disable-WSManCredSSP -Role Client } -computer abc.xyz.net 

That is it from my side. I hope you have enjoyed stepping into the world of Windows PowerShell.
Feel free to contact.

Happy Coding 🙂

read more
Danyal MalikPowerShell -From Noob to Ninja

Linux Commands

This page lists the most common usage commands while operating a linux.

How to empty a file

To empty a file, text, log or any other, of its content, while keeping the file there, we can either open the file and remove all the content in it, or we can use a simple command:

>filename

Simply write “>” and then write the file name. Make sure you’re in the directory where this file is located.

Can this work by giving path to the file? (not confirmed by me, check and update).

List all files with details

Listing all files takes “ls” while for listing all files with details including file permissions, owners detail, file size and last modified date, use this command:

ls -l

This will simply list all the files in selected or current directory.

SSH to server with custom port

To ssh to a server, use this command:

ssh -p 22 user@domain_or_ip

You can skip the “-p 22” part if the port is default, that’s 22. (-p means port and 22 means the port number).

However, make sure you keep the same sequence, you can’t add the port after the user and domain part.

How to delete a file

Delete or remove a file by simply using this command:

rm filename

The “rm” command followed by file-name that we need to be deleted.

How to rename a file on terminal

Renaming a file on terminal, on linux or mac os x, can be confusing for some people, however it’s pretty simple.

You simply have to use the command for moving the files, like this:

mv initial-file-name destination-file-name

The command will rename the file, in the same directory, not necessarily moving it to any other folder.

How to search files above specific size in linux

You can search for the larger files, above specific file size, using this command:

find /directory/path/ -size +20M

This command will find files in our specified folder, that are 20MB or above. (MB or Mb?, I guess MB, confirm and update)

How to zip a file on ubuntu terminal

On ubuntu or any other linux or mac os x, with zip installed (if not, then: apt-get install zip), use this command to zip all the files in a folder:

zip -r newzipname.zip foldertozip/

-r will zip all the files in it recursively.

How to CHMOD permissions recursively

Simply follow this:

chmod -R 755 folder/path/

This will set this permission for this folder and all files and folders inside it too.

Check:

Which version of centos installed: cat /etc/issue

If nginx installed: nginx -v

If memcached installed: php -m | grep memcache

For all php modules: php -m

read more
khanLinux Commands

SiteLock

SiteLock.com provides security and performance services for your websites. It works by pointing the dns to their server and then adding your web hosting server ip in sitelock dashboard where your website is located.

How to disable sitelock temporarily

There can be some situations when we might need to turn off sitelock truespeed acceleration temporarily to allow various things. For example:

  • When adding headers to your files to be cached by cdn (amazon cloudfront as an example) with those headers, to allow them to be called by any domain or anything else you need in them

To turn off sitelock protection through trueshield and truespeed, follow these steps:

  1. Login to sitelock account
  2. Go to settings from top menu
  3. On the settings page, select your domain for which you want true speed to be disabled in your site lock account
  4. On that website settings, select “TrueShield & TrueSpeed Settings”
  5. On the settings page for trueshield and truespeed, click on “Temporarily ByPass SiteLock’s network”
  6. Click “Save Settings” to save the settings

disable-sitelock-trueshield-bypass

Note that this page have options to enable or disable true speed acceleration or true shild protection only too. Disabling true speed only might work in some types of situations too, however disabling sitelock completely like explained above might be needed for various tasks. So if in doubt, chose to temporarily bypass sitelock’s network and then enable it when desired tasks are done and results achieved.

Update:

I’ve noticed that clicking on “temporarily bypass sitelock’s network” might cause some issues on your site like a redirect loop.

The solution is not to temporarliy bypass the sitelock’s network, rather uncheck both trueshield security and truespeed acceleration from the option next to it. This will disable the cache and other functions of sitelock while not putting your site into a redirect loop.

read more
khanSiteLock

Slack

These are the instructions to setup and install slack and configure it for better usage.

What is slack?

Slack is a team communication system that allows conversation in:

  • Public channels
  • Private channels
  • Direct messages (we will call it DM)

How is it different from skype and others?

There are various reasons why we’ve choose slack over skype and other communication methods. Although we will still be using skype for calls and various purposes, but slack will be our main mode of communication.

Main reasons include:

  • Offline messages better than skype
  • Notifications can be customized and only relevant ones will disturb you
  • Both members don’t need to be online to transfer the files
  • Images are transferred in a better way, with a preview, so you don’t need to download and all to view them
  • Many integrations are possible in slack, allowing it to compile and sum up a lot of things going around us, including:
    • project updates from visual studio and others
    • email updates (not configured in our setup yet, will be done soon)
    • custom integrations through json

Setting up and configuring Slack

Follow each step in sequence, don’t jump please.

  1. You’ll receive the invitation email from the admins, use that to sign up to the slack. Save the url being used for slack.
  2. Download desktop client for slack from https://slack.com/downloads
  3. Download and install mobile app for slack for your mobile
  4. Once sign up is complete and you are logged in successfully:
    1. Edit your slack profile and update it with your name, image, number, etc.
    2. Add your office skype id to your profile info in slack, this step is important
    3. Edit the preferences for slackedit-slack-preferences
    4. Edit the preferences as per your requirements, however the ones I use are(details under image):slack-notification-preferences
      1. Change desktop notifications to: “only for highlight words and direct messages”
        • this helps in reducing unnecessary messages in various channels that might not be of your concern
        • if someone direct messages you or mentions you or any important word in channel, you will get a voice notification
        • you can add custom words separated by commas that are important to you and you will get notified when someone mentions them
      2. Enable: display message text in desktop notifications to get the preview of messages, so that you can decide if they’re worth opening
      3. Change the notification sound to your choice
    5. You can make changes to various other things, including that I prefer compact look, you can chose the one you like, etc.
    6. Let me know if you have any query

When using slack, when you type in the input box, you can add various types of text and change its formatting. Various ways to do that are mentioned just under the input box and appears when you start typing, like this:

slack-writing-tips

They appear after the third character is typed.

read more
khanSlack
custom-icon-clipboard11.png

Friends Planet

Coding Bots released its new windows 8.1 application named “Friends Planet“. Keep you friends very closer to you. 🙂

Download it from here, Don’t forget to give your feed back use rate and review for that.

read more
Danyal MalikFriends Planet
custom-icon-mobile11.png

Working With XAML 2/4

Those people, who have not been following us from the beginning, can go back to start at the beginning.

Grids:

When we talk about grids, the first thing that comes to our mind is the concept of rows and columns. So, grids are basically dividing the whole page into rows and columns. This is the most flexible control in XAML that is used for arranging different elements on different locations on the screen. A grid’s columns and rows make cells and we place elements in these cells.

Example:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50*" />
        <RowDefinition Height="50*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50*" />
        <ColumnDefinition Width="50*" />
    </Grid.ColumnDefinitions>
    <TextBox Text="1st row 1st column" Grid.Column="0" Grid.Row="0" />
    <Button Content="1st row 2nd column" Grid.Column="1" Grid.Row="0" />
    <TextBox Text="2rd row 1st column" Grid.Column="0" Grid.Row="1" /> 
    <Button Content="2rd row 2nd column" Grid.Column="1" Grid.Row="1" />
</Grid>

The output of the above code is shown below:

Grid rows and columns

In the above code, we have divided the screen into 4 cells of equal height and width, and placed four elements (i.e. textboxes and buttons) in these cells.

To place element(s) in any of the grid cell, we have to write that element after rows and columns definitions and before closing tag of grid i.e.  “</Grid>”. Then write

Grid.Row="1" Grid.Column="1"

as a property of that element as shown below. The button, in this case, will be placed in the bottom right cell (2nd row, 2nd column) of the grid with two rows and two columns.

<Button Content="Submit" Grid.Row="1" Grid.Column="1" />

The value of the “Height” property in “RowDefinition” tag can be given in the following notations:

  • Height can be defined as “*” meaning percentage; for example, Height=”40*” and Height=”60*” means that you have divided the screens into 2 rows, one with 40 percent height of the whole screen and the rest 60 percent is allocated to the other row.
  • You can use Height=”Auto”, this means that you are currently giving zero height to that row but as you place an element (let’s say a button) in this row then the row automatically sets its height equal to the height of the element placed in it.
  • You can also define this property as Height=”200″, which means a height of 200 pixels. But this is not recommended to use because this will not give responsive behavior for the layout.

You can also have multiple grids or StackPanels or any other container or element inside the grid cells. Below is the example of the nested grid and StackPanels inside grids

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50*" />
        <RowDefinition Height="50*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50*" />
        <ColumnDefinition Width="50*" />
    </Grid.ColumnDefinitions>

    <Grid Grid.Row="1" Grid.Column="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="50*" />
            <RowDefinition Height="50*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50*" />
            <ColumnDefinition Width="50*" />
        </Grid.ColumnDefinitions>
 
        <TextBox Text="1st row 1st column of child grid" Grid.Column="0" Grid.Row="0" />
        <Button Content="1st row 2nd column of child grid" Grid.Column="1" Grid.Row="0"/>
        <TextBox Text="2nd row 1st column of child grid" Grid.Column="0" Grid.Row="1" />
        <Button Content="2nd row 2nd column of child grid" Grid.Column="1" Grid.Row="1"/> 
    </Grid>
    <TextBox Text="1st row 1st column of parent grid" Grid.Column="0" Grid.Row="0" />
    <TextBox Text="1st row 2nd column of parent grid" Grid.Column="1" Grid.Row="0" /> 
    <Button Content="2rd row 2nd column of parent grid" Grid.Column="1" Grid.Row="1" />
</Grid>

The output for the above code is shown below:

nested grids

Note: Grid.Row=”0″ means 1st row, as the indices of the rows and columns start with zero.

In the above example, we made a grid with 2 rows and 2 columns, placed another grid in its 2nd row and 1st column (bottom left cell) and created two rows and two columns inside that cell (i.e. nested grid). You can also place StackPanel or any other element inside any of the cell.

Here is the code for the grid having another grid and stackpanel in it:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50*" />
        <RowDefinition Height="50*" />
    /Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50*" />
        <ColumnDefinition Width="50*" />
    </Grid.ColumnDefinitions>
 
    <Grid Grid.Row="1" Grid.Column="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="50*" />
            <RowDefinition Height="50*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50*" />
            <ColumnDefinition Width="50*" />
        </Grid.ColumnDefinitions>
 
           <TextBox Text="Row 1, column 1 of child grid" Grid.Column="0" Grid.Row="0"/>
           <Button Content="Row 1,column 2 of child grid" Grid.Column="1" Grid.Row="0"/>
           <TextBox Text="Row 2, column 1 of child grid" Grid.Column="0" Grid.Row="1"/>
           <Button Content="Row 2, column 2 of child grid" Grid.Column="1" Grid.Row="1"/>
        </Grid>
        <StackPanel  Grid.Column="0" Grid.Row="0" >
            <Rectangle Width="200" Height="100" Fill="Green" />
            <Rectangle Width="200" Height="100" Fill="Blue" />
            <Rectangle Width="200" Height="100" Fill="Red" />
        </StackPanel>
        <TextBox Text="Row 1, column 2 of parent grid" Grid.Column="1" Grid.Row="0" />
        <Button Content="Row 2, column 2 of parent grid" Grid.Column="1" Grid.Row="1" />
</Grid>

Now you have seen the use of grids yourself and you may have noticed that grids are very flexible for designing layouts. So practice them and start using them as they are very dynamic in nature.

Thank you for reading 🙂

read more
Danyal MalikWorking With XAML 2/4
custom-icon-wayfarer11.png

Working with XAML 1/4

Who should read this article:

Any one who wants to work with the following that are listed below or anyone who is a beginner in them, should read this article.

  • Windows 8/onward Development using C# & XAML
  • Windows Phone 8/onward Development using C# & XAML
  • Windows Presentation Foundation (WPF)

What is XAML:

Microsoft developed Markup language named XAML is an abbreviation of “Extensible Application Markup Language”. which is pronounced as “zamel”. Used  for developing front end of Windows RunTime applications, Silver light application and WPF application. You can read more from Microsoft website.

introduction xaml

Lets Start Working:

Following are the default controls in XAML:

  • TextBox
  • TextBlock
  • Slider
  • ProgressBar
  • ProgressRing
  • Button
  • CheckBox
  • RadioButton
  • HyperlinkButton
  • ToggleSwitch
  • PasswordBox
  • RichEditBox
  • ComboBox
  • ListBox
  • Image
  • ToolTip
  • Popup

Some of the layouts are listed here that we will cover in this article:

  • Stack Panel
  • Canvas
  • Grid
  • Grid View
  • List View

Stack Panel:

As it is clear from the name, all items in this container will be stacked together either vertically or horizontally. By default, all items in stack panel are aligned vertically.

        <StackPanel>
            <!-- Item 1 here -->
            <!-- Item 2 here -->
            <!-- Item 3 here -->
        </StackPanel>

These items can be any thing; for example, button, textbox, textblock, stack panel, grid etc.

        <StackPanel>
            <Button Content="Button one" />
            <Button Content="Button two" />
            <Button Content="Button three" />
        </StackPanel>

The output for the above code is:
Stack panel layout

 

If we set the property of Orientation to Horizontal,

<StackPanel Orientation="Horizontal">
........
....

Then the output will be:

horizontal stack panel

For alignment of the stackpanel itself you can use two important properties listed below with values

  • HorizontalAlignment
    • Center
    • Left
    • Right
    • Stretch
  • VerticalAlignment
    • Botton
    • Center
    • Stretch
    • Top
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" >
.....
...

Here is another code with output for your better understanding:

        <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" > 
            <Button Content="Button one" />
            <StackPanel Orientation="Horizontal">
                <Button Content="Button two" />
                <Button Content="Button three" />
            </StackPanel>
        </StackPanel>

Here is the output:

nested stack panel

You can read more here. Stay tuned for further details.

read more
Danyal MalikWorking with XAML 1/4